From 25429f760cf054781cf4b7818c835338a4821b12 Mon Sep 17 00:00:00 2001 From: Conrad Irwin Date: Wed, 27 Sep 2023 12:32:01 -0600 Subject: [PATCH 1/2] ctrl-a/x for vim --- assets/keymaps/vim.json | 8 +- crates/vim/src/normal.rs | 2 + crates/vim/src/normal/increment.rs | 169 +++++++++++++++++++++++ crates/vim/test_data/test_increment.json | 3 + 4 files changed, 181 insertions(+), 1 deletion(-) create mode 100644 crates/vim/src/normal/increment.rs create mode 100644 crates/vim/test_data/test_increment.json diff --git a/assets/keymaps/vim.json b/assets/keymaps/vim.json index 3aaa3e4e1a..0e7c11c23d 100644 --- a/assets/keymaps/vim.json +++ b/assets/keymaps/vim.json @@ -2,6 +2,8 @@ { "context": "Editor && VimControl && !VimWaiting && !menu", "bindings": { + "ctrl-a": "vim::Increment", + "ctrl-x": "vim::Decrement", "i": [ "vim::PushOperator", { @@ -380,9 +382,11 @@ "shift-a": "vim::InsertEndOfLine", "x": "vim::DeleteRight", "shift-x": "vim::DeleteLeft", - "o": "vim::InsertLineBelow", + "k": "vim::InsertLineBelow", "shift-o": "vim::InsertLineAbove", "~": "vim::ChangeCase", + "ctrl-a": "vim::Increment", + "ctrl-x": "vim::Decrement", "p": "vim::Paste", "shift-p": [ "vim::Paste", @@ -494,6 +498,8 @@ "shift-r": "vim::SubstituteLine", "c": "vim::Substitute", "~": "vim::ChangeCase", + "ctrl-a": "vim::Increment", + "ctrl-x": "vim::Decrement", "shift-i": "vim::InsertBefore", "shift-a": "vim::InsertAfter", "shift-j": "vim::JoinLines", diff --git a/crates/vim/src/normal.rs b/crates/vim/src/normal.rs index a23091c7a7..36eab2c4c0 100644 --- a/crates/vim/src/normal.rs +++ b/crates/vim/src/normal.rs @@ -1,6 +1,7 @@ mod case; mod change; mod delete; +mod increment; mod paste; pub(crate) mod repeat; mod scroll; @@ -56,6 +57,7 @@ pub fn init(cx: &mut AppContext) { scroll::init(cx); search::init(cx); substitute::init(cx); + increment::init(cx); cx.add_action(insert_after); cx.add_action(insert_before); diff --git a/crates/vim/src/normal/increment.rs b/crates/vim/src/normal/increment.rs new file mode 100644 index 0000000000..caebf1c59c --- /dev/null +++ b/crates/vim/src/normal/increment.rs @@ -0,0 +1,169 @@ +use std::{ascii::AsciiExt, fmt::Binary, ops::Range}; + +use editor::{ + movement, scroll::autoscroll::Autoscroll, Editor, MultiBufferSnapshot, ToOffset, ToPoint, +}; +use gpui::{actions, AppContext, WindowContext}; +use language::Point; +use workspace::Workspace; + +use crate::{state::Mode, Vim}; + +actions!(vim, [Increment, Decrement]); + +pub fn init(cx: &mut AppContext) { + dbg!("hi"); + + cx.add_action(|_: &mut Workspace, _: &Increment, cx| { + Vim::update(cx, |vim, cx| { + vim.record_current_action(cx); + let count = vim.take_count(cx).unwrap_or(1); + increment(vim, count as i32, cx) + }) + }); + cx.add_action(|_: &mut Workspace, _: &Decrement, cx| { + Vim::update(cx, |vim, cx| { + vim.record_current_action(cx); + let count = vim.take_count(cx).unwrap_or(1); + increment(vim, count as i32 * -1, cx) + }) + }); +} + +fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { + vim.update_active_editor(cx, |editor, cx| { + let mut edits = Vec::new(); + let mut new_anchors = Vec::new(); + + let snapshot = editor.buffer().read(cx).snapshot(cx); + for selection in editor.selections.all_adjusted(cx) { + if !selection.is_empty() { + new_anchors.push((true, snapshot.anchor_before(selection.start))) + } + for row in selection.start.row..=selection.end.row { + let start = if row == selection.start.row { + selection.start + } else { + Point::new(row, 0) + }; + + if let Some((range, num, radix)) = find_number(&snapshot, start) { + if let Ok(val) = i32::from_str_radix(&num, radix) { + let result = val + delta; + let replace = match radix { + 10 => format!("{}", result), + 16 => { + if num.to_ascii_lowercase() == num { + format!("{:x}", result) + } else { + format!("{:X}", result) + } + } + 2 => format!("{:b}", result), + _ => unreachable!(), + }; + if selection.is_empty() { + new_anchors.push((false, snapshot.anchor_after(range.end))) + } + edits.push((range, replace)); + } + } + } + } + editor.transact(cx, |editor, cx| { + editor.edit(edits, cx); + + let snapshot = editor.buffer().read(cx).snapshot(cx); + editor.change_selections(Some(Autoscroll::fit()), cx, |s| { + let mut new_ranges = Vec::new(); + for (visual, anchor) in new_anchors.iter() { + let mut point = anchor.to_point(&snapshot); + if !*visual && point.column > 0 { + point.column -= 1 + } + new_ranges.push(point..point); + } + s.select_ranges(new_ranges) + }) + }); + }); + vim.switch_mode(Mode::Normal, false, cx) +} + +fn find_number( + snapshot: &MultiBufferSnapshot, + start: Point, +) -> Option<(Range, String, u32)> { + let mut offset = start.to_offset(snapshot); + + for ch in snapshot.reversed_chars_at(offset) { + if ch.is_ascii_digit() || ch == '-' || ch == 'b' || ch == 'x' { + offset -= ch.len_utf8(); + continue; + } + break; + } + + let mut begin = None; + let mut end = None; + let mut num = String::new(); + let mut radix = 10; + + let mut chars = snapshot.chars_at(offset).peekable(); + while let Some(ch) = chars.next() { + if num == "0" && ch == 'b' && chars.peek().is_some() && chars.peek().unwrap().is_digit(2) { + radix = 2; + begin = None; + num = String::new(); + } + if num == "0" && ch == 'x' && chars.peek().is_some() && chars.peek().unwrap().is_digit(16) { + radix = 16; + begin = None; + num = String::new(); + } + + if ch.is_digit(radix) || ch == '-' { + if begin.is_none() { + begin = Some(offset); + } + num.push(ch); + } else { + if begin.is_some() { + end = Some(offset); + break; + } else if ch == '\n' { + break; + } + } + offset += ch.len_utf8(); + } + if let Some(begin) = begin { + let end = end.unwrap_or(offset); + Some((begin.to_point(snapshot)..end.to_point(snapshot), num, radix)) + } else { + None + } +} + +#[cfg(test)] +mod test { + use indoc::indoc; + + use crate::test::NeovimBackedTestContext; + + #[gpui::test] + async fn test_increment(cx: &mut gpui::TestAppContext) { + let mut cx = NeovimBackedTestContext::new(cx).await; + + cx.set_shared_state(indoc! {" + 1ˇ2 + "}) + .await; + + cx.simulate_shared_keystrokes(["ctrl-a"]).await; + cx.assert_shared_state(indoc! {" + 1ˇ3 + "}) + .await; + } +} diff --git a/crates/vim/test_data/test_increment.json b/crates/vim/test_data/test_increment.json new file mode 100644 index 0000000000..125fb4a692 --- /dev/null +++ b/crates/vim/test_data/test_increment.json @@ -0,0 +1,3 @@ +{"Put":{"state":"1ˇ2\n"}} +{"Key":"ctrl-a"} +{"Get":{"state":"1ˇ3\n","mode":"Normal"}} From dd1cf5c3cf820906e5e3e46256bd490a6787a0f2 Mon Sep 17 00:00:00 2001 From: Conrad Irwin Date: Wed, 27 Sep 2023 16:43:24 -0600 Subject: [PATCH 2/2] vim: add ctrl-a/ctrl-x For zed-industries/community#1411 For zed-industries/community#619 --- assets/keymaps/vim.json | 16 ++- crates/vim/src/normal/increment.rs | 129 +++++++++++++++--- .../src/test/neovim_backed_test_context.rs | 11 ++ crates/vim/test_data/test_increment.json | 13 ++ .../vim/test_data/test_increment_radix.json | 15 ++ .../vim/test_data/test_increment_steps.json | 14 ++ 6 files changed, 177 insertions(+), 21 deletions(-) create mode 100644 crates/vim/test_data/test_increment_radix.json create mode 100644 crates/vim/test_data/test_increment_steps.json diff --git a/assets/keymaps/vim.json b/assets/keymaps/vim.json index 0e7c11c23d..50dd8884ba 100644 --- a/assets/keymaps/vim.json +++ b/assets/keymaps/vim.json @@ -2,8 +2,6 @@ { "context": "Editor && VimControl && !VimWaiting && !menu", "bindings": { - "ctrl-a": "vim::Increment", - "ctrl-x": "vim::Decrement", "i": [ "vim::PushOperator", { @@ -382,7 +380,7 @@ "shift-a": "vim::InsertEndOfLine", "x": "vim::DeleteRight", "shift-x": "vim::DeleteLeft", - "k": "vim::InsertLineBelow", + "o": "vim::InsertLineBelow", "shift-o": "vim::InsertLineAbove", "~": "vim::ChangeCase", "ctrl-a": "vim::Increment", @@ -500,6 +498,18 @@ "~": "vim::ChangeCase", "ctrl-a": "vim::Increment", "ctrl-x": "vim::Decrement", + "g ctrl-a": [ + "vim::Increment", + { + "step": true + } + ], + "g ctrl-x": [ + "vim::Decrement", + { + "step": true + } + ], "shift-i": "vim::InsertBefore", "shift-a": "vim::InsertAfter", "shift-j": "vim::JoinLines", diff --git a/crates/vim/src/normal/increment.rs b/crates/vim/src/normal/increment.rs index caebf1c59c..d7f3d1f904 100644 --- a/crates/vim/src/normal/increment.rs +++ b/crates/vim/src/normal/increment.rs @@ -1,36 +1,49 @@ -use std::{ascii::AsciiExt, fmt::Binary, ops::Range}; +use std::ops::Range; -use editor::{ - movement, scroll::autoscroll::Autoscroll, Editor, MultiBufferSnapshot, ToOffset, ToPoint, -}; -use gpui::{actions, AppContext, WindowContext}; -use language::Point; +use editor::{scroll::autoscroll::Autoscroll, MultiBufferSnapshot, ToOffset, ToPoint}; +use gpui::{impl_actions, AppContext, WindowContext}; +use language::{Bias, Point}; +use serde::Deserialize; use workspace::Workspace; use crate::{state::Mode, Vim}; -actions!(vim, [Increment, Decrement]); +#[derive(Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +struct Increment { + #[serde(default)] + step: bool, +} + +#[derive(Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +struct Decrement { + #[serde(default)] + step: bool, +} + +impl_actions!(vim, [Increment, Decrement]); pub fn init(cx: &mut AppContext) { - dbg!("hi"); - - cx.add_action(|_: &mut Workspace, _: &Increment, cx| { + cx.add_action(|_: &mut Workspace, action: &Increment, cx| { Vim::update(cx, |vim, cx| { vim.record_current_action(cx); let count = vim.take_count(cx).unwrap_or(1); - increment(vim, count as i32, cx) + let step = if action.step { 1 } else { 0 }; + increment(vim, count as i32, step, cx) }) }); - cx.add_action(|_: &mut Workspace, _: &Decrement, cx| { + cx.add_action(|_: &mut Workspace, action: &Decrement, cx| { Vim::update(cx, |vim, cx| { vim.record_current_action(cx); let count = vim.take_count(cx).unwrap_or(1); - increment(vim, count as i32 * -1, cx) + let step = if action.step { -1 } else { 0 }; + increment(vim, count as i32 * -1, step, cx) }) }); } -fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { +fn increment(vim: &mut Vim, mut delta: i32, step: i32, cx: &mut WindowContext) { vim.update_active_editor(cx, |editor, cx| { let mut edits = Vec::new(); let mut new_anchors = Vec::new(); @@ -38,7 +51,9 @@ fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { let snapshot = editor.buffer().read(cx).snapshot(cx); for selection in editor.selections.all_adjusted(cx) { if !selection.is_empty() { - new_anchors.push((true, snapshot.anchor_before(selection.start))) + if vim.state().mode != Mode::VisualBlock || new_anchors.is_empty() { + new_anchors.push((true, snapshot.anchor_before(selection.start))) + } } for row in selection.start.row..=selection.end.row { let start = if row == selection.start.row { @@ -50,6 +65,7 @@ fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { if let Some((range, num, radix)) = find_number(&snapshot, start) { if let Ok(val) = i32::from_str_radix(&num, radix) { let result = val + delta; + delta += step; let replace = match radix { 10 => format!("{}", result), 16 => { @@ -79,7 +95,8 @@ fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { for (visual, anchor) in new_anchors.iter() { let mut point = anchor.to_point(&snapshot); if !*visual && point.column > 0 { - point.column -= 1 + point.column -= 1; + point = snapshot.clip_point(point, Bias::Left) } new_ranges.push(point..point); } @@ -87,7 +104,7 @@ fn increment(vim: &mut Vim, delta: i32, cx: &mut WindowContext) { }) }); }); - vim.switch_mode(Mode::Normal, false, cx) + vim.switch_mode(Mode::Normal, true, cx) } fn find_number( @@ -96,6 +113,7 @@ fn find_number( ) -> Option<(Range, String, u32)> { let mut offset = start.to_offset(snapshot); + // go backwards to the start of any number the selection is within for ch in snapshot.reversed_chars_at(offset) { if ch.is_ascii_digit() || ch == '-' || ch == 'b' || ch == 'x' { offset -= ch.len_utf8(); @@ -110,6 +128,7 @@ fn find_number( let mut radix = 10; let mut chars = snapshot.chars_at(offset).peekable(); + // find the next number on the line (may start after the original cursor position) while let Some(ch) = chars.next() { if num == "0" && ch == 'b' && chars.peek().is_some() && chars.peek().unwrap().is_digit(2) { radix = 2; @@ -122,7 +141,12 @@ fn find_number( num = String::new(); } - if ch.is_digit(radix) || ch == '-' { + if ch.is_digit(radix) + || (begin.is_none() + && ch == '-' + && chars.peek().is_some() + && chars.peek().unwrap().is_digit(radix)) + { if begin.is_none() { begin = Some(offset); } @@ -165,5 +189,74 @@ mod test { 1ˇ3 "}) .await; + cx.simulate_shared_keystrokes(["ctrl-x"]).await; + cx.assert_shared_state(indoc! {" + 1ˇ2 + "}) + .await; + + cx.simulate_shared_keystrokes(["9", "9", "ctrl-a"]).await; + cx.assert_shared_state(indoc! {" + 11ˇ1 + "}) + .await; + cx.simulate_shared_keystrokes(["1", "1", "1", "ctrl-x"]) + .await; + cx.assert_shared_state(indoc! {" + ˇ0 + "}) + .await; + cx.simulate_shared_keystrokes(["."]).await; + cx.assert_shared_state(indoc! {" + -11ˇ1 + "}) + .await; + } + + #[gpui::test] + async fn test_increment_radix(cx: &mut gpui::TestAppContext) { + let mut cx = NeovimBackedTestContext::new(cx).await; + + cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-a"], " total: 0x10ˇ0") + .await; + cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-x"], " total: 0xfˇe") + .await; + cx.assert_matches_neovim("ˇ total: 0xFF", ["ctrl-x"], " total: 0xFˇE") + .await; + cx.assert_matches_neovim("(ˇ0b10f)", ["ctrl-a"], "(0b1ˇ1f)") + .await; + cx.assert_matches_neovim("ˇ-1", ["ctrl-a"], "ˇ0").await; + } + + #[gpui::test] + async fn test_increment_steps(cx: &mut gpui::TestAppContext) { + let mut cx = NeovimBackedTestContext::new(cx).await; + + cx.set_shared_state(indoc! {" + ˇ1 + 1 + 1 2 + 1 + 1"}) + .await; + + cx.simulate_shared_keystrokes(["j", "v", "shift-g", "g", "ctrl-a"]) + .await; + cx.assert_shared_state(indoc! {" + 1 + ˇ2 + 3 2 + 4 + 5"}) + .await; + cx.simulate_shared_keystrokes(["shift-g", "ctrl-v", "g", "g", "g", "ctrl-x"]) + .await; + cx.assert_shared_state(indoc! {" + ˇ0 + 0 + 0 2 + 0 + 0"}) + .await; } } diff --git a/crates/vim/src/test/neovim_backed_test_context.rs b/crates/vim/src/test/neovim_backed_test_context.rs index 227d39bb63..6be1275236 100644 --- a/crates/vim/src/test/neovim_backed_test_context.rs +++ b/crates/vim/src/test/neovim_backed_test_context.rs @@ -346,6 +346,17 @@ impl<'a> NeovimBackedTestContext<'a> { self.assert_state_matches().await; } + pub async fn assert_matches_neovim( + &mut self, + marked_positions: &str, + keystrokes: [&str; COUNT], + result: &str, + ) { + self.set_shared_state(marked_positions).await; + self.simulate_shared_keystrokes(keystrokes).await; + self.assert_shared_state(result).await; + } + pub async fn assert_binding_matches_all_exempted( &mut self, keystrokes: [&str; COUNT], diff --git a/crates/vim/test_data/test_increment.json b/crates/vim/test_data/test_increment.json index 125fb4a692..fe893bca97 100644 --- a/crates/vim/test_data/test_increment.json +++ b/crates/vim/test_data/test_increment.json @@ -1,3 +1,16 @@ {"Put":{"state":"1ˇ2\n"}} {"Key":"ctrl-a"} {"Get":{"state":"1ˇ3\n","mode":"Normal"}} +{"Key":"ctrl-x"} +{"Get":{"state":"1ˇ2\n","mode":"Normal"}} +{"Key":"9"} +{"Key":"9"} +{"Key":"ctrl-a"} +{"Get":{"state":"11ˇ1\n","mode":"Normal"}} +{"Key":"1"} +{"Key":"1"} +{"Key":"1"} +{"Key":"ctrl-x"} +{"Get":{"state":"ˇ0\n","mode":"Normal"}} +{"Key":"."} +{"Get":{"state":"-11ˇ1\n","mode":"Normal"}} diff --git a/crates/vim/test_data/test_increment_radix.json b/crates/vim/test_data/test_increment_radix.json new file mode 100644 index 0000000000..f9379a7195 --- /dev/null +++ b/crates/vim/test_data/test_increment_radix.json @@ -0,0 +1,15 @@ +{"Put":{"state":"ˇ total: 0xff"}} +{"Key":"ctrl-a"} +{"Get":{"state":" total: 0x10ˇ0","mode":"Normal"}} +{"Put":{"state":"ˇ total: 0xff"}} +{"Key":"ctrl-x"} +{"Get":{"state":" total: 0xfˇe","mode":"Normal"}} +{"Put":{"state":"ˇ total: 0xFF"}} +{"Key":"ctrl-x"} +{"Get":{"state":" total: 0xFˇE","mode":"Normal"}} +{"Put":{"state":"(ˇ0b10f)"}} +{"Key":"ctrl-a"} +{"Get":{"state":"(0b1ˇ1f)","mode":"Normal"}} +{"Put":{"state":"ˇ-1"}} +{"Key":"ctrl-a"} +{"Get":{"state":"ˇ0","mode":"Normal"}} diff --git a/crates/vim/test_data/test_increment_steps.json b/crates/vim/test_data/test_increment_steps.json new file mode 100644 index 0000000000..fffaf1fd29 --- /dev/null +++ b/crates/vim/test_data/test_increment_steps.json @@ -0,0 +1,14 @@ +{"Put":{"state":"ˇ1\n1\n1 2\n1\n1"}} +{"Key":"j"} +{"Key":"v"} +{"Key":"shift-g"} +{"Key":"g"} +{"Key":"ctrl-a"} +{"Get":{"state":"1\nˇ2\n3 2\n4\n5","mode":"Normal"}} +{"Key":"shift-g"} +{"Key":"ctrl-v"} +{"Key":"g"} +{"Key":"g"} +{"Key":"g"} +{"Key":"ctrl-x"} +{"Get":{"state":"ˇ0\n0\n0 2\n0\n0","mode":"Normal"}}