From 20d6b202d5e31f6cd040e73924036f9600112dad Mon Sep 17 00:00:00 2001
From: Gokul Soumya <gokulps15@gmail.com>
Date: Wed, 16 Jun 2021 21:41:54 +0530
Subject: [PATCH 01/31] Fix cursor position bugs related to o and O

- `O` at the beginning of file didn't move cursor
- `o` and `O` messed up cursor position with multiple cursors

Fixes #127
---
 helix-term/src/commands.rs | 70 ++++++++++++++++++++------------------
 1 file changed, 36 insertions(+), 34 deletions(-)

diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index c80716d4..59ae0e79 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1495,53 +1495,55 @@ fn open(cx: &mut Context, open: Open) {
     enter_insert_mode(doc);
 
     let text = doc.text().slice(..);
+    let contents = doc.text();
     let selection = doc.selection(view.id);
 
     let mut ranges = SmallVec::with_capacity(selection.len());
+    let mut offs = 0;
 
-    let changes: Vec<Change> = selection
-        .iter()
-        .map(|range| {
-            let line = text.char_to_line(range.head);
+    let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
+        let line = text.char_to_line(range.head);
 
-            let line = match open {
-                // adjust position to the end of the line (next line - 1)
-                Open::Below => line + 1,
-                // adjust position to the end of the previous line (current line - 1)
-                Open::Above => line,
-            };
+        let line = match open {
+            // adjust position to the end of the line (next line - 1)
+            Open::Below => line + 1,
+            // adjust position to the end of the previous line (current line - 1)
+            Open::Above => line,
+        };
 
-            let index = doc.text().line_to_char(line).saturating_sub(1);
+        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(
-                doc.language_config(),
-                doc.syntax(),
-                text,
-                index,
-                true,
-            );
-            let indent = doc.indent_unit().repeat(indent_level);
-            let mut text = String::with_capacity(1 + indent.len());
-            text.push('\n');
-            text.push_str(&indent);
-            let text = text.repeat(count);
+        // TODO: share logic with insert_newline for indentation
+        let indent_level = indent::suggested_indent_for_pos(
+            doc.language_config(),
+            doc.syntax(),
+            text,
+            index,
+            true,
+        );
+        let indent = doc.indent_unit().repeat(indent_level);
+        let mut text = String::with_capacity(1 + indent.len());
+        text.push('\n');
+        text.push_str(&indent);
+        let text = text.repeat(count);
 
-            // calculate new selection range
-            let pos = index + text.chars().count();
-            ranges.push(Range::new(pos, pos));
+        // calculate new selection range
+        let pos = if line == 0 {
+            0 // Required since text will have a min len of 1 (\n)
+        } else {
+            index + offs + text.chars().count()
+        };
+        ranges.push(Range::new(pos, pos));
 
-            (index, index, Some(text.into()))
-        })
-        .collect();
+        offs += text.chars().count();
+
+        (index, index, Some(text.into()))
+    });
 
     // TODO: count actually inserts "n" new lines and starts editing on all of them.
     // TODO: append "count" newlines and modify cursors to those lines
 
-    let selection = Selection::new(ranges, 0);
-
-    let transaction =
-        Transaction::change(doc.text(), changes.into_iter()).with_selection(selection);
+    transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
 
     doc.apply(&transaction, view.id);
 }

From 47d2e3aefa5d31c19e7def624057a29c4bc7bc41 Mon Sep 17 00:00:00 2001
From: Gokul Soumya <gokulps15@gmail.com>
Date: Thu, 17 Jun 2021 11:49:02 +0530
Subject: [PATCH 02/31] Let o, O take counts for multiple cursors

---
 helix-term/src/commands.rs | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index 59ae0e79..e6ecda06 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -107,6 +107,7 @@ impl<'a> Context<'a> {
         self.callbacks.push(callback);
     }
 
+    /// Returns 1 if no explicit count was provided
     #[inline]
     pub fn count(&self) -> usize {
         self.count.map_or(1, |v| v.get())
@@ -1511,14 +1512,15 @@ fn open(cx: &mut Context, open: Open) {
             Open::Above => line,
         };
 
-        let index = doc.text().line_to_char(line).saturating_sub(1);
+        // insert newlines after this index for both Above and Below variants
+        let linend_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(
             doc.language_config(),
             doc.syntax(),
             text,
-            index,
+            linend_index,
             true,
         );
         let indent = doc.indent_unit().repeat(indent_level);
@@ -1527,22 +1529,21 @@ fn open(cx: &mut Context, open: Open) {
         text.push_str(&indent);
         let text = text.repeat(count);
 
-        // calculate new selection range
+        // calculate new selection ranges
         let pos = if line == 0 {
             0 // Required since text will have a min len of 1 (\n)
         } else {
-            index + offs + text.chars().count()
+            offs + linend_index + 1
         };
-        ranges.push(Range::new(pos, pos));
+        for i in 0..count {
+            ranges.push(Range::new(pos + i, pos + i));
+        }
 
         offs += text.chars().count();
 
-        (index, index, Some(text.into()))
+        (linend_index, linend_index, Some(text.into()))
     });
 
-    // TODO: count actually inserts "n" new lines and starts editing on all of them.
-    // TODO: append "count" newlines and modify cursors to those lines
-
     transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
 
     doc.apply(&transaction, view.id);

From f7e00cf720f55ea82933ac6625b7511e9d38139e Mon Sep 17 00:00:00 2001
From: PabloMansanet <pablomansanet@gmail.com>
Date: Thu, 17 Jun 2021 13:08:05 +0200
Subject: [PATCH 03/31] Configurable keys 2 (Mapping keys to commands) (#268)

* Add convenience/clarity wrapper for Range initialization

* Add keycode parse and display methods

* Add remapping functions and tests

* Implement key remapping

* Add remapping book entry

* Use raw string literal for toml

* Add command constants

* Make command functions private

* Map directly to commands

* Match key parsing/displaying to Kakoune

* Formatting pass

* Update documentation

* Formatting

* Fix example in the book

* Refactor into single config file

* Formatting

* Refactor configuration and add keymap newtype wrappers

* Address first batch of PR comments

* Replace FromStr with custom deserialize
---
 book/src/SUMMARY.md           |   1 +
 book/src/remapping.md         |  48 +++
 helix-term/src/application.rs |   7 +-
 helix-term/src/commands.rs    | 425 ++++++++++++++++-------
 helix-term/src/config.rs      |  33 ++
 helix-term/src/keymap.rs      | 620 +++++++++++++++++++++++++---------
 helix-term/src/lib.rs         |   1 +
 helix-term/src/main.rs        |  11 +-
 helix-term/src/ui/editor.rs   |  27 +-
 helix-view/src/document.rs    |  27 +-
 10 files changed, 894 insertions(+), 306 deletions(-)
 create mode 100644 book/src/remapping.md
 create mode 100644 helix-term/src/config.rs

diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md
index 474c2e70..3ea1fb9a 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 00000000..313ac72e
--- /dev/null
+++ b/book/src/remapping.md
@@ -0,0 +1,48 @@
+# Key Remapping
+
+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]
+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]
+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 => "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`
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));
 
-pub fn move_char_left(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, )*
+        ];
+    }
+}
+
+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,
+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) => commands::move_char_left,
-        key!(Down) => commands::move_line_down,
-        key!(Up) => commands::move_line_up,
-        key!(Right) => commands::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') => 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!('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) => commands::move_line_start,
-        key!(End) => commands::move_line_end,
+            key!(Home) => Command::move_line_start,
+            key!(End) => Command::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!('w') => Command::move_next_word_start,
+            key!('b') => Command::move_prev_word_start,
+            key!('e') => Command::move_next_word_end,
 
-        key!('v') => commands::select_mode,
-        key!('g') => commands::goto_mode,
-        key!(':') => commands::command_mode,
+            key!('v') => Command::select_mode,
+            key!('g') => Command::goto_mode,
+            key!(':') => Command::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!('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') => commands::delete_selection,
-        // TODO: also delete without yanking
-        key!('c') => commands::change_selection,
-        // TODO: also change delete without yanking
+            key!('d') => Command::delete_selection,
+            // TODO: also delete without yanking
+            key!('c') => Command::change_selection,
+            // TODO: also change delete without yanking
 
-        // key!('r') => commands::replace_with_char,
+            // key!('r') => 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,
-        // or select mode X?
-        // extend_to_whole_line, crop_to_whole_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::match_brackets,
-        // TODO: refactor into
-        // key!('m') => commands::select_to_matching,
-        // key!('M') => commands::back_select_to_matching,
-        // select mode extend equivalents
+            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
+            // 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,
+            // TODO: figure out what key to use
+            // key!('[') => Command::expand_selection, ??
+            key!('[') => Command::left_bracket_mode,
+            key!(']') => Command::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!('/') => 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') => commands::undo,
-        key!('U') => commands::redo,
+            key!('u') => Command::undo,
+            key!('U') => Command::redo,
 
-        key!('y') => commands::yank,
-        // yank_all
-        key!('p') => commands::paste_after,
-        // paste_all
-        key!('P') => commands::paste_before,
+            key!('y') => Command::yank,
+            // yank_all
+            key!('p') => Command::paste_after,
+            // paste_all
+            key!('P') => Command::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
+            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!(' ') => commands::keep_primary_selection,
+            // TODO: clashes with space mode
+            key!(' ') => Command::keep_primary_selection,
 
-        // key!('q') => commands::record_macro,
-        // key!('Q') => commands::replay_macro,
+            // key!('q') => Command::record_macro,
+            // key!('Q') => Command::replay_macro,
 
-        // ~ / apostrophe => change case
-        // & align selections
-        // _ trim selections
+            // ~ / apostrophe => change case
+            // & align selections
+            // _ trim selections
 
-        // C / altC = copy (repeat) selections on prev/next lines
+            // 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,
+            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::window_mode,
+            ctrl!('w') => Command::window_mode,
 
-        // move under <space>c
-        ctrl!('c') => commands::toggle_comments,
-        key!('K') => commands::hover,
+            // move under <space>c
+            ctrl!('c') => Command::toggle_comments,
+            key!('K') => Command::hover,
 
-        // z family for save/restore/combine from/to sels from register
+            // 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,
+            // supposedly ctrl!('i') but did not work
+            key!(Tab) => Command::jump_forward,
+            ctrl!('o') => Command::jump_backward,
+            // ctrl!('s') => Command::save_selection,
 
-        key!(' ') => commands::space_mode,
-        key!('z') => commands::view_mode,
+            key!(' ') => Command::space_mode,
+            key!('z') => Command::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!('"') => 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) => commands::extend_char_left,
-            key!(Down) => commands::extend_line_down,
-            key!(Up) => commands::extend_line_up,
-            key!(Right) => commands::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') => commands::extend_next_word_start,
-            key!('b') => commands::extend_prev_word_start,
-            key!('e') => commands::extend_next_word_end,
+                key!('w') => Command::extend_next_word_start,
+                key!('b') => Command::extend_prev_word_start,
+                key!('e') => Command::extend_next_word_end,
 
