Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vim: Add Multi Replace mode in Vim #8469

Merged
merged 19 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions assets/keymaps/vim.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"shift-v": "vim::ToggleVisualLine",
"ctrl-v": "vim::ToggleVisualBlock",
"ctrl-q": "vim::ToggleVisualBlock",
"R": "vim::ToggleReplace",
weartist marked this conversation as resolved.
Show resolved Hide resolved
"0": "vim::StartOfLine", // When no number operator present, use start of line motion
"ctrl-f": "vim::PageDown",
"pagedown": "vim::PageDown",
Expand Down Expand Up @@ -504,6 +505,15 @@
"ctrl-d": "vim::Outdent"
}
},
{
"context": "Editor && vim_mode == replace",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-c": "vim::NormalBefore",
"ctrl-[": "vim::NormalBefore",
"backspace": "vim::UndoReplace"
}
},
{
"context": "Editor && VimWaiting",
"bindings": {
Expand Down
6 changes: 6 additions & 0 deletions crates/editor/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ pub struct Editor {
_subscriptions: Vec<Subscription>,
pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
gutter_width: Pixels,
pub last_snapshot: Option<MultiBufferSnapshot>,
style: Option<EditorStyle>,
editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
show_copilot_suggestions: bool,
Expand Down Expand Up @@ -1535,6 +1536,7 @@ impl Editor {
workspace: None,
keymap_context_layers: Default::default(),
input_enabled: true,
last_snapshot: None,
use_modal_editing: mode == EditorMode::Full,
read_only: false,
use_autoclose: true,
Expand Down Expand Up @@ -1808,6 +1810,10 @@ impl Editor {
self.input_enabled = input_enabled;
}

pub fn set_last_snapshot(&mut self, last_snapshot: Option<MultiBufferSnapshot>) {
self.last_snapshot = last_snapshot;
}

pub fn set_autoindent(&mut self, autoindent: bool) {
if autoindent {
self.autoindent_mode = Some(AutoindentMode::EachLine);
Expand Down
10 changes: 10 additions & 0 deletions crates/vim/src/motion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{
state::{Mode, Operator},
utils::coerce_punctuation,
visual::visual_motion,
replace::replace_motion,
Vim,
};

Expand Down Expand Up @@ -80,6 +81,7 @@ pub enum Motion {
WindowTop,
WindowMiddle,
WindowBottom,
UndoReplace,
}

#[derive(Clone, Deserialize, PartialEq)]
Expand Down Expand Up @@ -182,6 +184,7 @@ actions!(
WindowTop,
WindowMiddle,
WindowBottom,
UndoReplace,
]
);

Expand Down Expand Up @@ -309,6 +312,8 @@ pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
motion(Motion::PreviousWordEnd { ignore_punctuation }, cx)
},
);
workspace
.register_action(|_: &mut Workspace, _: &UndoReplace, cx: _| motion(Motion::UndoReplace, cx));
}

pub(crate) fn motion(motion: Motion, cx: &mut WindowContext) {
Expand All @@ -322,6 +327,7 @@ pub(crate) fn motion(motion: Motion, cx: &mut WindowContext) {
let operator = Vim::read(cx).active_operator();
match Vim::read(cx).state().mode {
Mode::Normal => normal_motion(motion, operator, count, cx),
Mode::Replace => replace_motion(motion, operator, count, cx),
Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_motion(motion, count, cx),
Mode::Insert => {
// Shouldn't execute a motion in insert mode. Ignoring
Expand Down Expand Up @@ -354,6 +360,7 @@ impl Motion {
| FindForward { .. }
| Left
| Backspace
| UndoReplace
| Right
| Space
| StartOfLine { .. }
Expand Down Expand Up @@ -382,6 +389,7 @@ impl Motion {
| RepeatFind { .. }
| Left
| Backspace
| UndoReplace
| Right
| Space
| StartOfLine { .. }
Expand All @@ -408,6 +416,7 @@ impl Motion {
match self {
Down { .. }
| Up { .. }
| UndoReplace
| StartOfDocument
| EndOfDocument
| CurrentLine
Expand Down Expand Up @@ -466,6 +475,7 @@ impl Motion {
Up {
display_lines: true,
} => up_display(map, point, goal, times, &text_layout_details),
UndoReplace => (backspace(map, point, times), SelectionGoal::None),
Right => (right(map, point, times), SelectionGoal::None),
Space => (space(map, point, times), SelectionGoal::None),
NextWordStart { ignore_punctuation } => (
Expand Down
2 changes: 1 addition & 1 deletion crates/vim/src/normal/case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ where
cursor_positions.push(selection.start..selection.start);
}
}
Mode::Insert | Mode::Normal => {
Mode::Insert | Mode::Normal | Mode::Replace => {
let start = selection.start;
let mut end = start;
for _ in 0..count {
Expand Down
2 changes: 1 addition & 1 deletion crates/vim/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ fn object(object: Object, cx: &mut WindowContext) {
match Vim::read(cx).state().mode {
Mode::Normal => normal_object(object, cx),
Mode::Visual | Mode::VisualLine | Mode::VisualBlock => visual_object(object, cx),
Mode::Insert => {
Mode::Insert | Mode::Replace => {
// Shouldn't execute a text object in insert mode. Ignoring
}
}
Expand Down
174 changes: 174 additions & 0 deletions crates/vim/src/replace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
use std::sync::Arc;

use crate::{
motion::Motion,
state::{Mode, Operator},
Vim,
};
use editor::{movement, Bias};
use gpui::{actions, ViewContext, WindowContext};
use log::error;
use workspace::Workspace;

actions!(vim, [ToggleReplace]);

pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
workspace.register_action(|_, _: &ToggleReplace, cx: &mut ViewContext<Workspace>| {
Vim::update(cx, |vim, cx| {
if vim.state().mode == Mode::Replace {
vim.switch_mode(Mode::Normal, false, cx);
} else {
vim.switch_mode(Mode::Replace, false, cx);
vim.update_active_editor(cx, |_, editor, cx| {
editor.set_last_snapshot(Some(editor.buffer().clone().read(cx).snapshot(cx)));
});
}
});
});
}

pub fn replace_motion(
motion: Motion,
operator: Option<Operator>,
times: Option<usize>,
cx: &mut WindowContext,
) {
Vim::update(cx, |vim, cx| {
match operator {
None => undo_replace_motion(vim, motion, times, cx),
Some(operator) => {
// Can't do anything for text objects, Ignoring
error!("Unexpected replace mode motion operator: {:?}", operator)
}
}
});
}

pub(crate) fn multi_replace(text: Arc<str>, cx: &mut WindowContext) {
Vim::update(cx, |vim, cx| {
vim.stop_recording();
weartist marked this conversation as resolved.
Show resolved Hide resolved
vim.update_active_editor(cx, |_, editor, cx| {
editor.transact(cx, |editor, cx| {
editor.set_clip_at_line_ends(false, cx);
let (map, display_selections) = editor.selections.all_display(cx);
let stable_anchors = editor
.selections
.disjoint_anchors()
.into_iter()
.map(|selection| {
let start = selection.start.bias_right(&map.buffer_snapshot);
start..start
})
.collect::<Vec<_>>();

let edits = display_selections
.into_iter()
.map(|selection| {
let mut range = selection.range();
// "\n" need to be handled separately, because when a "\n" is typing,
// we don't do a replace, we need insert a "\n"
if text.as_ref() != "\n" {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does mapping "enter": "editor::Newline" in the keymap do the right thing? If not quite we may still want to call editor.newline as that also handles preserving leading indentation/comments etc.

*range.end.column_mut() += 1;
range.end = map.clip_point(range.end, Bias::Right);
}
(
range.start.to_offset(&map, Bias::Left)
..range.end.to_offset(&map, Bias::Left),
text.clone(),
)
})
.collect::<Vec<_>>();

editor.buffer().update(cx, |buffer, cx| {
buffer.edit(edits, None, cx);
});
editor.set_clip_at_line_ends(true, cx);
editor.change_selections(None, cx, |s| {
s.select_anchor_ranges(stable_anchors);
});
});
});
});
}

fn undo_replace_motion(vim: &mut Vim, _: Motion, _: Option<usize>, cx: &mut WindowContext) {
vim.stop_recording();
vim.update_active_editor(cx, |_, editor, cx| {
if let Some(original_snapshot) = editor.last_snapshot.clone() {
editor.transact(cx, |editor, cx| {
editor.set_clip_at_line_ends(false, cx);
let (map, display_selections) = editor.selections.all_display(cx);
let stable_anchors = display_selections
.into_iter()
.map(|selection| {
let is_multi_cursor = editor.selections.count() > 1;
let range = if selection.start.column() == 0
&& (is_multi_cursor || selection.start.row() == 0)
{
selection.range()
} else {
movement::left(&map, selection.start)
..movement::left(&map, selection.start)
};
range
})
.collect::<Vec<_>>();

let (map, display_selections) = editor.selections.all_display(cx);

let edits = display_selections
.into_iter()
.map(|selection| {
let is_multi_cursor = editor.selections.count() > 1;
let range = if selection.start.column() == 0
&& (is_multi_cursor || selection.start.row() == 0)
{
selection.start..movement::right(&map, selection.start)
} else {
movement::left(&map, selection.start)..selection.start
};
let recover_text = if range.start.row()
>= original_snapshot.max_buffer_row()
|| range.start.column() >= original_snapshot.line_len(range.start.row())
{
"".to_string()
} else {
original_snapshot
.chars_at(range.start.to_offset(&map, Bias::Left))
.next()
.map(|item| item.to_string())
.unwrap_or("".to_string())
};
let current_text = editor
.buffer()
.read(cx)
.snapshot(cx)
.chars_at(range.start.to_offset(&map, Bias::Left))
.next()
.map(|item| item.to_string())
.unwrap_or("".to_string());
let mut replace_text = recover_text.to_string();
let target_range = range.start.to_offset(&map, Bias::Left)
..range.end.to_offset(&map, Bias::Left);
// "\n" need to be handled se
//
// parately, because when a backspace is triggered
// and the previous character is "\n", we don't do a replace, we need delete a "\n"
if current_text == "\n" && current_text != recover_text {
replace_text = "".to_string();
}
(target_range, replace_text)
})
.collect::<Vec<_>>();
editor.buffer().update(cx, |buffer, cx| {
buffer.edit(edits, None, cx);
});

editor.set_clip_at_line_ends(true, cx);
editor.change_selections(None, cx, |s| {
s.select_display_ranges(stable_anchors);
});
});
};
});
}
Loading
Loading