-            key!('t') => commands::extend_till_char,
-            key!('f') => commands::extend_next_char,
+                key!('t') => Command::extend_till_char,
+                key!('f') => Command::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(),
-    );
+                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) => 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,
-        ),
-    )
+        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) => {
diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs
index a1c4b407..254e01b0 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::{
@@ -86,6 +88,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<Self, Self::Err> {
+        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<T, F>(mut_ref: &mut T, closure: F)

From 14db2cc68b3e9911f64e675c32800f8cc7b2a5ed Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bla=C5=BE=20Hrastnik?= <blaz@mxxn.io>
Date: Thu, 17 Jun 2021 23:21:33 +0900
Subject: [PATCH 04/31] Add homebrew tap instructions again

---
 book/src/install.md | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/book/src/install.md b/book/src/install.md
index 0a08af8c..e81034ce 100644
--- a/book/src/install.md
+++ b/book/src/install.md
@@ -4,9 +4,12 @@ We provide pre-built binaries on the [GitHub Releases page](https://github.com/h
 
 ## OSX
 
-TODO: brew tap
+A Homebrew tap is available:
 
-Please use a pre-built binary release for the time being.
+```
+brew tap helix-editor/helix
+brew install helix
+```
 
 ## Linux
 

From f65db9397a2d832f7ef873ea416f13f8fb07cb74 Mon Sep 17 00:00:00 2001
From: Perry Thompson <contact@ryper.org>
Date: Thu, 17 Jun 2021 15:55:39 -0500
Subject: [PATCH 05/31] Fix typos in Markdown documentation

---
 book/src/remapping.md | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/book/src/remapping.md b/book/src/remapping.md
index 313ac72e..610d5179 100644
--- a/book/src/remapping.md
+++ b/book/src/remapping.md
@@ -26,9 +26,9 @@ Control, Shift and Alt modifiers are encoded respectively with the prefixes
 * Space => "space"
 * Return/Enter => "ret"
 * < => "lt"
-* > => "gt"
-* + => "plus"
-* - => "minus"
+* \> => "gt"
+* \+ => "plus"
+* \- => "minus"
 * ; => "semicolon"
 * % => "percent"
 * Left => "left"

From 8664d70e731c73fa34dda293b4f6b6dec80a3273 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Thu, 17 Jun 2021 18:09:10 -0400
Subject: [PATCH 06/31] Replace `Editor::current` by a macro

This is necessary to workaround ownership issues across function calls.
The issue notably arised when implementing the registers into `Editor`
and I was getting annoyed again when implementing copy/pasting into
system clipboard.
The problem is addressed by using macro calls instead of function calls.
There is no notable side effect.
---
 helix-term/src/commands.rs      | 256 +++++++++++++++-----------------
 helix-term/src/lib.rs           |   3 +
 helix-term/src/ui/completion.rs |   6 +-
 helix-term/src/ui/editor.rs     |   4 +-
 helix-term/src/ui/mod.rs        |  10 +-
 helix-view/src/editor.rs        |  29 +---
 helix-view/src/lib.rs           |   3 +
 helix-view/src/macros.rs        |  29 ++++
 8 files changed, 172 insertions(+), 168 deletions(-)
 create mode 100644 helix-view/src/macros.rs

diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index 3ec06aaa..dc4805a5 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -52,27 +52,6 @@ pub struct Context<'a> {
 }
 
 impl<'a> Context<'a> {
-    #[inline]
-    pub fn view(&mut self) -> &mut View {
-        self.editor.view_mut()
-    }
-
-    #[inline]
-    pub fn doc(&mut self) -> &mut Document {
-        let id = self.editor.view().doc;
-        &mut self.editor.documents[id]
-    }
-
-    #[inline]
-    pub fn current(&mut self) -> (&mut View, &mut Document) {
-        self.editor.current()
-    }
-
-    #[inline]
-    pub fn current_with_registers(&mut self) -> (&mut View, &mut Document, &mut Registers) {
-        self.editor.current_with_registers()
-    }
-
     /// Push a new component onto the compositor.
     pub fn push_layer(&mut self, mut component: Box<dyn Component>) {
         self.callback = Some(Box::new(|compositor: &mut Compositor| {
@@ -275,7 +254,7 @@ impl Command {
 
 fn move_char_left(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_horizontally(text, range, Direction::Backward, count, Movement::Move)
@@ -285,7 +264,7 @@ fn move_char_left(cx: &mut Context) {
 
 fn move_char_right(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_horizontally(text, range, Direction::Forward, count, Movement::Move)
@@ -295,7 +274,7 @@ fn move_char_right(cx: &mut Context) {
 
 fn move_line_up(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_vertically(text, range, Direction::Backward, count, Movement::Move)
@@ -305,7 +284,7 @@ fn move_line_up(cx: &mut Context) {
 
 fn move_line_down(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_vertically(text, range, Direction::Forward, count, Movement::Move)
@@ -314,7 +293,7 @@ fn move_line_down(cx: &mut Context) {
 }
 
 fn move_line_end(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -330,7 +309,7 @@ fn move_line_end(cx: &mut Context) {
 }
 
 fn move_line_start(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -345,7 +324,7 @@ fn move_line_start(cx: &mut Context) {
 }
 
 fn move_first_nonwhitespace(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -368,7 +347,7 @@ fn move_first_nonwhitespace(cx: &mut Context) {
 
 fn move_next_word_start(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc
@@ -380,7 +359,7 @@ fn move_next_word_start(cx: &mut Context) {
 
 fn move_prev_word_start(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc
@@ -392,7 +371,7 @@ fn move_prev_word_start(cx: &mut Context) {
 
 fn move_next_word_end(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc
@@ -404,13 +383,13 @@ fn move_next_word_end(cx: &mut Context) {
 
 fn move_file_start(cx: &mut Context) {
     push_jump(cx.editor);
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     doc.set_selection(view.id, Selection::point(0));
 }
 
 fn move_file_end(cx: &mut Context) {
     push_jump(cx.editor);
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text();
     let last_line = text.line_to_char(text.len_lines().saturating_sub(2));
     doc.set_selection(view.id, Selection::point(last_line));
@@ -418,7 +397,7 @@ fn move_file_end(cx: &mut Context) {
 
 fn extend_next_word_start(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc.selection(view.id).transform(|mut range| {
@@ -432,7 +411,7 @@ fn extend_next_word_start(cx: &mut Context) {
 
 fn extend_prev_word_start(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc.selection(view.id).transform(|mut range| {
@@ -445,7 +424,7 @@ fn extend_prev_word_start(cx: &mut Context) {
 
 fn extend_next_word_end(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
 
     let selection = doc.selection(view.id).transform(|mut range| {
@@ -482,7 +461,7 @@ where
             _ => return,
         };
 
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let text = doc.text().slice(..);
 
         let selection = doc.selection(view.id).transform(|mut range| {
@@ -574,7 +553,7 @@ fn extend_prev_char(cx: &mut Context) {
 }
 
 fn extend_first_nonwhitespace(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -607,7 +586,7 @@ fn replace(cx: &mut Context) {
         };
 
         if let Some(ch) = ch {
-            let (view, doc) = cx.current();
+            let (view, doc) = current!(cx.editor);
 
             let transaction =
                 Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
@@ -631,7 +610,7 @@ fn replace(cx: &mut Context) {
 
 fn scroll(cx: &mut Context, offset: usize, direction: Direction) {
     use Direction::*;
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let cursor = coords_at_pos(doc.text().slice(..), doc.selection(view.id).cursor());
     let doc_last_line = doc.text().len_lines() - 1;
 
@@ -672,32 +651,32 @@ fn scroll(cx: &mut Context, offset: usize, direction: Direction) {
 }
 
 fn page_up(cx: &mut Context) {
-    let view = cx.view();
+    let view = view!(cx.editor);
     let offset = view.area.height as usize;
     scroll(cx, offset, Direction::Backward);
 }
 
 fn page_down(cx: &mut Context) {
-    let view = cx.view();
+    let view = view!(cx.editor);
     let offset = view.area.height as usize;
     scroll(cx, offset, Direction::Forward);
 }
 
 fn half_page_up(cx: &mut Context) {
-    let view = cx.view();
+    let view = view!(cx.editor);
     let offset = view.area.height as usize / 2;
     scroll(cx, offset, Direction::Backward);
 }
 
 fn half_page_down(cx: &mut Context) {
-    let view = cx.view();
+    let view = view!(cx.editor);
     let offset = view.area.height as usize / 2;
     scroll(cx, offset, Direction::Forward);
 }
 
 fn extend_char_left(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_horizontally(text, range, Direction::Backward, count, Movement::Extend)
@@ -707,7 +686,7 @@ fn extend_char_left(cx: &mut Context) {
 
 fn extend_char_right(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_horizontally(text, range, Direction::Forward, count, Movement::Extend)
@@ -717,7 +696,7 @@ fn extend_char_right(cx: &mut Context) {
 
 fn extend_line_up(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_vertically(text, range, Direction::Backward, count, Movement::Extend)
@@ -727,7 +706,7 @@ fn extend_line_up(cx: &mut Context) {
 
 fn extend_line_down(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     let selection = doc.selection(view.id).transform(|range| {
         movement::move_vertically(text, range, Direction::Forward, count, Movement::Extend)
@@ -736,7 +715,7 @@ fn extend_line_down(cx: &mut Context) {
 }
 
 fn extend_line_end(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -752,7 +731,7 @@ fn extend_line_end(cx: &mut Context) {
 }
 
 fn extend_line_start(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let selection = doc.selection(view.id).transform(|range| {
         let text = doc.text();
@@ -767,7 +746,7 @@ fn extend_line_start(cx: &mut Context) {
 }
 
 fn select_all(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let end = doc.text().len_chars().saturating_sub(1);
     doc.set_selection(view.id, Selection::single(0, end))
@@ -796,7 +775,7 @@ fn split_selection(cx: &mut Context) {
 }
 
 fn split_selection_on_newline(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text().slice(..);
     // only compile the regex once
     #[allow(clippy::trivial_regex)]
@@ -848,7 +827,7 @@ fn search_impl(doc: &mut Document, view: &mut View, contents: &str, regex: &Rege
 
 // TODO: use one function for search vs extend
 fn search(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     // TODO: could probably share with select_on_matches?
 
@@ -871,7 +850,8 @@ fn search(cx: &mut Context) {
 }
 
 fn search_next_impl(cx: &mut Context, extend: bool) {
-    let (view, doc, registers) = cx.current_with_registers();
+    let (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
     if let Some(query) = registers.read('\\') {
         let query = query.first().unwrap();
         let contents = doc.text().slice(..).to_string();
@@ -889,7 +869,7 @@ fn extend_search_next(cx: &mut Context) {
 }
 
 fn search_selection(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let contents = doc.text().slice(..);
     let query = doc.selection(view.id).primary().fragment(contents);
     let regex = regex::escape(&query);
@@ -905,7 +885,7 @@ fn search_selection(cx: &mut Context) {
 
 fn select_line(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let pos = doc.selection(view.id).primary();
     let text = doc.text();
@@ -920,7 +900,7 @@ fn select_line(cx: &mut Context) {
 }
 fn extend_line(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let pos = doc.selection(view.id).primary();
     let text = doc.text();
@@ -962,7 +942,8 @@ fn delete_selection_impl(reg: &mut Register, doc: &mut Document, view_id: ViewId
 
 fn delete_selection(cx: &mut Context) {
     let reg_name = cx.selected_register.name();
-    let (view, doc, registers) = cx.current_with_registers();
+    let (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
     let reg = registers.get_or_insert(reg_name);
     delete_selection_impl(reg, doc, view.id);
 
@@ -974,14 +955,15 @@ fn delete_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 (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
     let reg = registers.get_or_insert(reg_name);
     delete_selection_impl(reg, doc, view.id);
     enter_insert_mode(doc);
 }
 
 fn collapse_selection(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let selection = doc
         .selection(view.id)
         .transform(|range| Range::new(range.head, range.head));
@@ -990,7 +972,7 @@ fn collapse_selection(cx: &mut Context) {
 }
 
 fn flip_selections(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let selection = doc
         .selection(view.id)
         .transform(|range| Range::new(range.head, range.anchor));
@@ -1004,7 +986,7 @@ fn enter_insert_mode(doc: &mut Document) {
 
 // inserts at the start of each selection
 fn insert_mode(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     enter_insert_mode(doc);
 
     let selection = doc
@@ -1015,7 +997,7 @@ fn insert_mode(cx: &mut Context) {
 
 // inserts at the end of each selection
 fn append_mode(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     enter_insert_mode(doc);
     doc.restore_cursor = true;
 
@@ -1062,11 +1044,11 @@ mod cmd {
         if editor.tree.views().count() == 1 && buffers_remaining_impl(editor) {
             return;
         }
-        editor.close(editor.view().id, /* close_buffer */ false);
+        editor.close(view!(editor).id, /* close_buffer */ false);
     }
 
     fn force_quit(editor: &mut Editor, args: &[&str], event: PromptEvent) {
-        editor.close(editor.view().id, /* close_buffer */ false);
+        editor.close(view!(editor).id, /* close_buffer */ false);
     }
 
     fn open(editor: &mut Editor, args: &[&str], event: PromptEvent) {
@@ -1108,7 +1090,7 @@ mod cmd {
     }
 
     fn write(editor: &mut Editor, args: &[&str], event: PromptEvent) {
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
         if let Err(e) = write_impl(view, doc, args.first()) {
             editor.set_error(e.to_string());
         };
@@ -1119,7 +1101,7 @@ mod cmd {
     }
 
     fn format(editor: &mut Editor, args: &[&str], event: PromptEvent) {
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
 
         doc.format(view.id)
     }
@@ -1129,7 +1111,7 @@ mod cmd {
 
         // If no argument, report current indent style.
         if args.is_empty() {
-            let style = editor.current().1.indent_style;
+            let style = current!(editor).1.indent_style;
             editor.set_status(match style {
                 Tabs => "tabs".into(),
                 Spaces(1) => "1 space".into(),
@@ -1152,7 +1134,7 @@ mod cmd {
         };
 
         if let Some(s) = style {
-            let (_, doc) = editor.current();
+            let doc = doc_mut!(editor);
             doc.indent_style = s;
         } else {
             // Invalid argument.
@@ -1168,7 +1150,7 @@ mod cmd {
                 return;
             }
         };
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
         doc.earlier(view.id, uk)
     }
 
@@ -1180,12 +1162,12 @@ mod cmd {
                 return;
             }
         };
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
         doc.later(view.id, uk)
     }
 
     fn write_quit(editor: &mut Editor, args: &[&str], event: PromptEvent) {
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
         if let Err(e) = write_impl(view, doc, args.first()) {
             editor.set_error(e.to_string());
             return;
@@ -1499,7 +1481,7 @@ fn file_picker(cx: &mut Context) {
 
 fn buffer_picker(cx: &mut Context) {
     use std::path::{Path, PathBuf};
-    let current = cx.editor.view().doc;
+    let current = view!(cx.editor).doc;
 
     let picker = Picker::new(
         cx.editor
@@ -1547,7 +1529,7 @@ fn symbol_picker(cx: &mut Context) {
             nested_to_flat(list, file, child);
         }
     }
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
@@ -1568,7 +1550,7 @@ fn symbol_picker(cx: &mut Context) {
                 let symbols = match symbols {
                     lsp::DocumentSymbolResponse::Flat(symbols) => symbols,
                     lsp::DocumentSymbolResponse::Nested(symbols) => {
-                        let (_view, doc) = editor.current();
+                        let (_view, doc) = current!(editor);
                         let mut flat_symbols = Vec::new();
                         for symbol in symbols {
                             nested_to_flat(&mut flat_symbols, &doc.identifier(), symbol)
@@ -1582,7 +1564,7 @@ fn symbol_picker(cx: &mut Context) {
                     |symbol| (&symbol.name).into(),
                     move |editor: &mut Editor, symbol, _action| {
                         push_jump(editor);
-                        let (view, doc) = editor.current();
+                        let (view, doc) = current!(editor);
 
                         if let Some(range) =
                             lsp_range_to_range(doc.text(), symbol.location.range, offset_encoding)
@@ -1601,13 +1583,13 @@ fn symbol_picker(cx: &mut Context) {
 // I inserts at the first nonwhitespace character of each line with a selection
 fn prepend_to_line(cx: &mut Context) {
     move_first_nonwhitespace(cx);
-    let doc = cx.doc();
+    let doc = doc_mut!(cx.editor);
     enter_insert_mode(doc);
 }
 
 // A inserts at the end of each line with a selection
 fn append_to_line(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     enter_insert_mode(doc);
 
     let selection = doc.selection(view.id).transform(|range| {
@@ -1627,7 +1609,7 @@ enum Open {
 
 fn open(cx: &mut Context, open: Open) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     enter_insert_mode(doc);
 
     let text = doc.text().slice(..);
@@ -1695,7 +1677,7 @@ fn open_above(cx: &mut Context) {
 }
 
 fn normal_mode(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     doc.mode = Mode::Normal;
 
@@ -1718,13 +1700,13 @@ fn normal_mode(cx: &mut Context) {
 
 // Store a jump on the jumplist.
 fn push_jump(editor: &mut Editor) {
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
     let jump = (doc.id(), doc.selection(view.id).clone());
     view.jumps.push(jump);
 }
 
 fn switch_to_last_accessed_file(cx: &mut Context) {
-    let alternate_file = cx.view().last_accessed_doc;
+    let alternate_file = view!(cx.editor).last_accessed_doc;
     if let Some(alt) = alternate_file {
         cx.editor.switch(alt, Action::Replace);
     } else {
@@ -1736,7 +1718,7 @@ fn goto_mode(cx: &mut Context) {
     if let Some(count) = cx.count {
         push_jump(cx.editor);
 
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let line_idx = std::cmp::min(count.get() - 1, doc.text().len_lines().saturating_sub(2));
         let pos = doc.text().line_to_char(line_idx);
         doc.set_selection(view.id, Selection::point(pos));
@@ -1750,7 +1732,8 @@ fn goto_mode(cx: &mut Context) {
         } = event
         {
             // TODO: temporarily show GOTO in the mode list
-            match (cx.doc().mode, ch) {
+            let doc = doc_mut!(cx.editor);
+            match (doc.mode, ch) {
                 (_, 'g') => move_file_start(cx),
                 (_, 'e') => move_file_end(cx),
                 (_, 'a') => switch_to_last_accessed_file(cx),
@@ -1766,7 +1749,7 @@ fn goto_mode(cx: &mut Context) {
                 (Mode::Select, 's') => extend_first_nonwhitespace(cx),
 
                 (_, 't') | (_, 'm') | (_, 'b') => {
-                    let (view, doc) = cx.current();
+                    let (view, doc) = current!(cx.editor);
 
                     let pos = doc.selection(view.id).cursor();
                     let line = doc.text().char_to_line(pos);
@@ -1794,11 +1777,11 @@ fn goto_mode(cx: &mut Context) {
 }
 
 fn select_mode(cx: &mut Context) {
-    cx.doc().mode = Mode::Select;
+    doc_mut!(cx.editor).mode = Mode::Select;
 }
 
 fn exit_select_mode(cx: &mut Context) {
-    cx.doc().mode = Mode::Normal;
+    doc_mut!(cx.editor).mode = Mode::Normal;
 }
 
 fn goto_impl(
@@ -1820,7 +1803,7 @@ fn goto_impl(
         let id = editor
             .open(PathBuf::from(location.uri.path()), action)
             .expect("editor.open failed");
-        let (view, doc) = editor.current();
+        let (view, doc) = current!(editor);
         let definition_pos = location.range.start;
         // TODO: convert inside server
         let new_pos =
@@ -1858,7 +1841,7 @@ fn goto_impl(
 }
 
 fn goto_definition(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
         None => return,
@@ -1895,7 +1878,7 @@ fn goto_definition(cx: &mut Context) {
 }
 
 fn goto_type_definition(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
         None => return,
@@ -1932,7 +1915,7 @@ fn goto_type_definition(cx: &mut Context) {
 }
 
 fn goto_implementation(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
         None => return,
@@ -1969,7 +1952,7 @@ fn goto_implementation(cx: &mut Context) {
 }
 
 fn goto_reference(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
         None => return,
@@ -2000,7 +1983,7 @@ fn goto_reference(cx: &mut Context) {
 fn goto_pos(editor: &mut Editor, pos: usize) {
     push_jump(editor);
 
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
 
     doc.set_selection(view.id, Selection::point(pos));
     align_view(doc, view, Align::Center);
@@ -2008,7 +1991,7 @@ fn goto_pos(editor: &mut Editor, pos: usize) {
 
 fn goto_first_diag(cx: &mut Context) {
     let editor = &mut cx.editor;
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
 
     let cursor_pos = doc.selection(view.id).cursor();
     let diag = if let Some(diag) = doc.diagnostics().first() {
@@ -2022,7 +2005,7 @@ fn goto_first_diag(cx: &mut Context) {
 
 fn goto_last_diag(cx: &mut Context) {
     let editor = &mut cx.editor;
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
 
     let cursor_pos = doc.selection(view.id).cursor();
     let diag = if let Some(diag) = doc.diagnostics().last() {
@@ -2036,7 +2019,7 @@ fn goto_last_diag(cx: &mut Context) {
 
 fn goto_next_diag(cx: &mut Context) {
     let editor = &mut cx.editor;
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
 
     let cursor_pos = doc.selection(view.id).cursor();
     let diag = if let Some(diag) = doc
@@ -2057,7 +2040,7 @@ fn goto_next_diag(cx: &mut Context) {
 
 fn goto_prev_diag(cx: &mut Context) {
     let editor = &mut cx.editor;
-    let (view, doc) = editor.current();
+    let (view, doc) = current!(editor);
 
     let cursor_pos = doc.selection(view.id).cursor();
     let diag = if let Some(diag) = doc
@@ -2078,7 +2061,7 @@ fn goto_prev_diag(cx: &mut Context) {
 }
 
 fn signature_help(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
@@ -2124,7 +2107,7 @@ pub mod insert {
 
     fn completion(cx: &mut Context, ch: char) {
         // if ch matches completion char, trigger completion
-        let doc = cx.doc();
+        let doc = doc_mut!(cx.editor);
         let language_server = match doc.language_server() {
             Some(language_server) => language_server,
             None => return,
@@ -2152,7 +2135,7 @@ pub mod insert {
 
     fn signature_help(cx: &mut Context, ch: char) {
         // if ch matches signature_help char, trigger
-        let doc = cx.doc();
+        let doc = doc_mut!(cx.editor);
         let language_server = match doc.language_server() {
             Some(language_server) => language_server,
             None => return,
@@ -2207,7 +2190,7 @@ pub mod insert {
     const POST_HOOKS: &[PostHook] = &[completion, signature_help];
 
     pub fn insert_char(cx: &mut Context, c: char) {
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
 
         let text = doc.text();
         let selection = doc.selection(view.id);
@@ -2229,7 +2212,7 @@ pub mod insert {
     }
 
     pub fn insert_tab(cx: &mut Context) {
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         // TODO: round out to nearest indentation level (for example a line with 3 spaces should
         // indent by one to reach 4 spaces).
 
@@ -2239,7 +2222,7 @@ pub mod insert {
     }
 
     pub fn insert_newline(cx: &mut Context) {
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let text = doc.text().slice(..);
 
         let contents = doc.text();
@@ -2308,7 +2291,7 @@ pub mod insert {
     // TODO: handle indent-aware delete
     pub fn delete_char_backward(cx: &mut Context) {
         let count = cx.count();
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let text = doc.text().slice(..);
         let transaction =
             Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
@@ -2323,7 +2306,7 @@ pub mod insert {
 
     pub fn delete_char_forward(cx: &mut Context) {
         let count = cx.count();
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let text = doc.text().slice(..);
         let transaction =
             Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| {
@@ -2338,7 +2321,7 @@ pub mod insert {
 
     pub fn delete_word_backward(cx: &mut Context) {
         let count = cx.count();
-        let (view, doc) = cx.current();
+        let (view, doc) = current!(cx.editor);
         let text = doc.text().slice(..);
         let selection = doc
             .selection(view.id)
@@ -2354,20 +2337,22 @@ pub mod insert {
 // storing it?
 
 fn undo(cx: &mut Context) {
-    let view_id = cx.view().id;
-    cx.doc().undo(view_id);
+    let (view, doc) = current!(cx.editor);
+    let view_id = view.id;
+    doc.undo(view_id);
 }
 
 fn redo(cx: &mut Context) {
-    let view_id = cx.view().id;
-    cx.doc().redo(view_id);
+    let (view, doc) = current!(cx.editor);
+    let view_id = view.id;
+    doc.redo(view_id);
 }
 
 // Yank / Paste
 
 fn yank(cx: &mut Context) {
     // TODO: should selections be made end inclusive?
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let values: Vec<String> = doc
         .selection(view.id)
         .fragments(doc.text().slice(..))
@@ -2432,7 +2417,8 @@ fn paste_impl(
 
 fn replace_with_yanked(cx: &mut Context) {
     let reg_name = cx.selected_register.name();
-    let (view, doc, registers) = cx.current_with_registers();
+    let (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
 
     if let Some(values) = registers.read(reg_name) {
         if let Some(yank) = values.first() {
@@ -2461,7 +2447,8 @@ fn replace_with_yanked(cx: &mut Context) {
 
 fn paste_after(cx: &mut Context) {
     let reg_name = cx.selected_register.name();
-    let (view, doc, registers) = cx.current_with_registers();
+    let (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
 
     if let Some(transaction) = registers
         .read(reg_name)
@@ -2474,7 +2461,8 @@ fn paste_after(cx: &mut Context) {
 
 fn paste_before(cx: &mut Context) {
     let reg_name = cx.selected_register.name();
-    let (view, doc, registers) = cx.current_with_registers();
+    let (view, doc) = current!(cx.editor);
+    let registers = &mut cx.editor.registers;
 
     if let Some(transaction) = registers
         .read(reg_name)
@@ -2504,7 +2492,7 @@ fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
 
 fn indent(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let lines = get_lines(doc, view.id);
 
     // Indent by one level
@@ -2523,7 +2511,7 @@ fn indent(cx: &mut Context) {
 
 fn unindent(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let lines = get_lines(doc, view.id);
     let mut changes = Vec::with_capacity(lines.len());
     let tab_width = doc.tab_width();
@@ -2562,7 +2550,7 @@ fn unindent(cx: &mut Context) {
 }
 
 fn format_selections(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     // via lsp if available
     // else via tree-sitter indentation calculations
@@ -2609,7 +2597,7 @@ fn format_selections(cx: &mut Context) {
 
 fn join_selections(cx: &mut Context) {
     use movement::skip_while;
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let text = doc.text();
     let slice = doc.text().slice(..);
 
@@ -2665,7 +2653,7 @@ fn keep_selections(cx: &mut Context) {
 }
 
 fn keep_primary_selection(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let range = doc.selection(view.id).primary();
     let selection = Selection::single(range.anchor, range.head);
@@ -2678,7 +2666,7 @@ 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());
+    tokio::spawn(doc_mut!(cx.editor).save());
 }
 
 fn completion(cx: &mut Context) {
@@ -2718,7 +2706,7 @@ fn completion(cx: &mut Context) {
     // The prefix still has to satisfy `company-minimum-prefix-length' before that
     // happens.  The value of nil means no idle completion."
 
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
@@ -2772,7 +2760,7 @@ fn completion(cx: &mut Context) {
 }
 
 fn hover(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     let language_server = match doc.language_server() {
         Some(language_server) => language_server,
@@ -2822,7 +2810,7 @@ fn hover(cx: &mut Context) {
 
 // comments
 fn toggle_comments(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id));
 
     doc.apply(&transaction, view.id);
@@ -2832,7 +2820,7 @@ fn toggle_comments(cx: &mut Context) {
 // tree sitter node selection
 
 fn expand_selection(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     if let Some(syntax) = doc.syntax() {
         let text = doc.text().slice(..);
@@ -2842,7 +2830,7 @@ fn expand_selection(cx: &mut Context) {
 }
 
 fn match_brackets(cx: &mut Context) {
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     if let Some(syntax) = doc.syntax() {
         let pos = doc.selection(view.id).cursor();
@@ -2857,12 +2845,12 @@ fn match_brackets(cx: &mut Context) {
 
 fn jump_forward(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     if let Some((id, selection)) = view.jumps.forward(count) {
         view.doc = *id;
         let selection = selection.clone();
-        let (view, doc) = cx.current(); // refetch doc
+        let (view, doc) = current!(cx.editor); // refetch doc
         doc.set_selection(view.id, selection);
 
         align_view(doc, view, Align::Center);
@@ -2871,7 +2859,7 @@ fn jump_forward(cx: &mut Context) {
 
 fn jump_backward(cx: &mut Context) {
     let count = cx.count();
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
 
     if let Some((id, selection)) = view.jumps.backward(view.id, doc, count) {
         // manually set the alternate_file as we cannot use the Editor::switch function here.
@@ -2880,7 +2868,7 @@ fn jump_backward(cx: &mut Context) {
         }
         view.doc = *id;
         let selection = selection.clone();
-        let (view, doc) = cx.current(); // refetch doc
+        let (view, doc) = current!(cx.editor); // refetch doc
         doc.set_selection(view.id, selection);
 
         align_view(doc, view, Align::Center);
@@ -2915,7 +2903,7 @@ 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();
+    let (view, doc) = current!(cx.editor);
     let id = doc.id();
     let selection = doc.selection(view.id).clone();
     let first_line = view.first_line;
@@ -2923,7 +2911,7 @@ fn split(cx: &mut Context, action: Action) {
     cx.editor.switch(id, action);
 
     // match the selection in the previous view
-    let (view, doc) = cx.current();
+    let (view, doc) = current!(cx.editor);
     view.first_line = first_line;
     doc.set_selection(view.id, selection);
 }
@@ -2937,7 +2925,7 @@ fn vsplit(cx: &mut Context) {
 }
 
 fn wclose(cx: &mut Context) {
-    let view_id = cx.view().id;
+    let view_id = view!(cx.editor).id;
     // close current split
     cx.editor.close(view_id, /* close_buffer */ false);
 }
@@ -2992,7 +2980,7 @@ fn view_mode(cx: &mut Context) {
                 | 't'
                 // bottom
                 | 'b' => {
-                    let (view, doc) = cx.current();
+                    let (view, doc) = current!(cx.editor);
 
                     align_view(doc, view, match ch {
                         'z' | 'c' => Align::Center,
@@ -3002,7 +2990,7 @@ fn view_mode(cx: &mut Context) {
                     });
                 }
                 'm' => {
-                    let (view, doc) = cx.current();
+                    let (view, doc) = current!(cx.editor);
                     let pos = doc.selection(view.id).cursor();
                     let pos = coords_at_pos(doc.text().slice(..), pos);
 
diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs
index 60190372..dc8ec38e 100644
--- a/helix-term/src/lib.rs
+++ b/helix-term/src/lib.rs
@@ -1,5 +1,8 @@
 #![allow(unused)]
 
+#[macro_use]
+extern crate helix_view;
+
 pub mod application;
 pub mod args;
 pub mod commands;
diff --git a/helix-term/src/ui/completion.rs b/helix-term/src/ui/completion.rs
index 00ecce03..06ed966d 100644
--- a/helix-term/src/ui/completion.rs
+++ b/helix-term/src/ui/completion.rs
@@ -89,7 +89,7 @@ impl Completion {
                     // doc.state = snapshot.clone();
                 }
                 PromptEvent::Validate => {
-                    let (view, doc) = editor.current();
+                    let (view, doc) = current!(editor);
 
                     // revert state to what it was before the last update
                     // doc.state = snapshot.clone();
@@ -169,7 +169,7 @@ impl Completion {
     pub fn update(&mut self, cx: &mut commands::Context) {
         // recompute menu based on matches
         let menu = self.popup.contents_mut();
-        let (view, doc) = cx.editor.current();
+        let (view, doc) = current!(cx.editor);
 
         // cx.hooks()
         // cx.add_hook(enum type,  ||)
@@ -233,7 +233,7 @@ impl Component for Completion {
             // ---
             // option.documentation
 
-            let (view, doc) = cx.editor.current();
+            let (view, doc) = current!(cx.editor);
             let language = doc
                 .language()
                 .and_then(|scope| scope.strip_prefix("source."))
diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs
index 07107c9e..ba5e7574 100644
--- a/helix-term/src/ui/editor.rs
+++ b/helix-term/src/ui/editor.rs
@@ -615,7 +615,7 @@ impl Component for EditorView {
                 // clear status
                 cx.editor.status_msg = None;
 
-                let (view, doc) = cx.editor.current();
+                let (view, doc) = current!(cx.editor);
                 let mode = doc.mode();
 
                 let mut cxt = commands::Context {
@@ -684,7 +684,7 @@ impl Component for EditorView {
                     return EventResult::Ignored;
                 }
 
-                let (view, doc) = cx.editor.current();
+                let (view, doc) = current!(cx.editor);
                 view.ensure_cursor_in_view(doc);
 
                 // mode transitions
diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs
index 77e53690..b2274d06 100644
--- a/helix-term/src/ui/mod.rs
+++ b/helix-term/src/ui/mod.rs
@@ -30,8 +30,9 @@ pub fn regex_prompt(
     prompt: String,
     fun: impl Fn(&mut View, &mut Document, &mut Registers, Regex) + 'static,
 ) -> Prompt {
-    let view_id = cx.view().id;
-    let snapshot = cx.doc().selection(view_id).clone();
+    let (view, doc) = current!(cx.editor);
+    let view_id = view.id;
+    let snapshot = doc.selection(view_id).clone();
 
     Prompt::new(
         prompt,
@@ -40,7 +41,7 @@ pub fn regex_prompt(
             match event {
                 PromptEvent::Abort => {
                     // TODO: also revert text
-                    let (view, doc) = editor.current();
+                    let (view, doc) = current!(editor);
                     doc.set_selection(view.id, snapshot.clone());
                 }
                 PromptEvent::Validate => {
@@ -54,7 +55,8 @@ pub fn regex_prompt(
 
                     match Regex::new(input) {
                         Ok(regex) => {
-                            let (view, doc, registers) = editor.current_with_registers();
+                            let (view, doc) = current!(editor);
+                            let registers = &mut editor.registers;
 
                             // revert state to what it was before the last update
                             // TODO: also revert text
diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs
index 24f43c0e..a1c93f75 100644
--- a/helix-view/src/editor.rs
+++ b/helix-view/src/editor.rs
@@ -101,19 +101,19 @@ impl Editor {
 
         match action {
             Action::Replace => {
-                let view = self.view();
+                let view = view!(self);
                 let jump = (
                     view.doc,
                     self.documents[view.doc].selection(view.id).clone(),
                 );
 
-                let view = self.view_mut();
+                let view = view_mut!(self);
                 view.jumps.push(jump);
                 view.last_accessed_doc = Some(view.doc);
                 view.doc = id;
                 view.first_line = 0;
 
-                let (view, doc) = self.current();
+                let (view, doc) = current!(self);
 
                 // initialize selection for view
                 let selection = doc
@@ -238,27 +238,6 @@ impl Editor {
         self.tree.is_empty()
     }
 
-    pub fn current(&mut self) -> (&mut View, &mut Document) {
-        let view = self.tree.get_mut(self.tree.focus);
-        let doc = &mut self.documents[view.doc];
-        (view, doc)
-    }
-
-    pub fn current_with_registers(&mut self) -> (&mut View, &mut Document, &mut Registers) {
-        let view = self.tree.get_mut(self.tree.focus);
-        let doc = &mut self.documents[view.doc];
-        let registers = &mut self.registers;
-        (view, doc, registers)
-    }
-
-    pub fn view(&self) -> &View {
-        self.tree.get(self.tree.focus)
-    }
-
-    pub fn view_mut(&mut self) -> &mut View {
-        self.tree.get_mut(self.tree.focus)
-    }
-
     pub fn ensure_cursor_in_view(&mut self, id: ViewId) {
         let view = self.tree.get_mut(id);
         let doc = &self.documents[view.doc];
@@ -280,7 +259,7 @@ impl Editor {
 
     pub fn cursor(&self) -> (Option<Position>, CursorKind) {
         const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
-        let view = self.view();
+        let view = view!(self);
         let doc = &self.documents[view.doc];
         let cursor = doc.selection(view.id).cursor();
         if let Some(mut pos) = view.screen_coords_at_pos(doc, doc.text().slice(..), cursor) {
diff --git a/helix-view/src/lib.rs b/helix-view/src/lib.rs
index 7e253320..20613451 100644
--- a/helix-view/src/lib.rs
+++ b/helix-view/src/lib.rs
@@ -1,3 +1,6 @@
+#[macro_use]
+pub mod macros;
+
 pub mod document;
 pub mod editor;
 pub mod register_selection;
diff --git a/helix-view/src/macros.rs b/helix-view/src/macros.rs
new file mode 100644
index 00000000..a06d37e7
--- /dev/null
+++ b/helix-view/src/macros.rs
@@ -0,0 +1,29 @@
+#[macro_export]
+macro_rules! current {
+    ( $( $editor:ident ).+ ) => {{
+        let view = $crate::view_mut!( $( $editor ).+ );
+        let doc = &mut $( $editor ).+ .documents[view.doc];
+        (view, doc)
+    }};
+}
+
+#[macro_export]
+macro_rules! doc_mut {
+    ( $( $editor:ident ).+ ) => {{
+        $crate::current!( $( $editor ).+ ).1
+    }};
+}
+
+#[macro_export]
+macro_rules! view_mut {
+    ( $( $editor:ident ).+ ) => {{
+        $( $editor ).+ .tree.get_mut($( $editor ).+ .tree.focus)
+    }};
+}
+
+#[macro_export]
+macro_rules! view {
+    ( $( $editor:ident ).+ ) => {{
+        $( $editor ).+ .tree.get($( $editor ).+ .tree.focus)
+    }};
+}

From 42142cf680197a2076b9fa8ec864b91e67068082 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Thu, 17 Jun 2021 18:24:15 -0400
Subject: [PATCH 07/31] Fix panic when entering unicode in command prompt

It was attempted to use `String::insert` and `String::remove` to insert
without taking care of unicodes.

Fixes https://github.com/helix-editor/helix/issues/282
---
 helix-term/src/ui/prompt.rs | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/helix-term/src/ui/prompt.rs b/helix-term/src/ui/prompt.rs
index 7b8af820..991b328d 100644
--- a/helix-term/src/ui/prompt.rs
+++ b/helix-term/src/ui/prompt.rs
@@ -53,7 +53,16 @@ impl Prompt {
     }
 
     pub fn insert_char(&mut self, c: char) {
-        self.line.insert(self.cursor, c);
+        let pos = if self.line.is_empty() {
+            0
+        } else {
+            self.line
+                .char_indices()
+                .nth(self.cursor)
+                .map(|(pos, _)| pos)
+                .unwrap_or_else(|| self.line.len())
+        };
+        self.line.insert(pos, c);
         self.cursor += 1;
         self.completion = (self.completion_fn)(&self.line);
         self.exit_selection();
@@ -79,7 +88,13 @@ impl Prompt {
 
     pub fn delete_char_backwards(&mut self) {
         if self.cursor > 0 {
-            self.line.remove(self.cursor - 1);
+            let pos = self
+                .line
+                .char_indices()
+                .nth(self.cursor - 1)
+                .map(|(pos, _)| pos)
+                .expect("line is not empty");
+            self.line.remove(pos);
             self.cursor -= 1;
             self.completion = (self.completion_fn)(&self.line);
         }

From 41b07486ad935ad820dd4ba210457a03c95e1145 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Wojciech=20K=C4=99pka?=
 <46892771+wojciechkepka@users.noreply.github.com>
Date: Fri, 18 Jun 2021 08:19:34 +0200
Subject: [PATCH 08/31] Fix expansion of `~` (#284)

* Fix expansion of `~`, dont use directory relative to cwd.

* Add `expand_tilde`

* Bring back `canonicalize_path`, use `expand_tilde` to `normalize`

* Make `:open ~` completion work

* Fix clippy

* Fold home dir into tilde in Document `realitve_path`
---
 helix-core/src/lib.rs      |  2 ++
 helix-term/src/commands.rs |  6 ++--
 helix-term/src/ui/mod.rs   | 18 ++++++++---
 helix-view/src/document.rs | 61 ++++++++++++++++++++++++++++++++------
 4 files changed, 71 insertions(+), 16 deletions(-)

diff --git a/helix-core/src/lib.rs b/helix-core/src/lib.rs
index b11faeab..03741719 100644
--- a/helix-core/src/lib.rs
+++ b/helix-core/src/lib.rs
@@ -89,6 +89,8 @@ pub fn cache_dir() -> std::path::PathBuf {
     path
 }
 
+pub use etcetera::home_dir;
+
 use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
 
 pub use ropey::{Rope, RopeSlice};
diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index dc4805a5..b2dd0d11 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1188,8 +1188,8 @@ mod cmd {
             .filter(|doc| doc.is_modified())
             .map(|doc| {
                 doc.relative_path()
-                    .and_then(|path| path.to_str())
-                    .unwrap_or("[scratch]")
+                    .map(|path| path.to_string_lossy().to_string())
+                    .unwrap_or_else(|| "[scratch]".into())
             })
             .collect();
         if !modified.is_empty() {
@@ -1487,7 +1487,7 @@ fn buffer_picker(cx: &mut Context) {
         cx.editor
             .documents
             .iter()
-            .map(|(id, doc)| (id, doc.relative_path().map(Path::to_path_buf)))
+            .map(|(id, doc)| (id, doc.relative_path()))
             .collect(),
         move |(id, path): &(DocumentId, Option<PathBuf>)| {
             // format_fn
diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs
index b2274d06..39e11cd6 100644
--- a/helix-term/src/ui/mod.rs
+++ b/helix-term/src/ui/mod.rs
@@ -126,10 +126,11 @@ pub mod completers {
         use ignore::WalkBuilder;
         use std::path::{Path, PathBuf};
 
-        let path = Path::new(input);
+        let is_tilde = input.starts_with('~') && input.len() == 1;
+        let path = helix_view::document::expand_tilde(Path::new(input));
 
         let (dir, file_name) = if input.ends_with('/') {
-            (path.into(), None)
+            (path, None)
         } else {
             let file_name = path
                 .file_name()
@@ -154,7 +155,16 @@ pub mod completers {
                     let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
 
                     let path = entry.path();
-                    let mut path = path.strip_prefix(&dir).unwrap_or(path).to_path_buf();
+                    let mut path = if is_tilde {
+                        // if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on
+                        // one of the directories the tilde will be replaced with a valid path not with a relative
+                        // home directory name.
+                        // ~ -> <TAB> -> /home/user
+                        // ~/ -> <TAB> -> ~/first_entry
+                        path.to_path_buf()
+                    } else {
+                        path.strip_prefix(&dir).unwrap_or(path).to_path_buf()
+                    };
 
                     if is_dir {
                         path.push("");
@@ -184,7 +194,7 @@ pub mod completers {
                 })
                 .collect();
 
-            let range = ((input.len() - file_name.len())..);
+            let range = ((input.len().saturating_sub(file_name.len()))..);
 
             matches.sort_unstable_by_key(|(_file, score)| Reverse(*score));
             files = matches
diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs
index 254e01b0..fe9c87f7 100644
--- a/helix-view/src/document.rs
+++ b/helix-view/src/document.rs
@@ -127,6 +127,36 @@ where
     }
 }
 
+/// Expands tilde `~` into users home directory if avilable, otherwise returns the path
+/// unchanged. The tilde will only be expanded when present as the first component of the path
+/// and only slash follows it.
+pub fn expand_tilde(path: &Path) -> PathBuf {
+    let mut components = path.components().peekable();
+    if let Some(Component::Normal(c)) = components.peek() {
+        if c == &"~" {
+            if let Ok(home) = helix_core::home_dir() {
+                // it's ok to unwrap, the path starts with `~`
+                return home.join(path.strip_prefix("~").unwrap());
+            }
+        }
+    }
+
+    path.to_path_buf()
+}
+
+/// Replaces users home directory from `path` with tilde `~` if the directory
+/// is available, otherwise returns the path unchanged.
+pub fn fold_home_dir(path: &Path) -> PathBuf {
+    if let Ok(home) = helix_core::home_dir() {
+        if path.starts_with(&home) {
+            // it's ok to unwrap, the path starts with home dir
+            return PathBuf::from("~").join(path.strip_prefix(&home).unwrap());
+        }
+    }
+
+    path.to_path_buf()
+}
+
 /// Normalize a path, removing things like `.` and `..`.
 ///
 /// CAUTION: This does not resolve symlinks (unlike
@@ -137,6 +167,7 @@ where
 /// needs to improve on.
 /// Copied from cargo: https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81
 pub fn normalize_path(path: &Path) -> PathBuf {
+    let path = expand_tilde(path);
     let mut components = path.components().peekable();
     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
         components.next();
@@ -163,12 +194,17 @@ pub fn normalize_path(path: &Path) -> PathBuf {
     ret
 }
 
-// Returns the canonical, absolute form of a path with all intermediate components normalized.
-//
-// This function is used instead of `std::fs::canonicalize` because we don't want to verify
-// here if the path exists, just normalize it's components.
+/// Returns the canonical, absolute form of a path with all intermediate components normalized.
+///
+/// This function is used instead of `std::fs::canonicalize` because we don't want to verify
+/// here if the path exists, just normalize it's components.
 pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> {
-    std::env::current_dir().map(|current_dir| normalize_path(&current_dir.join(path)))
+    let normalized = normalize_path(path);
+    if normalized.is_absolute() {
+        Ok(normalized)
+    } else {
+        std::env::current_dir().map(|current_dir| current_dir.join(normalized))
+    }
 }
 
 use helix_lsp::lsp;
@@ -709,12 +745,19 @@ impl Document {
         &self.selections[&view_id]
     }
 
-    pub fn relative_path(&self) -> Option<&Path> {
+    pub fn relative_path(&self) -> Option<PathBuf> {
         let cwdir = std::env::current_dir().expect("couldn't determine current directory");
 
-        self.path
-            .as_ref()
-            .map(|path| path.strip_prefix(cwdir).unwrap_or(path))
+        self.path.as_ref().map(|path| {
+            let path = fold_home_dir(path);
+            if path.is_relative() {
+                path
+            } else {
+                path.strip_prefix(cwdir)
+                    .map(|p| p.to_path_buf())
+                    .unwrap_or(path)
+            }
+        })
     }
 
     // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {

From 52fb90b81eb6eb48ed64aceb7e6e1527b25cd998 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:37:40 +0200
Subject: [PATCH 09/31] Add `MethodCall`, `ProgressStatus`, `LspProgressMap`

---
 helix-lsp/src/lib.rs | 98 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 98 insertions(+)

diff --git a/helix-lsp/src/lib.rs b/helix-lsp/src/lib.rs
index cff62492..be1e23a5 100644
--- a/helix-lsp/src/lib.rs
+++ b/helix-lsp/src/lib.rs
@@ -181,6 +181,30 @@ pub mod util {
     }
 }
 
+#[derive(Debug, PartialEq, Clone)]
+pub enum MethodCall {
+    WorkDoneProgressCreate(lsp::WorkDoneProgressCreateParams),
+}
+
+impl MethodCall {
+    pub fn parse(method: &str, params: jsonrpc::Params) -> Option<MethodCall> {
+        use lsp::request::Request;
+        let request = match method {
+            lsp::request::WorkDoneProgressCreate::METHOD => {
+                let params: lsp::WorkDoneProgressCreateParams = params
+                    .parse()
+                    .expect("Failed to parse WorkDoneCreate params");
+                Self::WorkDoneProgressCreate(params)
+            }
+            _ => {
+                log::warn!("unhandled lsp request: {}", method);
+                return None;
+            }
+        };
+        Some(request)
+    }
+}
+
 #[derive(Debug, PartialEq, Clone)]
 pub enum Notification {
     PublishDiagnostics(lsp::PublishDiagnosticsParams),
@@ -275,6 +299,80 @@ impl Registry {
     }
 }
 
+#[derive(Debug)]
+pub enum ProgressStatus {
+    Created,
+    Started(lsp::WorkDoneProgress),
+}
+
+impl ProgressStatus {
+    pub fn progress(&self) -> Option<&lsp::WorkDoneProgress> {
+        match &self {
+            ProgressStatus::Created => None,
+            ProgressStatus::Started(progress) => Some(&progress),
+        }
+    }
+}
+
+#[derive(Default, Debug)]
+/// Acts as a container for progress reported by language servers. Each server
+/// has a unique id assigned at creation through [`Registry`]. This id is then used
+/// to store the progress in this map.
+pub struct LspProgressMap(HashMap<usize, HashMap<lsp::ProgressToken, ProgressStatus>>);
+
+impl LspProgressMap {
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Returns a map of all tokens coresponding to the lanaguage server with `id`.
+    pub fn progress_map(&self, id: usize) -> Option<&HashMap<lsp::ProgressToken, ProgressStatus>> {
+        self.0.get(&id)
+    }
+
+    /// Returns last progress status for a given server with `id` and `token`.
+    pub fn progress(&self, id: usize, token: &lsp::ProgressToken) -> Option<&ProgressStatus> {
+        self.0.get(&id).and_then(|values| values.get(token))
+    }
+
+    /// Checks if progress `token` for server with `id` is created.
+    pub fn is_created(&mut self, id: usize, token: &lsp::ProgressToken) -> bool {
+        self.0
+            .get(&id)
+            .map(|values| values.get(token).is_some())
+            .unwrap_or_default()
+    }
+
+    pub fn create(&mut self, id: usize, token: lsp::ProgressToken) {
+        self.0
+            .entry(id)
+            .or_default()
+            .insert(token, ProgressStatus::Created);
+    }
+
+    /// Ends the progress by removing the `token` from server with `id`, if removed returns the value.
+    pub fn end_progress(
+        &mut self,
+        id: usize,
+        token: &lsp::ProgressToken,
+    ) -> Option<ProgressStatus> {
+        self.0.get_mut(&id).and_then(|vals| vals.remove(token))
+    }
+
+    /// Updates the progess of `token` for server with `id` to `status`, returns the value replaced or `None`.
+    pub fn update(
+        &mut self,
+        id: usize,
+        token: lsp::ProgressToken,
+        status: lsp::WorkDoneProgress,
+    ) -> Option<ProgressStatus> {
+        self.0
+            .entry(id)
+            .or_default()
+            .insert(token, ProgressStatus::Started(status))
+    }
+}
+
 // REGISTRY = HashMap<LanguageId, Lazy/OnceCell<Arc<RwLock<Client>>>
 // spawn one server per language type, need to spawn one per workspace if server doesn't support
 // workspaces

From a6d39585d8a1cf260262e7f3e3c4741791582049 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:39:37 +0200
Subject: [PATCH 10/31] Add `work_done_token` as parameter to lsp methods

---
 helix-lsp/src/client.rs    | 52 ++++++++++++++++++++------------------
 helix-term/src/commands.rs | 14 +++++-----
 helix-view/src/document.rs |  9 ++++---
 3 files changed, 40 insertions(+), 35 deletions(-)

diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs
index 9ca708a7..0b52681c 100644
--- a/helix-lsp/src/client.rs
+++ b/helix-lsp/src/client.rs
@@ -465,6 +465,7 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
         // ) -> Result<Vec<lsp::CompletionItem>> {
         let params = lsp::CompletionParams {
@@ -473,9 +474,7 @@ impl Client {
                 position,
             },
             // TODO: support these tokens by async receiving and updating the choice list
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
             partial_result_params: lsp::PartialResultParams {
                 partial_result_token: None,
             },
@@ -490,15 +489,14 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
         let params = lsp::SignatureHelpParams {
             text_document_position_params: lsp::TextDocumentPositionParams {
                 text_document,
                 position,
             },
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
             context: None,
             // lsp::SignatureHelpContext
         };
@@ -510,15 +508,14 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
         let params = lsp::HoverParams {
             text_document_position_params: lsp::TextDocumentPositionParams {
                 text_document,
                 position,
             },
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
             // lsp::SignatureHelpContext
         };
 
@@ -531,6 +528,7 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         options: lsp::FormattingOptions,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> anyhow::Result<Vec<lsp::TextEdit>> {
         let capabilities = self.capabilities.as_ref().unwrap();
 
@@ -545,9 +543,7 @@ impl Client {
         let params = lsp::DocumentFormattingParams {
             text_document,
             options,
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
         };
 
         let response = self.request::<lsp::request::Formatting>(params).await?;
@@ -560,6 +556,7 @@ impl Client {
         text_document: lsp::TextDocumentIdentifier,
         range: lsp::Range,
         options: lsp::FormattingOptions,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> anyhow::Result<Vec<lsp::TextEdit>> {
         let capabilities = self.capabilities.as_ref().unwrap();
 
@@ -575,9 +572,7 @@ impl Client {
             text_document,
             range,
             options,
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
         };
 
         let response = self
@@ -596,15 +591,14 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
         let params = lsp::GotoDefinitionParams {
             text_document_position_params: lsp::TextDocumentPositionParams {
                 text_document,
                 position,
             },
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
             partial_result_params: lsp::PartialResultParams {
                 partial_result_token: None,
             },
@@ -617,30 +611,42 @@ impl Client {
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
-        self.goto_request::<lsp::request::GotoDefinition>(text_document, position)
+        self.goto_request::<lsp::request::GotoDefinition>(text_document, position, work_done_token)
     }
 
     pub fn goto_type_definition(
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
-        self.goto_request::<lsp::request::GotoTypeDefinition>(text_document, position)
+        self.goto_request::<lsp::request::GotoTypeDefinition>(
+            text_document,
+            position,
+            work_done_token,
+        )
     }
 
     pub fn goto_implementation(
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
-        self.goto_request::<lsp::request::GotoImplementation>(text_document, position)
+        self.goto_request::<lsp::request::GotoImplementation>(
+            text_document,
+            position,
+            work_done_token,
+        )
     }
 
     pub fn goto_reference(
         &self,
         text_document: lsp::TextDocumentIdentifier,
         position: lsp::Position,
+        work_done_token: Option<lsp::ProgressToken>,
     ) -> impl Future<Output = Result<Value>> {
         let params = lsp::ReferenceParams {
             text_document_position: lsp::TextDocumentPositionParams {
@@ -650,9 +656,7 @@ impl Client {
             context: lsp::ReferenceContext {
                 include_declaration: true,
             },
-            work_done_progress_params: lsp::WorkDoneProgressParams {
-                work_done_token: None,
-            },
+            work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
             partial_result_params: lsp::PartialResultParams {
                 partial_result_token: None,
             },
diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index b2dd0d11..9b916a5e 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1852,7 +1852,7 @@ fn goto_definition(cx: &mut Context) {
     let pos = pos_to_lsp_pos(doc.text(), doc.selection(view.id).cursor(), offset_encoding);
 
     // TODO: handle fails
-    let future = language_server.goto_definition(doc.identifier(), pos);
+    let future = language_server.goto_definition(doc.identifier(), pos, None);
 
     cx.callback(
         future,
@@ -1889,7 +1889,7 @@ fn goto_type_definition(cx: &mut Context) {
     let pos = pos_to_lsp_pos(doc.text(), doc.selection(view.id).cursor(), offset_encoding);
 
     // TODO: handle fails
-    let future = language_server.goto_type_definition(doc.identifier(), pos);
+    let future = language_server.goto_type_definition(doc.identifier(), pos, None);
 
     cx.callback(
         future,
@@ -1926,7 +1926,7 @@ fn goto_implementation(cx: &mut Context) {
     let pos = pos_to_lsp_pos(doc.text(), doc.selection(view.id).cursor(), offset_encoding);
 
     // TODO: handle fails
-    let future = language_server.goto_implementation(doc.identifier(), pos);
+    let future = language_server.goto_implementation(doc.identifier(), pos, None);
 
     cx.callback(
         future,
@@ -1963,7 +1963,7 @@ fn goto_reference(cx: &mut Context) {
     let pos = pos_to_lsp_pos(doc.text(), doc.selection(view.id).cursor(), offset_encoding);
 
     // TODO: handle fails
-    let future = language_server.goto_reference(doc.identifier(), pos);
+    let future = language_server.goto_reference(doc.identifier(), pos, None);
 
     cx.callback(
         future,
@@ -2075,7 +2075,7 @@ fn signature_help(cx: &mut Context) {
     );
 
     // TODO: handle fails
-    let future = language_server.text_document_signature_help(doc.identifier(), pos);
+    let future = language_server.text_document_signature_help(doc.identifier(), pos, None);
 
     cx.callback(
         future,
@@ -2718,7 +2718,7 @@ fn completion(cx: &mut Context) {
     let pos = pos_to_lsp_pos(doc.text(), doc.selection(view.id).cursor(), offset_encoding);
 
     // TODO: handle fails
-    let future = language_server.completion(doc.identifier(), pos);
+    let future = language_server.completion(doc.identifier(), pos, None);
 
     let trigger_offset = doc.selection(view.id).cursor();
 
@@ -2776,7 +2776,7 @@ fn hover(cx: &mut Context) {
     );
 
     // TODO: handle fails
-    let future = language_server.text_document_hover(doc.identifier(), pos);
+    let future = language_server.text_document_hover(doc.identifier(), pos, None);
 
     cx.callback(
         future,
diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs
index fe9c87f7..e9a8097c 100644
--- a/helix-view/src/document.rs
+++ b/helix-view/src/document.rs
@@ -263,10 +263,11 @@ impl Document {
     pub fn format(&mut self, view_id: ViewId) {
         if let Some(language_server) = self.language_server() {
             // TODO: await, no blocking
-            let transaction = helix_lsp::block_on(
-                language_server
-                    .text_document_formatting(self.identifier(), lsp::FormattingOptions::default()),
-            )
+            let transaction = helix_lsp::block_on(language_server.text_document_formatting(
+                self.identifier(),
+                lsp::FormattingOptions::default(),
+                None,
+            ))
             .map(|edits| {
                 helix_lsp::util::generate_transaction_from_edits(
                     self.text(),

From 80b4a690535b2171cc7db2ee6b4daf3bcb4c4f11 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:40:57 +0200
Subject: [PATCH 11/31] Update `client::reply` to be non async

---
 helix-lsp/src/client.rs | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs
index 0b52681c..6554e996 100644
--- a/helix-lsp/src/client.rs
+++ b/helix-lsp/src/client.rs
@@ -165,13 +165,16 @@ impl Client {
     }
 
     /// Reply to a language server RPC call.
-    pub async fn reply(
+    pub fn reply(
         &self,
         id: jsonrpc::Id,
         result: core::result::Result<Value, jsonrpc::Error>,
-    ) -> Result<()> {
+    ) -> impl Future<Output = Result<()>> {
         use jsonrpc::{Failure, Output, Success, Version};
 
+        let server_tx = self.server_tx.clone();
+
+        async move {
         let output = match result {
             Ok(result) => Output::Success(Success {
                 jsonrpc: Some(Version::V2),
@@ -185,12 +188,13 @@ impl Client {
             }),
         };
 
-        self.server_tx
+            server_tx
             .send(Payload::Response(output))
             .map_err(|e| Error::Other(e.into()))?;
 
         Ok(())
     }
+    }
 
     // -------------------------------------------------------------------------------------------
     // General messages

From 38cb934d8f579663ff13496bf79293103863b60b Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:42:34 +0200
Subject: [PATCH 12/31] Add unique id to each lsp client/server pair

---
 helix-lsp/src/client.rs       | 14 ++++++++++++--
 helix-lsp/src/lib.rs          | 25 +++++++++++++++++++------
 helix-lsp/src/transport.rs    | 12 +++++++++---
 helix-term/src/application.rs | 12 ++++++++----
 4 files changed, 48 insertions(+), 15 deletions(-)

diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs
index 6554e996..e14d0197 100644
--- a/helix-lsp/src/client.rs
+++ b/helix-lsp/src/client.rs
@@ -18,6 +18,7 @@ use tokio::{
 
 #[derive(Debug)]
 pub struct Client {
+    id: usize,
     _process: Child,
     server_tx: UnboundedSender<Payload>,
     request_counter: AtomicU64,
@@ -26,7 +27,11 @@ pub struct Client {
 }
 
 impl Client {
-    pub fn start(cmd: &str, args: &[String]) -> Result<(Self, UnboundedReceiver<Call>)> {
+    pub fn start(
+        cmd: &str,
+        args: &[String],
+        id: usize,
+    ) -> Result<(Self, UnboundedReceiver<(usize, Call)>)> {
         let process = Command::new(cmd)
             .args(args)
             .stdin(Stdio::piped())
@@ -43,9 +48,10 @@ impl Client {
         let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
         let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
 
-        let (server_rx, server_tx) = Transport::start(reader, writer, stderr);
+        let (server_rx, server_tx) = Transport::start(reader, writer, stderr, id);
 
         let client = Self {
+            id,
             _process: process,
             server_tx,
             request_counter: AtomicU64::new(0),
@@ -59,6 +65,10 @@ impl Client {
         Ok((client, server_rx))
     }
 
+    pub fn id(&self) -> usize {
+        self.id
+    }
+
     fn next_request_id(&self) -> jsonrpc::Id {
         let id = self.request_counter.fetch_add(1, Ordering::Relaxed);
         jsonrpc::Id::Num(id)
diff --git a/helix-lsp/src/lib.rs b/helix-lsp/src/lib.rs
index be1e23a5..774de075 100644
--- a/helix-lsp/src/lib.rs
+++ b/helix-lsp/src/lib.rs
@@ -13,7 +13,10 @@ use helix_core::syntax::LanguageConfiguration;
 
 use std::{
     collections::{hash_map::Entry, HashMap},
-    sync::Arc,
+    sync::{
+        atomic::{AtomicUsize, Ordering},
+        Arc,
+    },
 };
 
 use serde::{Deserialize, Serialize};
@@ -254,9 +257,10 @@ impl Notification {
 
 #[derive(Debug)]
 pub struct Registry {
-    inner: HashMap<LanguageId, Arc<Client>>,
+    inner: HashMap<LanguageId, (usize, Arc<Client>)>,
 
-    pub incoming: SelectAll<UnboundedReceiverStream<Call>>,
+    counter: AtomicUsize,
+    pub incoming: SelectAll<UnboundedReceiverStream<(usize, Call)>>,
 }
 
 impl Default for Registry {
@@ -269,10 +273,18 @@ impl Registry {
     pub fn new() -> Self {
         Self {
             inner: HashMap::new(),
+            counter: AtomicUsize::new(0),
             incoming: SelectAll::new(),
         }
     }
 
+    pub fn get_by_id(&mut self, id: usize) -> Option<&Client> {
+        self.inner
+            .values()
+            .find(|(client_id, _)| client_id == &id)
+            .map(|(_, client)| client.as_ref())
+    }
+
     pub fn get(&mut self, language_config: &LanguageConfiguration) -> Result<Arc<Client>> {
         if let Some(config) = &language_config.language_server {
             // avoid borrow issues
@@ -280,16 +292,17 @@ impl Registry {
             let s_incoming = &mut self.incoming;
 
             match inner.entry(language_config.scope.clone()) {
-                Entry::Occupied(language_server) => Ok(language_server.get().clone()),
+                Entry::Occupied(entry) => Ok(entry.get().1.clone()),
                 Entry::Vacant(entry) => {
                     // initialize a new client
-                    let (mut client, incoming) = Client::start(&config.command, &config.args)?;
+                    let id = self.counter.fetch_add(1, Ordering::Relaxed);
+                    let (mut client, incoming) = Client::start(&config.command, &config.args, id)?;
                     // TODO: run this async without blocking
                     futures_executor::block_on(client.initialize())?;
                     s_incoming.push(UnboundedReceiverStream::new(incoming));
                     let client = Arc::new(client);
 
-                    entry.insert(client.clone());
+                    entry.insert((id, client.clone()));
                     Ok(client)
                 }
             }
diff --git a/helix-lsp/src/transport.rs b/helix-lsp/src/transport.rs
index e8068323..29ce2e84 100644
--- a/helix-lsp/src/transport.rs
+++ b/helix-lsp/src/transport.rs
@@ -33,7 +33,8 @@ enum ServerMessage {
 
 #[derive(Debug)]
 pub struct Transport {
-    client_tx: UnboundedSender<jsonrpc::Call>,
+    id: usize,
+    client_tx: UnboundedSender<(usize, jsonrpc::Call)>,
     client_rx: UnboundedReceiver<Payload>,
 
     pending_requests: HashMap<jsonrpc::Id, Sender<Result<Value>>>,
@@ -48,11 +49,16 @@ impl Transport {
         server_stdout: BufReader<ChildStdout>,
         server_stdin: BufWriter<ChildStdin>,
         server_stderr: BufReader<ChildStderr>,
-    ) -> (UnboundedReceiver<jsonrpc::Call>, UnboundedSender<Payload>) {
+        id: usize,
+    ) -> (
+        UnboundedReceiver<(usize, jsonrpc::Call)>,
+        UnboundedSender<Payload>,
+    ) {
         let (client_tx, rx) = unbounded_channel();
         let (tx, client_rx) = unbounded_channel();
 
         let transport = Self {
+            id,
             server_stdout,
             server_stdin,
             server_stderr,
@@ -156,7 +162,7 @@ impl Transport {
         match msg {
             ServerMessage::Output(output) => self.process_request_response(output).await?,
             ServerMessage::Call(call) => {
-                self.client_tx.send(call).unwrap();
+                self.client_tx.send((self.id, call)).unwrap();
                 // let notification = Notification::parse(&method, params);
             }
         };
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index f5cba365..3f1d6a10 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -109,8 +109,8 @@ impl Application {
                 event = reader.next() => {
                     self.handle_terminal_events(event)
                 }
-                Some(call) = self.editor.language_servers.incoming.next() => {
-                    self.handle_language_server_message(call).await
+                Some((id, call)) = self.editor.language_servers.incoming.next() => {
+                    self.handle_language_server_message(call, id).await
                 }
                 Some(callback) = &mut self.callbacks.next() => {
                     self.handle_language_server_callback(callback)
@@ -153,8 +153,12 @@ impl Application {
         }
     }
 
-    pub async fn handle_language_server_message(&mut self, call: helix_lsp::Call) {
-        use helix_lsp::{Call, Notification};
+    pub async fn handle_language_server_message(
+        &mut self,
+        call: helix_lsp::Call,
+        server_id: usize,
+    ) {
+        use helix_lsp::{Call, MethodCall, Notification};
         match call {
             Call::Notification(helix_lsp::jsonrpc::Notification { method, params, .. }) => {
                 let notification = match Notification::parse(&method, params) {

From e1109a5a010d02b34c2a8f68726fcdae47d44f2d Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:43:24 +0200
Subject: [PATCH 13/31] Update handling of progress notification

---
 helix-term/src/application.rs | 67 +++++++++++++++++++++--------------
 1 file changed, 41 insertions(+), 26 deletions(-)

diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 3f1d6a10..80b9655a 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -1,4 +1,4 @@
-use helix_lsp::lsp;
+use helix_lsp::{lsp, LspProgressMap};
 use helix_view::{document::Mode, Document, Editor, Theme, View};
 
 use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui};
@@ -9,6 +9,7 @@ use std::{
     future::Future,
     io::{self, stdout, Stdout, Write},
     path::PathBuf,
+    pin::Pin,
     sync::Arc,
     time::Duration,
 };
@@ -23,7 +24,6 @@ use crossterm::{
 use tui::layout::Rect;
 
 use futures_util::stream::FuturesUnordered;
-use std::pin::Pin;
 
 type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
 pub type LspCallback =
@@ -37,6 +37,8 @@ pub struct Application {
     editor: Editor,
 
     callbacks: LspCallbacks,
+
+    lsp_progress: LspProgressMap,
 }
 
 impl Application {
@@ -74,6 +76,7 @@ impl Application {
             editor,
 
             callbacks: FuturesUnordered::new(),
+            lsp_progress: LspProgressMap::new(),
         };
 
         Ok(app)
@@ -246,55 +249,67 @@ impl Application {
                         log::warn!("unhandled window/logMessage: {:?}", params);
                     }
                     Notification::ProgressMessage(params) => {
-                        let token = match params.token {
-                            lsp::NumberOrString::Number(n) => n.to_string(),
-                            lsp::NumberOrString::String(s) => s,
-                        };
-                        let msg = {
-                            let lsp::ProgressParamsValue::WorkDone(work) = params.value;
-                            let parts = match work {
+                        let lsp::ProgressParams { token, value } = params;
+
+                        let lsp::ProgressParamsValue::WorkDone(work) = value;
+                        let parts = match &work {
                                 lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin {
                                     title,
                                     message,
                                     percentage,
                                     ..
-                                }) => (Some(title), message, percentage.map(|n| n.to_string())),
+                            }) => (Some(title), message, percentage),
                                 lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport {
                                     message,
                                     percentage,
                                     ..
-                                }) => (None, message, percentage.map(|n| n.to_string())),
-                                lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd {
-                                    message,
-                                }) => {
-                                    if let Some(message) = message {
-                                        (None, Some(message), None)
+                            }) => (None, message, percentage),
+                            lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd { message }) => {
+                                if message.is_some() {
+                                    (None, message, &None)
                                     } else {
+                                    self.lsp_progress.end_progress(server_id, &token);
                                         self.editor.clear_status();
                                         return;
                                     }
                                 }
                             };
-                            match parts {
+                        let token_d: &dyn std::fmt::Display = match &token {
+                            lsp::NumberOrString::Number(n) => n,
+                            lsp::NumberOrString::String(s) => s,
+                        };
+
+                        let status = match parts {
                                 (Some(title), Some(message), Some(percentage)) => {
-                                    format!("{}% {} - {}", percentage, title, message)
+                                format!("[{}] {}% {} - {}", token_d, percentage, title, message)
                                 }
                                 (Some(title), None, Some(percentage)) => {
-                                    format!("{}% {}", percentage, title)
+                                format!("[{}] {}% {}", token_d, percentage, title)
                                 }
                                 (Some(title), Some(message), None) => {
-                                    format!("{} - {}", title, message)
+                                format!("[{}] {} - {}", token_d, title, message)
                                 }
                                 (None, Some(message), Some(percentage)) => {
-                                    format!("{}% {}", percentage, message)
+                                format!("[{}] {}% {}", token_d, percentage, message)
                                 }
-                                (Some(title), None, None) => title,
-                                (None, Some(message), None) => message,
-                                (None, None, Some(percentage)) => format!("{}%", percentage),
-                                (None, None, None) => "".into(),
+                            (Some(title), None, None) => {
+                                format!("[{}] {}", token_d, title)
                             }
+                            (None, Some(message), None) => {
+                                format!("[{}] {}", token_d, message)
+                            }
+                            (None, None, Some(percentage)) => {
+                                format!("[{}] {}%", token_d, percentage)
+                            }
+                            (None, None, None) => format!("[{}]", token_d),
                         };
-                        let status = format!("[{}] {}", token, msg);
+
+                        if let lsp::WorkDoneProgress::End(_) = work {
+                            self.lsp_progress.end_progress(server_id, &token);
+                        } else {
+                            self.lsp_progress.update(server_id, token, work);
+                        }
+
                         self.editor.set_status(status);
                         self.render();
                     }

From 612511dc9859cb232b6c84b8d50461f5d181c9dc Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:43:44 +0200
Subject: [PATCH 14/31] Handle workDoneProgress/create request

---
 helix-term/src/application.rs | 100 ++++++++++++++++++++++++++--------
 1 file changed, 76 insertions(+), 24 deletions(-)

diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 80b9655a..b2b49be5 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -253,45 +253,45 @@ impl Application {
 
                         let lsp::ProgressParamsValue::WorkDone(work) = value;
                         let parts = match &work {
-                                lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin {
-                                    title,
-                                    message,
-                                    percentage,
-                                    ..
+                            lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin {
+                                title,
+                                message,
+                                percentage,
+                                ..
                             }) => (Some(title), message, percentage),
-                                lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport {
-                                    message,
-                                    percentage,
-                                    ..
+                            lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport {
+                                message,
+                                percentage,
+                                ..
                             }) => (None, message, percentage),
                             lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd { message }) => {
                                 if message.is_some() {
                                     (None, message, &None)
-                                    } else {
+                                } else {
                                     self.lsp_progress.end_progress(server_id, &token);
-                                        self.editor.clear_status();
-                                        return;
-                                    }
+                                    self.editor.clear_status();
+                                    return;
                                 }
-                            };
+                            }
+                        };
                         let token_d: &dyn std::fmt::Display = match &token {
                             lsp::NumberOrString::Number(n) => n,
                             lsp::NumberOrString::String(s) => s,
                         };
 
                         let status = match parts {
-                                (Some(title), Some(message), Some(percentage)) => {
+                            (Some(title), Some(message), Some(percentage)) => {
                                 format!("[{}] {}% {} - {}", token_d, percentage, title, message)
-                                }
-                                (Some(title), None, Some(percentage)) => {
+                            }
+                            (Some(title), None, Some(percentage)) => {
                                 format!("[{}] {}% {}", token_d, percentage, title)
-                                }
-                                (Some(title), Some(message), None) => {
+                            }
+                            (Some(title), Some(message), None) => {
                                 format!("[{}] {} - {}", token_d, title, message)
-                                }
-                                (None, Some(message), Some(percentage)) => {
+                            }
+                            (None, Some(message), Some(percentage)) => {
                                 format!("[{}] {}% {}", token_d, percentage, message)
-                                }
+                            }
                             (Some(title), None, None) => {
                                 format!("[{}] {}", token_d, title)
                             }
@@ -316,9 +316,61 @@ impl Application {
                     _ => unreachable!(),
                 }
             }
-            Call::MethodCall(call) => {
-                error!("Method not found {}", call.method);
+            Call::MethodCall(helix_lsp::jsonrpc::MethodCall {
+                method,
+                params,
+                jsonrpc,
+                id,
+            }) => {
+                let call = match MethodCall::parse(&method, params) {
+                    Some(call) => call,
+                    None => {
+                        error!("Method not found {}", method);
+                        return;
+                    }
+                };
 
+                match call {
+                    MethodCall::WorkDoneProgressCreate(params) => {
+                        self.lsp_progress.create(server_id, params.token);
+
+                        let doc = self.editor.documents().find(|doc| {
+                            doc.language_server()
+                                .map(|server| server.id() == server_id)
+                                .unwrap_or_default()
+                        });
+                        match doc {
+                            Some(doc) => {
+                                // it's ok to unwrap, we check for the language server before
+                                let server = doc.language_server().unwrap();
+                                tokio::spawn(server.reply(id, Ok(serde_json::Value::Null)));
+                            }
+                            None => {
+                                if let Some(server) =
+                                    self.editor.language_servers.get_by_id(server_id)
+                                {
+                                    log::warn!(
+                                        "missing document with language server id `{}`",
+                                        server_id
+                                    );
+                                    tokio::spawn(server.reply(
+                                        id,
+                                        Err(helix_lsp::jsonrpc::Error {
+                                            code: helix_lsp::jsonrpc::ErrorCode::InternalError,
+                                            message: "document missing".to_string(),
+                                            data: None,
+                                        }),
+                                    ));
+                                } else {
+                                    log::warn!(
+                                        "can't find language server with id `{}`",
+                                        server_id
+                                    );
+                                }
+                            }
+                        }
+                    }
+                }
                 // self.language_server.reply(
                 //     call.id,
                 //     // TODO: make a Into trait that can cast to Err(jsonrpc::Error)

From d095ec15d4672ec5fb3b1f4a85282db31f40c6ea Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:44:01 +0200
Subject: [PATCH 15/31] Reenable `work_done_progress` capability

---
 helix-lsp/src/client.rs | 35 +++++++++++++++++------------------
 1 file changed, 17 insertions(+), 18 deletions(-)

diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs
index e14d0197..245eb854 100644
--- a/helix-lsp/src/client.rs
+++ b/helix-lsp/src/client.rs
@@ -185,25 +185,25 @@ impl Client {
         let server_tx = self.server_tx.clone();
 
         async move {
-        let output = match result {
-            Ok(result) => Output::Success(Success {
-                jsonrpc: Some(Version::V2),
-                id,
-                result,
-            }),
-            Err(error) => Output::Failure(Failure {
-                jsonrpc: Some(Version::V2),
-                id,
-                error,
-            }),
-        };
+            let output = match result {
+                Ok(result) => Output::Success(Success {
+                    jsonrpc: Some(Version::V2),
+                    id,
+                    result,
+                }),
+                Err(error) => Output::Failure(Failure {
+                    jsonrpc: Some(Version::V2),
+                    id,
+                    error,
+                }),
+            };
 
             server_tx
-            .send(Payload::Response(output))
-            .map_err(|e| Error::Other(e.into()))?;
+                .send(Payload::Response(output))
+                .map_err(|e| Error::Other(e.into()))?;
 
-        Ok(())
-    }
+            Ok(())
+        }
     }
 
     // -------------------------------------------------------------------------------------------
@@ -243,8 +243,7 @@ impl Client {
                     ..Default::default()
                 }),
                 window: Some(lsp::WindowClientCapabilities {
-                    // TODO: temporarily disabled until we implement handling for window/workDoneProgress/create
-                    // work_done_progress: Some(true),
+                    work_done_progress: Some(true),
                     ..Default::default()
                 }),
                 ..Default::default()

From bbefc1db63f7c3933adfd91fc404db9850af8399 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 05:57:36 +0200
Subject: [PATCH 16/31] Add an option to disable display of progress in status
 bar

---
 book/src/configuration.md     |  8 ++++++++
 helix-term/src/application.rs |  8 ++++++--
 helix-term/src/config.rs      | 10 ++++++++++
 3 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/book/src/configuration.md b/book/src/configuration.md
index 649aa21f..31c267cf 100644
--- a/book/src/configuration.md
+++ b/book/src/configuration.md
@@ -1,5 +1,12 @@
 # Configuration
 
+## LSP
+
+To disable language server progress report from being displayed in the status bar add this option to your `config.toml`:
+```toml
+lsp_progress = false
+```
+
 ## Theme
 
 Use a custom theme by placing a theme.toml in your config directory (i.e ~/.config/helix/theme.toml). The default theme.toml can be found [here](https://github.com/helix-editor/helix/blob/master/theme.toml), and user submitted themes [here](https://github.com/helix-editor/helix/blob/master/contrib/themes).
@@ -87,3 +94,4 @@ Possible keys:
 These keys match [tree-sitter scopes](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#theme). We half-follow the common scopes from [macromates language grammars](https://macromates.com/manual/en/language_grammars) with some differences.
 
 For a given highlight produced, styling will be determined based on the longest matching theme key. So it's enough to provide function to highlight `function.macro` and `function.builtin` as well, but you can use more specific scopes to highlight specific cases differently.
+
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index b2b49be5..aa2ce884 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -39,6 +39,7 @@ pub struct Application {
     callbacks: LspCallbacks,
 
     lsp_progress: LspProgressMap,
+    lsp_progress_enabled: bool,
 }
 
 impl Application {
@@ -77,6 +78,7 @@ impl Application {
 
             callbacks: FuturesUnordered::new(),
             lsp_progress: LspProgressMap::new(),
+            lsp_progress_enabled: config.global.lsp_progress,
         };
 
         Ok(app)
@@ -310,8 +312,10 @@ impl Application {
                             self.lsp_progress.update(server_id, token, work);
                         }
 
-                        self.editor.set_status(status);
-                        self.render();
+                        if self.lsp_progress_enabled {
+                            self.editor.set_status(status);
+                            self.render();
+                        }
                     }
                     _ => unreachable!(),
                 }
diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs
index bd84e0b1..2b8b475b 100644
--- a/helix-term/src/config.rs
+++ b/helix-term/src/config.rs
@@ -5,13 +5,20 @@ use serde::{de::Error as SerdeError, Deserialize, Serialize};
 
 use crate::keymap::{parse_keymaps, Keymaps};
 
+#[derive(Default)]
+pub struct GlobalConfig {
+    pub lsp_progress: bool,
+}
+
 #[derive(Default)]
 pub struct Config {
+    pub global: GlobalConfig,
     pub keymaps: Keymaps,
 }
 
 #[derive(Serialize, Deserialize)]
 struct TomlConfig {
+    lsp_progress: Option<bool>,
     keys: Option<HashMap<String, HashMap<String, String>>>,
 }
 
@@ -22,6 +29,9 @@ impl<'de> Deserialize<'de> for Config {
     {
         let config = TomlConfig::deserialize(deserializer)?;
         Ok(Self {
+            global: GlobalConfig {
+                lsp_progress: config.lsp_progress.unwrap_or(true),
+            },
             keymaps: config
                 .keys
                 .map(|r| parse_keymaps(&r))

From a3cb79ebaaaa7682c7c7b007ed928b24f80cf3c2 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 06:09:42 +0200
Subject: [PATCH 17/31] Use kebab-case for config

---
 book/src/configuration.md | 2 +-
 helix-term/src/config.rs  | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/book/src/configuration.md b/book/src/configuration.md
index 31c267cf..3ff02adb 100644
--- a/book/src/configuration.md
+++ b/book/src/configuration.md
@@ -4,7 +4,7 @@
 
 To disable language server progress report from being displayed in the status bar add this option to your `config.toml`:
 ```toml
-lsp_progress = false
+lsp-progress = false
 ```
 
 ## Theme
diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs
index 2b8b475b..d2bbe84f 100644
--- a/helix-term/src/config.rs
+++ b/helix-term/src/config.rs
@@ -17,6 +17,7 @@ pub struct Config {
 }
 
 #[derive(Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
 struct TomlConfig {
     lsp_progress: Option<bool>,
     keys: Option<HashMap<String, HashMap<String, String>>>,

From b1cb98283dacf98fb15e5fbcdb12d0be4161190b Mon Sep 17 00:00:00 2001
From: Gokul Soumya <gokulps15@gmail.com>
Date: Fri, 18 Jun 2021 14:20:25 +0530
Subject: [PATCH 18/31] Fix indent regression issue with o, O

Indents were no longer respected with `o` and `O`. Using counts resulted
in multiple cursors in the same line instead of cursors on each line.

Introduced by 47d2e3ae
---
 helix-term/src/commands.rs | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index 9b916a5e..a8610223 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1641,7 +1641,8 @@ fn open(cx: &mut Context, open: Open) {
             true,
         );
         let indent = doc.indent_unit().repeat(indent_level);
-        let mut text = String::with_capacity(1 + indent.len());
+        let indent_len = indent.len();
+        let mut text = String::with_capacity(1 + indent_len);
         text.push('\n');
         text.push_str(&indent);
         let text = text.repeat(count);
@@ -1653,7 +1654,10 @@ fn open(cx: &mut Context, open: Open) {
             offs + linend_index + 1
         };
         for i in 0..count {
-            ranges.push(Range::new(pos + i, pos + i));
+            // pos                    -> beginning of reference line,
+            // + (i * (1+indent_len)) -> beginning of i'th line from pos
+            // + indent_len ->        -> indent for i'th line
+            ranges.push(Range::point(pos + (i * (1 + indent_len)) + indent_len));
         }
 
         offs += text.chars().count();

From 1bb3b778adf6d03c10898f17858c6881afcd3d1f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Wojciech=20K=C4=99pka?=
 <46892771+wojciechkepka@users.noreply.github.com>
Date: Fri, 18 Jun 2021 15:41:49 +0200
Subject: [PATCH 19/31] Don't derive `Default` for `GlobalConfig` (#297)

We shouldn't derive Default because `lsp_progress` by default should be turned on (opt out).
---
 helix-term/src/config.rs | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs
index d2bbe84f..e5e17753 100644
--- a/helix-term/src/config.rs
+++ b/helix-term/src/config.rs
@@ -5,11 +5,16 @@ use serde::{de::Error as SerdeError, Deserialize, Serialize};
 
 use crate::keymap::{parse_keymaps, Keymaps};
 
-#[derive(Default)]
 pub struct GlobalConfig {
     pub lsp_progress: bool,
 }
 
+impl Default for GlobalConfig {
+    fn default() -> Self {
+        Self { lsp_progress: true }
+    }
+}
+
 #[derive(Default)]
 pub struct Config {
     pub global: GlobalConfig,

From 0151826233e301092e05b156a6172e2d3cde5118 Mon Sep 17 00:00:00 2001
From: rypervenche <rypervenche@users.noreply.github.com>
Date: Fri, 18 Jun 2021 08:42:25 -0500
Subject: [PATCH 20/31] Removed unneeded escaping in Markdown docs (#299)

---
 book/src/configuration.md | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/book/src/configuration.md b/book/src/configuration.md
index 3ff02adb..51a08e03 100644
--- a/book/src/configuration.md
+++ b/book/src/configuration.md
@@ -39,11 +39,11 @@ Possible modifiers:
 | `dim`          |
 | `italic`       |
 | `underlined`   |
-| `slow\_blink`  |
-| `rapid\_blink` |
+| `slow_blink`  |
+| `rapid_blink` |
 | `reversed`     |
 | `hidden`       |
-| `crossed\_out` |
+| `crossed_out` |
 
 Possible keys:
 

From b0522239e750d86432ab53e32aeb1fde99474239 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Fri, 18 Jun 2021 08:55:34 -0400
Subject: [PATCH 21/31] Update ropey dependency to 1.3

---
 Cargo.lock            | 4 ++--
 helix-core/Cargo.toml | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 2aedb848..12a03dac 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -672,9 +672,9 @@ checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
 
 [[package]]
 name = "ropey"
-version = "1.2.0"
+version = "1.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f0f3ef16589fdbb3e8fbce3dca944c08e61f39c7f16064b21a257d68ea911a83"
+checksum = "e4b1996ad82fb6b8ac0711329432d80aa1ad5d70a0fe6edd1a9cf6fd2375fbb2"
 dependencies = [
  "smallvec",
 ]
diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml
index f8e15bd7..0f532f5b 100644
--- a/helix-core/Cargo.toml
+++ b/helix-core/Cargo.toml
@@ -14,7 +14,7 @@ embed_runtime = ["rust-embed"]
 [dependencies]
 helix-syntax = { path = "../helix-syntax" }
 
-ropey = "1.2"
+ropey = "1.3"
 smallvec = "1.4"
 tendril = "0.4.2"
 unicode-segmentation = "1.7.1"

From 1c1474c3b8dbab8ca4b9a62220c079ddffb7ed9f Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 20:22:15 +0200
Subject: [PATCH 22/31] Add `ui.statusline.inactive`, use `ui.statusline` for
 statusline text

---
 contrib/themes/bogster.toml |  5 +++--
 contrib/themes/ingrid.toml  |  3 ++-
 contrib/themes/onedark.toml |  1 +
 helix-term/src/ui/editor.rs | 17 +++++++----------
 theme.toml                  |  3 ++-
 5 files changed, 15 insertions(+), 14 deletions(-)

diff --git a/contrib/themes/bogster.toml b/contrib/themes/bogster.toml
index 205e464c..43b422f3 100644
--- a/contrib/themes/bogster.toml
+++ b/contrib/themes/bogster.toml
@@ -31,7 +31,8 @@
 "ui.background" = { bg = "#161c23" }
 "ui.linenr" = { fg = "#415367" }
 "ui.linenr.selected" = { fg = "#e5ded6" }  # TODO
-"ui.statusline" = { bg = "#232d38" }
+"ui.statusline" = { fg = "#e5ded6", bg = "#232d38" }
+"ui.statusline.inactive" = { fg = "#c6b8ad", bg = "#232d38" }
 "ui.popup" = { bg = "#232d38" }
 "ui.window" = { bg = "#232d38" }
 "ui.help" = { bg = "#232d38", fg = "#e5ded6" }
@@ -39,7 +40,7 @@
 "ui.text" = { fg = "#e5ded6" }
 "ui.text.focus" = { fg = "#e5ded6", modifiers= ["bold"] }
 
-"ui.selection" = { bg = "#540099" }
+"ui.selection" = { bg = "#313f4e" }
 "ui.menu.selected" = { fg = "#e5ded6", bg = "#313f4e" }
 
 "warning" = "#dc7759"
diff --git a/contrib/themes/ingrid.toml b/contrib/themes/ingrid.toml
index da333fb8..d32a89d1 100644
--- a/contrib/themes/ingrid.toml
+++ b/contrib/themes/ingrid.toml
@@ -31,7 +31,8 @@
 "ui.background" = { bg = "#FFFCFD" }
 "ui.linenr" = { fg = "#bbbbbb" }
 "ui.linenr.selected" = { fg = "#F3EAE9" }  # TODO
-"ui.statusline" = { bg = "#F3EAE9" }
+"ui.statusline" = { fg = "#250E07", bg = "#F3EAE9" }
+"ui.statusline.inactive" = { fg = "#7b91b3", bg = "#F3EAE9" }
 "ui.popup" = { bg = "#F3EAE9" }
 "ui.window" = { bg = "#D8B8B3" }
 "ui.help" = { bg = "#D8B8B3", fg = "#250E07" }
diff --git a/contrib/themes/onedark.toml b/contrib/themes/onedark.toml
index 4c13a217..65f26725 100644
--- a/contrib/themes/onedark.toml
+++ b/contrib/themes/onedark.toml
@@ -36,6 +36,7 @@
 "ui.linenr.selected" = { fg = "#ABB2BF" }
 "ui.popup" = { bg = "#3E4452" }
 "ui.statusline" = { fg = "#ABB2BF", bg = "#2C323C" }
+"ui.statusline.inactive" = { fg = "#ABB2Bf", bg = "#2C323C" }
 "ui.selection" = { bg = "#3E4452" }
 "ui.text" = { fg = "#ABB2BF", bg = "#282C34" }
 "ui.text.focus" = { fg = "#ABB2BF", bg = "#2C323C", modifiers = ['bold'] }
diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs
index ba5e7574..3dc43d3f 100644
--- a/helix-term/src/ui/editor.rs
+++ b/helix-term/src/ui/editor.rs
@@ -476,18 +476,15 @@ impl EditorView {
             Mode::Select => "SEL",
             Mode::Normal => "NOR",
         };
-        let text_color = if is_focused {
-            theme.get("ui.text.focus")
+        let style = if is_focused {
+            theme.get("ui.statusline")
         } else {
-            theme.get("ui.text")
+            theme.get("ui.statusline.inactive")
         };
         // statusline
-        surface.set_style(
-            Rect::new(viewport.x, viewport.y, viewport.width, 1),
-            theme.get("ui.statusline"),
-        );
+        surface.set_style(Rect::new(viewport.x, viewport.y, viewport.width, 1), style);
         if is_focused {
-            surface.set_string(viewport.x + 1, viewport.y, mode, text_color);
+            surface.set_string(viewport.x + 1, viewport.y, mode, style);
         }
 
         if let Some(path) = doc.relative_path() {
@@ -499,7 +496,7 @@ impl EditorView {
                 viewport.y,
                 title,
                 viewport.width.saturating_sub(6) as usize,
-                text_color,
+                style,
             );
         }
 
@@ -538,7 +535,7 @@ impl EditorView {
             viewport.x + viewport.width.saturating_sub(text_len),
             viewport.y,
             right_side_text,
-            text_color,
+            style,
         );
     }
 
diff --git a/theme.toml b/theme.toml
index 903a5e26..a4f40267 100644
--- a/theme.toml
+++ b/theme.toml
@@ -41,7 +41,8 @@
 "ui.background" = { bg = "#3b224c" } # midnight
 "ui.linenr" = { fg = "#5a5977" } # comet
 "ui.linenr.selected" = { fg = "#dbbfef" } # lilac
-"ui.statusline" = { bg = "#281733" } # revolver
+"ui.statusline" = { fg = "#dbbfef", bg = "#281733" } # revolver
+"ui.statusline.inactive" = { fg = "#a4a0e8",  bg = "#281733" } # revolver
 "ui.popup" = { bg = "#281733" } # revolver
 "ui.window" = { bg = "#452859" } # bossa nova
 "ui.window" = { bg = "#452859" } # bossa nova

From b48054f3ee28db64110f9ddcc13d7f01bb78b357 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Fri, 18 Jun 2021 09:48:31 -0400
Subject: [PATCH 23/31] cargo: add version to local dependencies

First step towards enabling us to publish on crates.io.

See: https://github.com/helix-editor/helix/issues/42
---
 helix-core/Cargo.toml | 2 +-
 helix-lsp/Cargo.toml  | 4 ++--
 helix-term/Cargo.toml | 6 +++---
 helix-view/Cargo.toml | 4 ++--
 4 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml
index 0f532f5b..9ae7aff0 100644
--- a/helix-core/Cargo.toml
+++ b/helix-core/Cargo.toml
@@ -12,7 +12,7 @@ license = "MPL-2.0"
 embed_runtime = ["rust-embed"]
 
 [dependencies]
-helix-syntax = { path = "../helix-syntax" }
+helix-syntax = { version = "0.2", path = "../helix-syntax" }
 
 ropey = "1.3"
 smallvec = "1.4"
diff --git a/helix-lsp/Cargo.toml b/helix-lsp/Cargo.toml
index bcd18a38..185fe447 100644
--- a/helix-lsp/Cargo.toml
+++ b/helix-lsp/Cargo.toml
@@ -8,7 +8,7 @@ license = "MPL-2.0"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-helix-core = { path = "../helix-core" }
+helix-core = { version = "0.2", path = "../helix-core" }
 
 anyhow = "1.0"
 futures-executor = "0.3"
@@ -20,4 +20,4 @@ serde = { version = "1.0", features = ["derive"] }
 serde_json = "1.0"
 thiserror = "1.0"
 tokio = { version = "1.6", features = ["full"] }
-tokio-stream = "0.1.6"
\ No newline at end of file
+tokio-stream = "0.1.6"
diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml
index cda238fe..1b9df2ef 100644
--- a/helix-term/Cargo.toml
+++ b/helix-term/Cargo.toml
@@ -18,9 +18,9 @@ name = "hx"
 path = "src/main.rs"
 
 [dependencies]
-helix-core = { path = "../helix-core" }
-helix-view = { path = "../helix-view", features = ["term"]}
-helix-lsp = { path = "../helix-lsp"}
+helix-core = { version = "0.2", path = "../helix-core" }
+helix-view = { version = "0.2", path = "../helix-view", features = ["term"]}
+helix-lsp = { version = "0.2", path = "../helix-lsp"}
 
 anyhow = "1"
 once_cell = "1.8"
diff --git a/helix-view/Cargo.toml b/helix-view/Cargo.toml
index 593f00e0..db96c9aa 100644
--- a/helix-view/Cargo.toml
+++ b/helix-view/Cargo.toml
@@ -13,8 +13,8 @@ default = ["term"]
 
 [dependencies]
 anyhow = "1"
-helix-core = { path = "../helix-core" }
-helix-lsp = { path = "../helix-lsp"}
+helix-core = { version = "0.2", path = "../helix-core" }
+helix-lsp = { version = "0.2", path = "../helix-lsp"}
 
 # Conversion traits
 tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"], optional = true }

From db5bdf4f2da954595d6fe83ef4ace255883726e9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Fri, 18 Jun 2021 09:53:29 -0400
Subject: [PATCH 24/31] Run cargo-diet

cargo-diet is a helper for computing the optimal `include` directives
for Cargo.toml manifests.
https://github.com/the-lean-crate/cargo-diet
---
 helix-core/Cargo.toml   | 1 +
 helix-syntax/Cargo.toml | 7 +++++--
 helix-term/Cargo.toml   | 1 +
 helix-tui/Cargo.toml    | 1 +
 4 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml
index 9ae7aff0..9c1c6802 100644
--- a/helix-core/Cargo.toml
+++ b/helix-core/Cargo.toml
@@ -4,6 +4,7 @@ version = "0.2.0"
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+include = ["src/**/*", "README.md"]
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
diff --git a/helix-syntax/Cargo.toml b/helix-syntax/Cargo.toml
index 472b56c0..3c71fc34 100644
--- a/helix-syntax/Cargo.toml
+++ b/helix-syntax/Cargo.toml
@@ -4,8 +4,11 @@ version = "0.2.0"
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+description = "Tree-sitter grammars support"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
+include = ["src/**/*", "languages/**/*", "build.rs", "!**/docs/**/*", "!**/test/**/*", "!**/examples/**/*", "!**/build/**/*"]
 
 [dependencies]
 tree-sitter = "0.19"
diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml
index 1b9df2ef..e1e5da56 100644
--- a/helix-term/Cargo.toml
+++ b/helix-term/Cargo.toml
@@ -5,6 +5,7 @@ description = "A post-modern text editor."
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+include = ["src/**/*", "README.md"]
 
 [package.metadata.nix]
 build = true
diff --git a/helix-tui/Cargo.toml b/helix-tui/Cargo.toml
index 7ba16553..beab049c 100644
--- a/helix-tui/Cargo.toml
+++ b/helix-tui/Cargo.toml
@@ -7,6 +7,7 @@ A library to build rich terminal user interfaces or dashboards
 """
 edition = "2018"
 license = "MPL-2.0"
+include = ["src/**/*", "README.md"]
 
 [features]
 default = ["crossterm"]

From 03d1ca7b0a2610b5a5ee2956722c0a1fbdc2180c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= <benoit.cortier@fried-world.eu>
Date: Fri, 18 Jun 2021 10:41:03 -0400
Subject: [PATCH 25/31] cargo: add more metadata to manifests

---
 helix-core/Cargo.toml | 7 ++++---
 helix-lsp/Cargo.toml  | 4 ++++
 helix-term/Cargo.toml | 3 +++
 helix-tui/Cargo.toml  | 3 +++
 helix-view/Cargo.toml | 4 ++++
 5 files changed, 18 insertions(+), 3 deletions(-)

diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml
index 9c1c6802..13ac35fb 100644
--- a/helix-core/Cargo.toml
+++ b/helix-core/Cargo.toml
@@ -4,11 +4,12 @@ version = "0.2.0"
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+description = "Helix editor core editing primitives"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
 include = ["src/**/*", "README.md"]
 
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-
 [features]
 embed_runtime = ["rust-embed"]
 
diff --git a/helix-lsp/Cargo.toml b/helix-lsp/Cargo.toml
index 185fe447..2c1b813d 100644
--- a/helix-lsp/Cargo.toml
+++ b/helix-lsp/Cargo.toml
@@ -4,6 +4,10 @@ version = "0.2.0"
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+description = "LSP client implementation for Helix project"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml
index e1e5da56..385af64c 100644
--- a/helix-term/Cargo.toml
+++ b/helix-term/Cargo.toml
@@ -5,6 +5,9 @@ description = "A post-modern text editor."
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+categories = ["editor", "command-line-utilities"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
 include = ["src/**/*", "README.md"]
 
 [package.metadata.nix]
diff --git a/helix-tui/Cargo.toml b/helix-tui/Cargo.toml
index beab049c..89fa755d 100644
--- a/helix-tui/Cargo.toml
+++ b/helix-tui/Cargo.toml
@@ -7,6 +7,9 @@ A library to build rich terminal user interfaces or dashboards
 """
 edition = "2018"
 license = "MPL-2.0"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
 include = ["src/**/*", "README.md"]
 
 [features]
diff --git a/helix-view/Cargo.toml b/helix-view/Cargo.toml
index db96c9aa..13539a5a 100644
--- a/helix-view/Cargo.toml
+++ b/helix-view/Cargo.toml
@@ -4,6 +4,10 @@ version = "0.2.0"
 authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
 edition = "2018"
 license = "MPL-2.0"
+description = "UI abstractions for use in backends"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 

From c2aad859b12e01c7724f16ddf957e6db2b3c8a60 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Sat, 19 Jun 2021 04:56:50 +0200
Subject: [PATCH 26/31] Handle language server shutdown with timeout

---
 helix-lsp/src/client.rs       | 15 +++++++++++++++
 helix-lsp/src/lib.rs          |  4 ++++
 helix-term/src/application.rs | 13 ++++++++++++-
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs
index 245eb854..101d2f9b 100644
--- a/helix-lsp/src/client.rs
+++ b/helix-lsp/src/client.rs
@@ -272,6 +272,21 @@ impl Client {
         self.notify::<lsp::notification::Exit>(())
     }
 
+    /// Tries to shut down the language server but returns
+    /// early if server responds with an error.
+    pub async fn shutdown_and_exit(&self) -> Result<()> {
+        self.shutdown().await?;
+        self.exit().await
+    }
+
+    /// Forcefully shuts down the language server ignoring any errors.
+    pub async fn force_shutdown(&self) -> Result<()> {
+        if let Err(e) = self.shutdown().await {
+            log::warn!("language server failed to terminate gracefully - {}", e);
+        }
+        self.exit().await
+    }
+
     // -------------------------------------------------------------------------------------------
     // Text document
     // -------------------------------------------------------------------------------------------
diff --git a/helix-lsp/src/lib.rs b/helix-lsp/src/lib.rs
index 774de075..49d5527f 100644
--- a/helix-lsp/src/lib.rs
+++ b/helix-lsp/src/lib.rs
@@ -310,6 +310,10 @@ impl Registry {
             Err(Error::LspNotDefined)
         }
     }
+
+    pub fn iter_clients(&self) -> impl Iterator<Item = &Arc<Client>> {
+        self.inner.values().map(|(_, client)| client)
+    }
 }
 
 #[derive(Debug)]
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index aa2ce884..1f02ac4f 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -23,7 +23,7 @@ use crossterm::{
 
 use tui::layout::Rect;
 
-use futures_util::stream::FuturesUnordered;
+use futures_util::{future, stream::FuturesUnordered};
 
 type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
 pub type LspCallback =
@@ -406,6 +406,17 @@ impl Application {
 
         self.event_loop().await;
 
+        tokio::time::timeout(
+            Duration::from_millis(500),
+            future::join_all(
+                self.editor
+                    .language_servers
+                    .iter_clients()
+                    .map(|client| client.force_shutdown()),
+            ),
+        )
+        .await;
+
         // reset cursor shape
         write!(stdout, "\x1B[2 q");
 

From dd0af78079342b46ae1f4d1b265c7e0cd7519631 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Sat, 19 Jun 2021 04:57:05 +0200
Subject: [PATCH 27/31] Fix unwraps in lsp::transport

---
 helix-lsp/src/transport.rs | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/helix-lsp/src/transport.rs b/helix-lsp/src/transport.rs
index 29ce2e84..df55bbf6 100644
--- a/helix-lsp/src/transport.rs
+++ b/helix-lsp/src/transport.rs
@@ -1,4 +1,5 @@
 use crate::Result;
+use anyhow::Context;
 use jsonrpc_core as jsonrpc;
 use log::{error, info};
 use serde::{Deserialize, Serialize};
@@ -90,7 +91,7 @@ impl Transport {
 
             match (parts.next(), parts.next(), parts.next()) {
                 (Some("Content-Length"), Some(value), None) => {
-                    content_length = Some(value.parse().unwrap());
+                    content_length = Some(value.parse().context("invalid content length")?);
                 }
                 (Some(_), Some(_), None) => {}
                 _ => {
@@ -103,12 +104,12 @@ impl Transport {
             }
         }
 
-        let content_length = content_length.unwrap();
+        let content_length = content_length.context("missing content length")?;
 
         //TODO: reuse vector
         let mut content = vec![0; content_length];
         reader.read_exact(&mut content).await?;
-        let msg = String::from_utf8(content).unwrap();
+        let msg = String::from_utf8(content).context("invalid utf8 from server")?;
 
         info!("<- {}", msg);
 
@@ -162,7 +163,9 @@ impl Transport {
         match msg {
             ServerMessage::Output(output) => self.process_request_response(output).await?,
             ServerMessage::Call(call) => {
-                self.client_tx.send((self.id, call)).unwrap();
+                self.client_tx
+                    .send((self.id, call))
+                    .context("failed to send a message to server")?;
                 // let notification = Notification::parse(&method, params);
             }
         };

From c5a2fd5da394b5b16695af9f2eb437e29be010f0 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Sat, 19 Jun 2021 05:14:40 +0200
Subject: [PATCH 28/31] Add `close_language_servers` method on `Editor`

---
 Cargo.lock                    |  1 +
 helix-term/src/application.rs | 11 +----------
 helix-view/Cargo.toml         |  1 +
 helix-view/src/editor.rs      | 20 ++++++++++++++++++++
 4 files changed, 23 insertions(+), 10 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 12a03dac..24c277e1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -342,6 +342,7 @@ version = "0.2.0"
 dependencies = [
  "anyhow",
  "crossterm",
+ "futures-util",
  "helix-core",
  "helix-lsp",
  "helix-tui",
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 1f02ac4f..2fae467f 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -406,16 +406,7 @@ impl Application {
 
         self.event_loop().await;
 
-        tokio::time::timeout(
-            Duration::from_millis(500),
-            future::join_all(
-                self.editor
-                    .language_servers
-                    .iter_clients()
-                    .map(|client| client.force_shutdown()),
-            ),
-        )
-        .await;
+        self.editor.close_language_servers(None).await;
 
         // reset cursor shape
         write!(stdout, "\x1B[2 q");
diff --git a/helix-view/Cargo.toml b/helix-view/Cargo.toml
index 13539a5a..7f18e9a2 100644
--- a/helix-view/Cargo.toml
+++ b/helix-view/Cargo.toml
@@ -27,6 +27,7 @@ once_cell = "1.8"
 url = "2"
 
 tokio = { version = "1", features = ["full"] }
+futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }
 
 slotmap = "1"
 
diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs
index a1c93f75..db8ae87a 100644
--- a/helix-view/src/editor.rs
+++ b/helix-view/src/editor.rs
@@ -2,7 +2,9 @@ use crate::{theme::Theme, tree::Tree, Document, DocumentId, RegisterSelection, V
 use tui::layout::Rect;
 use tui::terminal::CursorKind;
 
+use futures_util::future;
 use std::path::PathBuf;
+use std::time::Duration;
 
 use slotmap::SlotMap;
 
@@ -270,4 +272,22 @@ impl Editor {
             (None, CursorKind::Hidden)
         }
     }
+
+    /// Closes language servers with timeout. The default timeout is 500 ms, use
+    /// `timeout` parameter to override this.
+    pub async fn close_language_servers(
+        &self,
+        timeout: Option<u64>,
+    ) -> Result<(), tokio::time::error::Elapsed> {
+        tokio::time::timeout(
+            Duration::from_millis(timeout.unwrap_or(500)),
+            future::join_all(
+                self.language_servers
+                    .iter_clients()
+                    .map(|client| client.force_shutdown()),
+            ),
+        )
+        .await
+        .map(|_| ())
+    }
 }

From 1c2585202145467f0fde7ad9c571e462081c3656 Mon Sep 17 00:00:00 2001
From: wojciechkepka <wojtek.kepka@protonmail.com>
Date: Fri, 18 Jun 2021 19:09:37 +0200
Subject: [PATCH 29/31] Make arrow keys and page up/down work in insert mode

---
 helix-term/src/keymap.rs | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs
index a2fdbdd1..f6bcbcc9 100644
--- a/helix-term/src/keymap.rs
+++ b/helix-term/src/keymap.rs
@@ -321,6 +321,12 @@ impl Default for Keymaps {
                 key!(Delete) => Command::delete_char_forward,
                 key!(Enter) => Command::insert_newline,
                 key!(Tab) => Command::insert_tab,
+                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!(PageUp) => Command::page_up,
+                key!(PageDown) => Command::page_down,
                 ctrl!('x') => Command::completion,
                 ctrl!('w') => Command::delete_word_backward,
             )),

From ca806d4f852e934651132fc9570a6110e30f646d Mon Sep 17 00:00:00 2001
From: Ivan Tham <pickfire@riseup.net>
Date: Fri, 18 Jun 2021 00:52:41 +0800
Subject: [PATCH 30/31] Refactor key into helix-view

Now also make use of Deserialize for Config.
---
 helix-term/src/application.rs |   4 +-
 helix-term/src/commands.rs    |  71 ++++---
 helix-term/src/config.rs      |  76 ++++----
 helix-term/src/keymap.rs      | 336 ++--------------------------------
 helix-term/src/main.rs        |  14 +-
 helix-term/src/ui/editor.rs   |   6 +-
 helix-view/src/document.rs    |  61 +++---
 helix-view/src/input.rs       | 226 +++++++++++++++++++++++
 helix-view/src/lib.rs         |   8 +-
 9 files changed, 388 insertions(+), 414 deletions(-)
 create mode 100644 helix-view/src/input.rs

diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 2fae467f..ce43808a 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -1,7 +1,7 @@
 use helix_lsp::{lsp, LspProgressMap};
 use helix_view::{document::Mode, Document, Editor, Theme, View};
 
-use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui};
+use crate::{args::Args, compositor::Compositor, config::Config, ui};
 
 use log::{error, info};
 
@@ -49,7 +49,7 @@ impl Application {
         let size = compositor.size();
         let mut editor = Editor::new(size);
 
-        let mut editor_view = Box::new(ui::EditorView::new(config.keymaps));
+        let mut editor_view = Box::new(ui::EditorView::new(config.keys));
         compositor.push(editor_view);
 
         if !args.files.is_empty() {
diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index a8610223..1243a86f 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -11,6 +11,7 @@ use helix_core::{
 
 use helix_view::{
     document::{IndentStyle, Mode},
+    input::{KeyCode, KeyEvent},
     view::{View, PADDING},
     Document, DocumentId, Editor, ViewId,
 };
@@ -38,8 +39,8 @@ use std::{
     path::{Path, PathBuf},
 };
 
-use crossterm::event::{KeyCode, KeyEvent};
 use once_cell::sync::Lazy;
+use serde::de::{self, Deserialize, Deserializer};
 
 pub struct Context<'a> {
     pub selected_register: helix_view::RegisterSelection,
@@ -252,6 +253,48 @@ impl Command {
     );
 }
 
+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()
+    }
+}
+
+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<'de> Deserialize<'de> for Command {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let s = String::deserialize(deserializer)?;
+        s.parse().map_err(de::Error::custom)
+    }
+}
+
+impl PartialEq for Command {
+    fn eq(&self, other: &Self) -> bool {
+        self.name() == other.name()
+    }
+}
+
 fn move_char_left(cx: &mut Context) {
     let count = cx.count();
     let (view, doc) = current!(cx.editor);
@@ -3042,29 +3085,3 @@ 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
index e5e17753..9c962299 100644
--- a/helix-term/src/config.rs
+++ b/helix-term/src/config.rs
@@ -1,10 +1,9 @@
-use anyhow::{Error, Result};
-use std::{collections::HashMap, str::FromStr};
+use serde::Deserialize;
 
-use serde::{de::Error as SerdeError, Deserialize, Serialize};
-
-use crate::keymap::{parse_keymaps, Keymaps};
+use crate::commands::Command;
+use crate::keymap::Keymaps;
 
+#[derive(Debug, PartialEq, Deserialize)]
 pub struct GlobalConfig {
     pub lsp_progress: bool,
 }
@@ -15,35 +14,50 @@ impl Default for GlobalConfig {
     }
 }
 
-#[derive(Default)]
+#[derive(Debug, Default, PartialEq, Deserialize)]
+#[serde(default)]
 pub struct Config {
     pub global: GlobalConfig,
-    pub keymaps: Keymaps,
+    pub keys: Keymaps,
 }
 
-#[derive(Serialize, Deserialize)]
-#[serde(rename_all = "kebab-case")]
-struct TomlConfig {
-    lsp_progress: Option<bool>,
-    keys: Option<HashMap<String, HashMap<String, String>>>,
-}
+#[test]
+fn parsing_keymaps_config_file() {
+    use helix_core::hashmap;
+    use helix_view::document::Mode;
+    use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
 
-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 {
-            global: GlobalConfig {
-                lsp_progress: config.lsp_progress.unwrap_or(true),
-            },
-            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),
-        })
-    }
+    let sample_keymaps = r#"
+            [keys.insert]
+            y = "move_line_down"
+            S-C-a = "delete_selection"
+
+            [keys.normal]
+            A-F12 = "move_next_word_end"
+        "#;
+
+    assert_eq!(
+        toml::from_str::<Config>(sample_keymaps).unwrap(),
+        Config {
+            global: Default::default(),
+            keys: Keymaps(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,
+                },
+            })
+        }
+    );
 }
diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs
index f6bcbcc9..24924832 100644
--- a/helix-term/src/keymap.rs
+++ b/helix-term/src/keymap.rs
@@ -3,6 +3,8 @@ pub use crate::commands::Command;
 use anyhow::{anyhow, Error, Result};
 use helix_core::hashmap;
 use helix_view::document::Mode;
+use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
+use serde::Deserialize;
 use std::{
     collections::HashMap,
     fmt::Display,
@@ -99,14 +101,6 @@ use std::{
 //      D] = last diagnostic
 // }
 
-// #[cfg(feature = "term")]
-pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
-
-#[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 {
     ($key:ident) => {
@@ -141,9 +135,21 @@ macro_rules! alt {
     };
 }
 
+#[derive(Debug, PartialEq, Deserialize)]
+#[serde(transparent)]
+pub struct Keymaps(pub HashMap<Mode, HashMap<KeyEvent, Command>>);
+
+impl Deref for Keymaps {
+    type Target = HashMap<Mode, HashMap<KeyEvent, Command>>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
 impl Default for Keymaps {
-    fn default() -> Self {
-        let normal = Keymap(hashmap!(
+    fn default() -> Keymaps {
+        let normal = hashmap!(
             key!('h') => Command::move_char_left,
             key!('j') => Command::move_line_down,
             key!('k') => Command::move_line_up,
@@ -277,12 +283,12 @@ impl Default for Keymaps {
             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(
+        select.extend(
             hashmap!(
                 key!('h') => Command::extend_char_left,
                 key!('j') => Command::extend_line_down,
@@ -315,7 +321,7 @@ impl Default for Keymaps {
             // TODO: select could be normal mode with some bindings merged over
             Mode::Normal => normal,
             Mode::Select => select,
-            Mode::Insert => Keymap(hashmap!(
+            Mode::Insert => hashmap!(
                 key!(Esc) => Command::normal_mode as Command,
                 key!(Backspace) => Command::delete_char_backward,
                 key!(Delete) => Command::delete_char_forward,
@@ -329,309 +335,7 @@ impl Default for Keymaps {
                 key!(PageDown) => Command::page_down,
                 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/main.rs b/helix-term/src/main.rs
index ef912480..12176910 100644
--- a/helix-term/src/main.rs
+++ b/helix-term/src/main.rs
@@ -1,10 +1,9 @@
+use anyhow::{Context, Error, Result};
 use helix_term::application::Application;
 use helix_term::args::Args;
 use helix_term::config::Config;
 use std::path::PathBuf;
 
-use anyhow::{Context, Result};
-
 fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> {
     let mut base_config = fern::Dispatch::new();
 
@@ -89,12 +88,11 @@ 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();
+    let config = match std::fs::read_to_string(conf_dir.join("config.toml")) {
+        Ok(config) => toml::from_str(&config)?,
+        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(),
+        Err(err) => return Err(Error::new(err)),
+    };
 
     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 3dc43d3f..d0eedad6 100644
--- a/helix-term/src/ui/editor.rs
+++ b/helix-term/src/ui/editor.rs
@@ -11,12 +11,13 @@ use helix_core::{
     syntax::{self, HighlightEvent},
     Position, Range,
 };
+use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
 use helix_view::{document::Mode, Document, Editor, Theme, View};
 use std::borrow::Cow;
 
 use crossterm::{
     cursor,
-    event::{read, Event, EventStream, KeyCode, KeyEvent, KeyModifiers},
+    event::{read, Event, EventStream},
 };
 use tui::{
     backend::CrosstermBackend,
@@ -607,7 +608,8 @@ impl Component for EditorView {
                 cx.editor.resize(Rect::new(0, 0, width, height - 1));
                 EventResult::Consumed(None)
             }
-            Event::Key(mut key) => {
+            Event::Key(key) => {
+                let mut key = KeyEvent::from(key);
                 canonicalize_key(&mut key);
                 // clear status
                 cx.editor.status_msg = None;
diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs
index e9a8097c..8875f70d 100644
--- a/helix-view/src/document.rs
+++ b/helix-view/src/document.rs
@@ -1,5 +1,7 @@
 use anyhow::{anyhow, Context, Error};
+use serde::de::{self, Deserialize, Deserializer};
 use std::cell::Cell;
+use std::collections::HashMap;
 use std::fmt::Display;
 use std::future::Future;
 use std::path::{Component, Path, PathBuf};
@@ -15,8 +17,6 @@ use helix_core::{
 
 use crate::{DocumentId, ViewId};
 
-use std::collections::HashMap;
-
 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
 pub enum Mode {
     Normal,
@@ -24,6 +24,40 @@ pub enum Mode {
     Insert,
 }
 
+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<Self, Self::Err> {
+        match s {
+            "normal" => Ok(Mode::Normal),
+            "select" => Ok(Mode::Select),
+            "insert" => Ok(Mode::Insert),
+            _ => Err(anyhow!("Invalid mode '{}'", s)),
+        }
+    }
+}
+
+// toml deserializer doesn't seem to recognize string as enum
+impl<'de> Deserialize<'de> for Mode {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let s = String::deserialize(deserializer)?;
+        s.parse().map_err(de::Error::custom)
+    }
+}
+
 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
 pub enum IndentStyle {
     Tabs,
@@ -88,29 +122,6 @@ 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<Self, Self::Err> {
-        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<T, F>(mut_ref: &mut T, closure: F)
diff --git a/helix-view/src/input.rs b/helix-view/src/input.rs
new file mode 100644
index 00000000..ab417819
--- /dev/null
+++ b/helix-view/src/input.rs
@@ -0,0 +1,226 @@
+//! Input event handling, currently backed by crossterm.
+use anyhow::{anyhow, Error};
+use crossterm::event;
+use serde::de::{self, Deserialize, Deserializer};
+use std::fmt;
+
+pub use crossterm::event::{KeyCode, KeyModifiers};
+
+/// Represents a key event.
+// We use a newtype here because we want to customize Deserialize and Display.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)]
+pub struct KeyEvent {
+    pub code: KeyCode,
+    pub modifiers: KeyModifiers,
+}
+
+impl fmt::Display for KeyEvent {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
+        f.write_fmt(format_args!(
+            "{}{}{}",
+            if self.modifiers.contains(KeyModifiers::SHIFT) {
+                "S-"
+            } else {
+                ""
+            },
+            if self.modifiers.contains(KeyModifiers::ALT) {
+                "A-"
+            } else {
+                ""
+            },
+            if self.modifiers.contains(KeyModifiers::CONTROL) {
+                "C-"
+            } else {
+                ""
+            },
+        ))?;
+        match self.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 std::str::FromStr for KeyEvent {
+    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(KeyEvent { code, modifiers })
+    }
+}
+
+impl<'de> Deserialize<'de> for KeyEvent {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let s = String::deserialize(deserializer)?;
+        s.parse().map_err(de::Error::custom)
+    }
+}
+
+impl From<event::KeyEvent> for KeyEvent {
+    fn from(event::KeyEvent { code, modifiers }: event::KeyEvent) -> KeyEvent {
+        KeyEvent { code, modifiers }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+
+    #[test]
+    fn parsing_unmodified_keys() {
+        assert_eq!(
+            str::parse::<KeyEvent>("backspace").unwrap(),
+            KeyEvent {
+                code: KeyCode::Backspace,
+                modifiers: KeyModifiers::NONE
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>("left").unwrap(),
+            KeyEvent {
+                code: KeyCode::Left,
+                modifiers: KeyModifiers::NONE
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>(",").unwrap(),
+            KeyEvent {
+                code: KeyCode::Char(','),
+                modifiers: KeyModifiers::NONE
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>("w").unwrap(),
+            KeyEvent {
+                code: KeyCode::Char('w'),
+                modifiers: KeyModifiers::NONE
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>("F12").unwrap(),
+            KeyEvent {
+                code: KeyCode::F(12),
+                modifiers: KeyModifiers::NONE
+            }
+        );
+    }
+
+    #[test]
+    fn parsing_modified_keys() {
+        assert_eq!(
+            str::parse::<KeyEvent>("S-minus").unwrap(),
+            KeyEvent {
+                code: KeyCode::Char('-'),
+                modifiers: KeyModifiers::SHIFT
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>("C-A-S-F12").unwrap(),
+            KeyEvent {
+                code: KeyCode::F(12),
+                modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
+            }
+        );
+
+        assert_eq!(
+            str::parse::<KeyEvent>("S-C-2").unwrap(),
+            KeyEvent {
+                code: KeyCode::Char('2'),
+                modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
+            }
+        );
+    }
+
+    #[test]
+    fn parsing_nonsensical_keys_fails() {
+        assert!(str::parse::<KeyEvent>("F13").is_err());
+        assert!(str::parse::<KeyEvent>("F0").is_err());
+        assert!(str::parse::<KeyEvent>("aaa").is_err());
+        assert!(str::parse::<KeyEvent>("S-S-a").is_err());
+        assert!(str::parse::<KeyEvent>("C-A-S-C-1").is_err());
+        assert!(str::parse::<KeyEvent>("FU").is_err());
+        assert!(str::parse::<KeyEvent>("123").is_err());
+        assert!(str::parse::<KeyEvent>("S--").is_err());
+    }
+}
diff --git a/helix-view/src/lib.rs b/helix-view/src/lib.rs
index 20613451..8b635700 100644
--- a/helix-view/src/lib.rs
+++ b/helix-view/src/lib.rs
@@ -3,14 +3,16 @@ pub mod macros;
 
 pub mod document;
 pub mod editor;
+pub mod input;
 pub mod register_selection;
 pub mod theme;
 pub mod tree;
 pub mod view;
 
-use slotmap::new_key_type;
-new_key_type! { pub struct DocumentId; }
-new_key_type! { pub struct ViewId; }
+slotmap::new_key_type! {
+    pub struct DocumentId;
+    pub struct ViewId;
+}
 
 pub use document::Document;
 pub use editor::Editor;

From 2cbec2b0470d0759578929b224c445b69617b6b6 Mon Sep 17 00:00:00 2001
From: Malte Voos <malte@malvo.org>
Date: Sat, 19 Jun 2021 09:58:08 +0200
Subject: [PATCH 31/31] Update flake.lock

Closes #302
---
 flake.lock | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)

diff --git a/flake.lock b/flake.lock
index 23143851..6f80276a 100644
--- a/flake.lock
+++ b/flake.lock
@@ -34,11 +34,11 @@
     "helix": {
       "flake": false,
       "locked": {
-        "lastModified": 1623545930,
-        "narHash": "sha256-14ASoYbxXHU/qPGctiUymb4fMRCoih9c7YujjxqEkdU=",
+        "lastModified": 1624077450,
+        "narHash": "sha256-gcL519tetuEv0N+oBP8X3U4bPjwcAgzbPdgwW19qeVI=",
         "ref": "master",
-        "rev": "9640ed1425f2db904fb42cd0c54dc6fbc05ca292",
-        "revCount": 821,
+        "rev": "1c2585202145467f0fde7ad9c571e462081c3656",
+        "revCount": 894,
         "submodules": true,
         "type": "git",
         "url": "https://github.com/helix-editor/helix.git"
@@ -58,11 +58,11 @@
         "rustOverlay": "rustOverlay"
       },
       "locked": {
-        "lastModified": 1623591988,
-        "narHash": "sha256-a8E5LYKxYjHmBWZsFxKnCBVGsWHFEWrKjeAJkplWrfI=",
+        "lastModified": 1624070370,
+        "narHash": "sha256-sfFqfmerCYvk0jDeP1gfuskz7AaqDsgV8aiQrEUGdsc=",
         "owner": "yusdacra",
         "repo": "nix-cargo-integration",
-        "rev": "8254b71eddd4e85173eddc189174b873fad85360",
+        "rev": "85e6c1ba4c0e3e6dec5a7d1f65bcc036d2ea6ae3",
         "type": "github"
       },
       "original": {
@@ -73,11 +73,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1623324058,
-        "narHash": "sha256-Jm9GUTXdjXz56gWDKy++EpFfjrBaxqXlLvTLfgEi8lo=",
+        "lastModified": 1623580589,
+        "narHash": "sha256-Ayp1cjXpwFCkAiWUE46rj9APTltsiEBdIs2+cj+U7+c=",
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "432fc2d9a67f92e05438dff5fdc2b39d33f77997",
+        "rev": "fa0326ce5233f7d592271df52c9d0812bec47b84",
         "type": "github"
       },
       "original": {
@@ -98,11 +98,11 @@
     "rustOverlay": {
       "flake": false,
       "locked": {
-        "lastModified": 1623550815,
-        "narHash": "sha256-RumRrkE6OTJDndHV4qZNZv8kUGnzwRHZQSyzx29r6/g=",
+        "lastModified": 1624069337,
+        "narHash": "sha256-9mTcx7osE4biF2Hm/GU19s1T3+KvphWj4QaUcJh39lU=",
         "owner": "oxalica",
         "repo": "rust-overlay",
-        "rev": "9824f142cbd7bc3e2a92eefbb79addfff8704cd3",
+        "rev": "67dc2a9543a7c24591e6cb102ad0121c3a704aab",
         "type": "github"
       },
       "original": {