Merge branch 'main' into allow-following-outside-of-projects

This commit is contained in:
Max Brunsfeld 2023-09-28 11:45:40 -07:00
commit a8b35eb8f5
147 changed files with 5383 additions and 1726 deletions

View file

@ -34,6 +34,8 @@ settings = { path = "../settings" }
workspace = { path = "../workspace" }
theme = { path = "../theme" }
language_selector = { path = "../language_selector"}
diagnostics = { path = "../diagnostics" }
zed-actions = { path = "../zed-actions" }
[dev-dependencies]
indoc.workspace = true

438
crates/vim/src/command.rs Normal file
View file

@ -0,0 +1,438 @@
use command_palette::CommandInterceptResult;
use editor::{SortLinesCaseInsensitive, SortLinesCaseSensitive};
use gpui::{impl_actions, Action, AppContext};
use serde_derive::Deserialize;
use workspace::{SaveIntent, Workspace};
use crate::{
motion::{EndOfDocument, Motion},
normal::{
move_cursor,
search::{FindCommand, ReplaceCommand},
JoinLines,
},
state::Mode,
Vim,
};
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct GoToLine {
pub line: u32,
}
impl_actions!(vim, [GoToLine]);
pub fn init(cx: &mut AppContext) {
cx.add_action(|_: &mut Workspace, action: &GoToLine, cx| {
Vim::update(cx, |vim, cx| {
vim.switch_mode(Mode::Normal, false, cx);
move_cursor(vim, Motion::StartOfDocument, Some(action.line as usize), cx);
});
});
}
pub fn command_interceptor(mut query: &str, _: &AppContext) -> Option<CommandInterceptResult> {
// Note: this is a very poor simulation of vim's command palette.
// In the future we should adjust it to handle parsing range syntax,
// and then calling the appropriate commands with/without ranges.
//
// We also need to support passing arguments to commands like :w
// (ideally with filename autocompletion).
//
// For now, you can only do a replace on the % range, and you can
// only use a specific line number range to "go to line"
while query.starts_with(":") {
query = &query[1..];
}
let (name, action) = match query {
// save and quit
"w" | "wr" | "wri" | "writ" | "write" => (
"write",
workspace::Save {
save_intent: Some(SaveIntent::Save),
}
.boxed_clone(),
),
"w!" | "wr!" | "wri!" | "writ!" | "write!" => (
"write!",
workspace::Save {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"q" | "qu" | "qui" | "quit" => (
"quit",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Close),
}
.boxed_clone(),
),
"q!" | "qu!" | "qui!" | "quit!" => (
"quit!",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Skip),
}
.boxed_clone(),
),
"wq" => (
"wq",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Save),
}
.boxed_clone(),
),
"wq!" => (
"wq!",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"x" | "xi" | "xit" | "exi" | "exit" => (
"exit",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::SaveAll),
}
.boxed_clone(),
),
"x!" | "xi!" | "xit!" | "exi!" | "exit!" => (
"exit!",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"up" | "upd" | "upda" | "updat" | "update" => (
"update",
workspace::Save {
save_intent: Some(SaveIntent::SaveAll),
}
.boxed_clone(),
),
"wa" | "wal" | "wall" => (
"wall",
workspace::SaveAll {
save_intent: Some(SaveIntent::SaveAll),
}
.boxed_clone(),
),
"wa!" | "wal!" | "wall!" => (
"wall!",
workspace::SaveAll {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"qa" | "qal" | "qall" | "quita" | "quital" | "quitall" => (
"quitall",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::Close),
}
.boxed_clone(),
),
"qa!" | "qal!" | "qall!" | "quita!" | "quital!" | "quitall!" => (
"quitall!",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::Skip),
}
.boxed_clone(),
),
"xa" | "xal" | "xall" => (
"xall",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::SaveAll),
}
.boxed_clone(),
),
"xa!" | "xal!" | "xall!" => (
"xall!",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"wqa" | "wqal" | "wqall" => (
"wqall",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::SaveAll),
}
.boxed_clone(),
),
"wqa!" | "wqal!" | "wqall!" => (
"wqall!",
workspace::CloseAllItemsAndPanes {
save_intent: Some(SaveIntent::Overwrite),
}
.boxed_clone(),
),
"cq" | "cqu" | "cqui" | "cquit" | "cq!" | "cqu!" | "cqui!" | "cquit!" => {
("cquit!", zed_actions::Quit.boxed_clone())
}
// pane management
"sp" | "spl" | "spli" | "split" => ("split", workspace::SplitUp.boxed_clone()),
"vs" | "vsp" | "vspl" | "vspli" | "vsplit" => {
("vsplit", workspace::SplitLeft.boxed_clone())
}
"new" => (
"new",
workspace::NewFileInDirection(workspace::SplitDirection::Up).boxed_clone(),
),
"vne" | "vnew" => (
"vnew",
workspace::NewFileInDirection(workspace::SplitDirection::Left).boxed_clone(),
),
"tabe" | "tabed" | "tabedi" | "tabedit" => ("tabedit", workspace::NewFile.boxed_clone()),
"tabnew" => ("tabnew", workspace::NewFile.boxed_clone()),
"tabn" | "tabne" | "tabnex" | "tabnext" => {
("tabnext", workspace::ActivateNextItem.boxed_clone())
}
"tabp" | "tabpr" | "tabpre" | "tabprev" | "tabprevi" | "tabprevio" | "tabpreviou"
| "tabprevious" => ("tabprevious", workspace::ActivatePrevItem.boxed_clone()),
"tabN" | "tabNe" | "tabNex" | "tabNext" => {
("tabNext", workspace::ActivatePrevItem.boxed_clone())
}
"tabc" | "tabcl" | "tabclo" | "tabclos" | "tabclose" => (
"tabclose",
workspace::CloseActiveItem {
save_intent: Some(SaveIntent::Close),
}
.boxed_clone(),
),
// quickfix / loclist (merged together for now)
"cl" | "cli" | "clis" | "clist" => ("clist", diagnostics::Deploy.boxed_clone()),
"cc" => ("cc", editor::Hover.boxed_clone()),
"ll" => ("ll", editor::Hover.boxed_clone()),
"cn" | "cne" | "cnex" | "cnext" => ("cnext", editor::GoToDiagnostic.boxed_clone()),
"lne" | "lnex" | "lnext" => ("cnext", editor::GoToDiagnostic.boxed_clone()),
"cpr" | "cpre" | "cprev" | "cprevi" | "cprevio" | "cpreviou" | "cprevious" => {
("cprevious", editor::GoToPrevDiagnostic.boxed_clone())
}
"cN" | "cNe" | "cNex" | "cNext" => ("cNext", editor::GoToPrevDiagnostic.boxed_clone()),
"lp" | "lpr" | "lpre" | "lprev" | "lprevi" | "lprevio" | "lpreviou" | "lprevious" => {
("lprevious", editor::GoToPrevDiagnostic.boxed_clone())
}
"lN" | "lNe" | "lNex" | "lNext" => ("lNext", editor::GoToPrevDiagnostic.boxed_clone()),
// modify the buffer (should accept [range])
"j" | "jo" | "joi" | "join" => ("join", JoinLines.boxed_clone()),
"d" | "de" | "del" | "dele" | "delet" | "delete" | "dl" | "dell" | "delel" | "deletl"
| "deletel" | "dp" | "dep" | "delp" | "delep" | "deletp" | "deletep" => {
("delete", editor::DeleteLine.boxed_clone())
}
"sor" | "sor " | "sort" | "sort " => ("sort", SortLinesCaseSensitive.boxed_clone()),
"sor i" | "sort i" => ("sort i", SortLinesCaseInsensitive.boxed_clone()),
// goto (other ranges handled under _ => )
"$" => ("$", EndOfDocument.boxed_clone()),
_ => {
if query.starts_with("/") || query.starts_with("?") {
(
query,
FindCommand {
query: query[1..].to_string(),
backwards: query.starts_with("?"),
}
.boxed_clone(),
)
} else if query.starts_with("%") {
(
query,
ReplaceCommand {
query: query.to_string(),
}
.boxed_clone(),
)
} else if let Ok(line) = query.parse::<u32>() {
(query, GoToLine { line }.boxed_clone())
} else {
return None;
}
}
};
let string = ":".to_owned() + name;
let positions = generate_positions(&string, query);
Some(CommandInterceptResult {
action,
string,
positions,
})
}
fn generate_positions(string: &str, query: &str) -> Vec<usize> {
let mut positions = Vec::new();
let mut chars = query.chars().into_iter();
let Some(mut current) = chars.next() else {
return positions;
};
for (i, c) in string.chars().enumerate() {
if c == current {
positions.push(i);
if let Some(c) = chars.next() {
current = c;
} else {
break;
}
}
}
positions
}
#[cfg(test)]
mod test {
use std::path::Path;
use crate::test::{NeovimBackedTestContext, VimTestContext};
use gpui::{executor::Foreground, TestAppContext};
use indoc::indoc;
#[gpui::test]
async fn test_command_basics(cx: &mut TestAppContext) {
if let Foreground::Deterministic { cx_id: _, executor } = cx.foreground().as_ref() {
executor.run_until_parked();
}
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.set_shared_state(indoc! {"
ˇa
b
c"})
.await;
cx.simulate_shared_keystrokes([":", "j", "enter"]).await;
// hack: our cursor positionining after a join command is wrong
cx.simulate_shared_keystrokes(["^"]).await;
cx.assert_shared_state(indoc! {
"ˇa b
c"
})
.await;
}
#[gpui::test]
async fn test_command_goto(cx: &mut TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.set_shared_state(indoc! {"
ˇa
b
c"})
.await;
cx.simulate_shared_keystrokes([":", "3", "enter"]).await;
cx.assert_shared_state(indoc! {"
a
b
ˇc"})
.await;
}
#[gpui::test]
async fn test_command_replace(cx: &mut TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.set_shared_state(indoc! {"
ˇa
b
c"})
.await;
cx.simulate_shared_keystrokes([":", "%", "s", "/", "b", "/", "d", "enter"])
.await;
cx.assert_shared_state(indoc! {"
a
ˇd
c"})
.await;
cx.simulate_shared_keystrokes([
":", "%", "s", ":", ".", ":", "\\", "0", "\\", "0", "enter",
])
.await;
cx.assert_shared_state(indoc! {"
aa
dd
ˇcc"})
.await;
}
#[gpui::test]
async fn test_command_search(cx: &mut TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.set_shared_state(indoc! {"
ˇa
b
a
c"})
.await;
cx.simulate_shared_keystrokes([":", "/", "b", "enter"])
.await;
cx.assert_shared_state(indoc! {"
a
ˇb
a
c"})
.await;
cx.simulate_shared_keystrokes([":", "?", "a", "enter"])
.await;
cx.assert_shared_state(indoc! {"
ˇa
b
a
c"})
.await;
}
#[gpui::test]
async fn test_command_write(cx: &mut TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
let path = Path::new("/root/dir/file.rs");
let fs = cx.workspace(|workspace, cx| workspace.project().read(cx).fs().clone());
cx.simulate_keystrokes(["i", "@", "escape"]);
cx.simulate_keystrokes([":", "w", "enter"]);
assert_eq!(fs.load(&path).await.unwrap(), "@\n");
fs.as_fake()
.write_file_internal(path, "oops\n".to_string())
.unwrap();
// conflict!
cx.simulate_keystrokes(["i", "@", "escape"]);
cx.simulate_keystrokes([":", "w", "enter"]);
let window = cx.window;
assert!(window.has_pending_prompt(cx.cx));
// "Cancel"
window.simulate_prompt_answer(0, cx.cx);
assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
assert!(!window.has_pending_prompt(cx.cx));
// force overwrite
cx.simulate_keystrokes([":", "w", "!", "enter"]);
assert!(!window.has_pending_prompt(cx.cx));
assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
}
#[gpui::test]
async fn test_command_quit(cx: &mut TestAppContext) {
let mut cx = VimTestContext::new(cx, true).await;
cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
cx.simulate_keystrokes([":", "q", "enter"]);
cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 1));
cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
cx.simulate_keystrokes([":", "q", "a", "enter"]);
cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 0));
}
}

View file

@ -4,7 +4,7 @@ mod delete;
mod paste;
pub(crate) mod repeat;
mod scroll;
mod search;
pub(crate) mod search;
pub mod substitute;
mod yank;
@ -168,7 +168,12 @@ pub fn normal_object(object: Object, cx: &mut WindowContext) {
})
}
fn move_cursor(vim: &mut Vim, motion: Motion, times: Option<usize>, cx: &mut WindowContext) {
pub(crate) fn move_cursor(
vim: &mut Vim,
motion: Motion,
times: Option<usize>,
cx: &mut WindowContext,
) {
vim.update_active_editor(cx, |editor, cx| {
editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_cursors_with(|map, cursor, goal| {

View file

@ -15,19 +15,19 @@ actions!(
pub fn init(cx: &mut AppContext) {
cx.add_action(|_: &mut Workspace, _: &LineDown, cx| {
scroll(cx, |c| ScrollAmount::Line(c.unwrap_or(1.)))
scroll(cx, false, |c| ScrollAmount::Line(c.unwrap_or(1.)))
});
cx.add_action(|_: &mut Workspace, _: &LineUp, cx| {
scroll(cx, |c| ScrollAmount::Line(-c.unwrap_or(1.)))
scroll(cx, false, |c| ScrollAmount::Line(-c.unwrap_or(1.)))
});
cx.add_action(|_: &mut Workspace, _: &PageDown, cx| {
scroll(cx, |c| ScrollAmount::Page(c.unwrap_or(1.)))
scroll(cx, false, |c| ScrollAmount::Page(c.unwrap_or(1.)))
});
cx.add_action(|_: &mut Workspace, _: &PageUp, cx| {
scroll(cx, |c| ScrollAmount::Page(-c.unwrap_or(1.)))
scroll(cx, false, |c| ScrollAmount::Page(-c.unwrap_or(1.)))
});
cx.add_action(|_: &mut Workspace, _: &ScrollDown, cx| {
scroll(cx, |c| {
scroll(cx, true, |c| {
if let Some(c) = c {
ScrollAmount::Line(c)
} else {
@ -36,7 +36,7 @@ pub fn init(cx: &mut AppContext) {
})
});
cx.add_action(|_: &mut Workspace, _: &ScrollUp, cx| {
scroll(cx, |c| {
scroll(cx, true, |c| {
if let Some(c) = c {
ScrollAmount::Line(-c)
} else {
@ -46,15 +46,27 @@ pub fn init(cx: &mut AppContext) {
});
}
fn scroll(cx: &mut ViewContext<Workspace>, by: fn(c: Option<f32>) -> ScrollAmount) {
fn scroll(
cx: &mut ViewContext<Workspace>,
move_cursor: bool,
by: fn(c: Option<f32>) -> ScrollAmount,
) {
Vim::update(cx, |vim, cx| {
let amount = by(vim.take_count(cx).map(|c| c as f32));
vim.update_active_editor(cx, |editor, cx| scroll_editor(editor, &amount, cx));
vim.update_active_editor(cx, |editor, cx| {
scroll_editor(editor, move_cursor, &amount, cx)
});
})
}
fn scroll_editor(editor: &mut Editor, amount: &ScrollAmount, cx: &mut ViewContext<Editor>) {
fn scroll_editor(
editor: &mut Editor,
preserve_cursor_position: bool,
amount: &ScrollAmount,
cx: &mut ViewContext<Editor>,
) {
let should_move_cursor = editor.newest_selection_on_screen(cx).is_eq();
let old_top_anchor = editor.scroll_manager.anchor().anchor;
editor.scroll_screen(amount, cx);
if should_move_cursor {
@ -68,8 +80,14 @@ fn scroll_editor(editor: &mut Editor, amount: &ScrollAmount, cx: &mut ViewContex
editor.change_selections(None, cx, |s| {
s.move_with(|map, selection| {
let head = selection.head();
let mut head = selection.head();
let top = top_anchor.to_display_point(map);
if preserve_cursor_position {
let old_top = old_top_anchor.to_display_point(map);
let new_row = top.row() + selection.head().row() - old_top.row();
head = map.clip_point(DisplayPoint::new(new_row, head.column()), Bias::Left)
}
let min_row = top.row() + VERTICAL_SCROLL_MARGIN as u32;
let max_row = top.row() + visible_rows - VERTICAL_SCROLL_MARGIN as u32 - 1;
@ -92,7 +110,10 @@ fn scroll_editor(editor: &mut Editor, amount: &ScrollAmount, cx: &mut ViewContex
#[cfg(test)]
mod test {
use crate::{state::Mode, test::VimTestContext};
use crate::{
state::Mode,
test::{NeovimBackedTestContext, VimTestContext},
};
use gpui::geometry::vector::vec2f;
use indoc::indoc;
use language::Point;
@ -148,10 +169,10 @@ mod test {
});
cx.simulate_keystrokes(["ctrl-d"]);
cx.update_editor(|editor, cx| {
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 2.0));
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.0));
assert_eq!(
editor.selections.newest(cx).range(),
Point::new(5, 0)..Point::new(5, 0)
Point::new(6, 0)..Point::new(6, 0)
)
});
@ -162,11 +183,48 @@ mod test {
});
cx.simulate_keystrokes(["v", "ctrl-d"]);
cx.update_editor(|editor, cx| {
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 2.0));
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.0));
assert_eq!(
editor.selections.newest(cx).range(),
Point::new(0, 0)..Point::new(5, 1)
Point::new(0, 0)..Point::new(6, 1)
)
});
}
#[gpui::test]
async fn test_ctrl_d_u(cx: &mut gpui::TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.set_scroll_height(10).await;
pub fn sample_text(rows: usize, cols: usize, start_char: char) -> String {
let mut text = String::new();
for row in 0..rows {
let c: char = (start_char as u32 + row as u32) as u8 as char;
let mut line = c.to_string().repeat(cols);
if row < rows - 1 {
line.push('\n');
}
text += &line;
}
text
}
let content = "ˇ".to_owned() + &sample_text(26, 2, 'a');
cx.set_shared_state(&content).await;
// skip over the scrolloff at the top
// test ctrl-d
cx.simulate_shared_keystrokes(["4", "j", "ctrl-d"]).await;
cx.assert_state_matches().await;
cx.simulate_shared_keystrokes(["ctrl-d"]).await;
cx.assert_state_matches().await;
cx.simulate_shared_keystrokes(["g", "g", "ctrl-d"]).await;
cx.assert_state_matches().await;
// test ctrl-u
cx.simulate_shared_keystrokes(["ctrl-u"]).await;
cx.assert_state_matches().await;
cx.simulate_shared_keystrokes(["ctrl-d", "ctrl-d", "4", "j", "ctrl-u", "ctrl-u"])
.await;
cx.assert_state_matches().await;
}
}

View file

@ -3,7 +3,7 @@ use search::{buffer_search, BufferSearchBar, SearchMode, SearchOptions};
use serde_derive::Deserialize;
use workspace::{searchable::Direction, Pane, Workspace};
use crate::{state::SearchState, Vim};
use crate::{motion::Motion, normal::move_cursor, state::SearchState, Vim};
#[derive(Clone, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
@ -25,7 +25,29 @@ pub(crate) struct Search {
backwards: bool,
}
impl_actions!(vim, [MoveToNext, MoveToPrev, Search]);
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct FindCommand {
pub query: String,
pub backwards: bool,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ReplaceCommand {
pub query: String,
}
#[derive(Debug, Default)]
struct Replacement {
search: String,
replacement: String,
should_replace_all: bool,
is_case_sensitive: bool,
}
impl_actions!(
vim,
[MoveToNext, MoveToPrev, Search, FindCommand, ReplaceCommand]
);
actions!(vim, [SearchSubmit]);
pub(crate) fn init(cx: &mut AppContext) {
@ -34,6 +56,9 @@ pub(crate) fn init(cx: &mut AppContext) {
cx.add_action(search);
cx.add_action(search_submit);
cx.add_action(search_deploy);
cx.add_action(find_command);
cx.add_action(replace_command);
}
fn move_to_next(workspace: &mut Workspace, action: &MoveToNext, cx: &mut ViewContext<Workspace>) {
@ -65,6 +90,7 @@ fn search(workspace: &mut Workspace, action: &Search, cx: &mut ViewContext<Works
cx.focus_self();
if query.is_empty() {
search_bar.set_replacement(None, cx);
search_bar.set_search_options(SearchOptions::CASE_SENSITIVE, cx);
search_bar.activate_search_mode(SearchMode::Regex, cx);
}
@ -151,6 +177,174 @@ pub fn move_to_internal(
});
}
fn find_command(workspace: &mut Workspace, action: &FindCommand, cx: &mut ViewContext<Workspace>) {
let pane = workspace.active_pane().clone();
pane.update(cx, |pane, cx| {
if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
let search = search_bar.update(cx, |search_bar, cx| {
if !search_bar.show(cx) {
return None;
}
let mut query = action.query.clone();
if query == "" {
query = search_bar.query(cx);
};
search_bar.activate_search_mode(SearchMode::Regex, cx);
Some(search_bar.search(&query, Some(SearchOptions::CASE_SENSITIVE), cx))
});
let Some(search) = search else { return };
let search_bar = search_bar.downgrade();
let direction = if action.backwards {
Direction::Prev
} else {
Direction::Next
};
cx.spawn(|_, mut cx| async move {
search.await?;
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.select_match(direction, 1, cx)
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
})
}
fn replace_command(
workspace: &mut Workspace,
action: &ReplaceCommand,
cx: &mut ViewContext<Workspace>,
) {
let replacement = parse_replace_all(&action.query);
let pane = workspace.active_pane().clone();
pane.update(cx, |pane, cx| {
let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() else {
return;
};
let search = search_bar.update(cx, |search_bar, cx| {
if !search_bar.show(cx) {
return None;
}
let mut options = SearchOptions::default();
if replacement.is_case_sensitive {
options.set(SearchOptions::CASE_SENSITIVE, true)
}
let search = if replacement.search == "" {
search_bar.query(cx)
} else {
replacement.search
};
search_bar.set_replacement(Some(&replacement.replacement), cx);
search_bar.activate_search_mode(SearchMode::Regex, cx);
Some(search_bar.search(&search, Some(options), cx))
});
let Some(search) = search else { return };
let search_bar = search_bar.downgrade();
cx.spawn(|_, mut cx| async move {
search.await?;
search_bar.update(&mut cx, |search_bar, cx| {
if replacement.should_replace_all {
search_bar.select_last_match(cx);
search_bar.replace_all(&Default::default(), cx);
Vim::update(cx, |vim, cx| {
move_cursor(
vim,
Motion::StartOfLine {
display_lines: false,
},
None,
cx,
)
})
}
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
})
}
// convert a vim query into something more usable by zed.
// we don't attempt to fully convert between the two regex syntaxes,
// but we do flip \( and \) to ( and ) (and vice-versa) in the pattern,
// and convert \0..\9 to $0..$9 in the replacement so that common idioms work.
fn parse_replace_all(query: &str) -> Replacement {
let mut chars = query.chars();
if Some('%') != chars.next() || Some('s') != chars.next() {
return Replacement::default();
}
let Some(delimeter) = chars.next() else {
return Replacement::default();
};
let mut search = String::new();
let mut replacement = String::new();
let mut flags = String::new();
let mut buffer = &mut search;
let mut escaped = false;
// 0 - parsing search
// 1 - parsing replacement
// 2 - parsing flags
let mut phase = 0;
for c in chars {
if escaped {
escaped = false;
if phase == 1 && c.is_digit(10) {
buffer.push('$')
// unescape escaped parens
} else if phase == 0 && c == '(' || c == ')' {
} else if c != delimeter {
buffer.push('\\')
}
buffer.push(c)
} else if c == '\\' {
escaped = true;
} else if c == delimeter {
if phase == 0 {
buffer = &mut replacement;
phase = 1;
} else if phase == 1 {
buffer = &mut flags;
phase = 2;
} else {
break;
}
} else {
// escape unescaped parens
if phase == 0 && c == '(' || c == ')' {
buffer.push('\\')
}
buffer.push(c)
}
}
let mut replacement = Replacement {
search,
replacement,
should_replace_all: true,
is_case_sensitive: true,
};
for c in flags.chars() {
match c {
'g' | 'I' => {}
'c' | 'n' => replacement.should_replace_all = false,
'i' => replacement.is_case_sensitive = false,
_ => {}
}
}
replacement
}
#[cfg(test)]
mod test {
use std::sync::Arc;

View file

@ -186,9 +186,6 @@ async fn test_selection_on_search(cx: &mut gpui::TestAppContext) {
assert_eq!(bar.query(cx), "cc");
});
// wait for the query editor change event to fire.
search_bar.next_notification(&cx).await;
cx.update_editor(|editor, cx| {
let highlights = editor.all_text_background_highlights(cx);
assert_eq!(3, highlights.len());

View file

@ -1,7 +1,5 @@
use std::ops::{Deref, DerefMut};
use gpui::ContextHandle;
use crate::state::Mode;
use super::{ExemptionFeatures, NeovimBackedTestContext, SUPPORTED_FEATURES};
@ -33,26 +31,17 @@ impl<'a, const COUNT: usize> NeovimBackedBindingTestContext<'a, COUNT> {
self.consume().binding(keystrokes)
}
pub async fn assert(
&mut self,
marked_positions: &str,
) -> Option<(ContextHandle, ContextHandle)> {
pub async fn assert(&mut self, marked_positions: &str) {
self.cx
.assert_binding_matches(self.keystrokes_under_test, marked_positions)
.await
.await;
}
pub async fn assert_exempted(
&mut self,
marked_positions: &str,
feature: ExemptionFeatures,
) -> Option<(ContextHandle, ContextHandle)> {
pub async fn assert_exempted(&mut self, marked_positions: &str, feature: ExemptionFeatures) {
if SUPPORTED_FEATURES.contains(&feature) {
self.cx
.assert_binding_matches(self.keystrokes_under_test, marked_positions)
.await
} else {
None
}
}

View file

@ -1,9 +1,10 @@
use editor::scroll::VERTICAL_SCROLL_MARGIN;
use indoc::indoc;
use settings::SettingsStore;
use std::ops::{Deref, DerefMut, Range};
use collections::{HashMap, HashSet};
use gpui::ContextHandle;
use gpui::{geometry::vector::vec2f, ContextHandle};
use language::{
language_settings::{AllLanguageSettings, SoftWrap},
OffsetRangeExt,
@ -106,26 +107,25 @@ impl<'a> NeovimBackedTestContext<'a> {
pub async fn simulate_shared_keystrokes<const COUNT: usize>(
&mut self,
keystroke_texts: [&str; COUNT],
) -> ContextHandle {
) {
for keystroke_text in keystroke_texts.into_iter() {
self.recent_keystrokes.push(keystroke_text.to_string());
self.neovim.send_keystroke(keystroke_text).await;
}
self.simulate_keystrokes(keystroke_texts)
self.simulate_keystrokes(keystroke_texts);
}
pub async fn set_shared_state(&mut self, marked_text: &str) -> ContextHandle {
pub async fn set_shared_state(&mut self, marked_text: &str) {
let mode = if marked_text.contains("»") {
Mode::Visual
} else {
Mode::Normal
};
let context_handle = self.set_state(marked_text, mode);
self.set_state(marked_text, mode);
self.last_set_state = Some(marked_text.to_string());
self.recent_keystrokes = Vec::new();
self.neovim.set_state(marked_text).await;
self.is_dirty = true;
context_handle
}
pub async fn set_shared_wrap(&mut self, columns: u32) {
@ -133,7 +133,9 @@ impl<'a> NeovimBackedTestContext<'a> {
panic!("nvim doesn't support columns < 12")
}
self.neovim.set_option("wrap").await;
self.neovim.set_option("columns=12").await;
self.neovim
.set_option(&format!("columns={}", columns))
.await;
self.update(|cx| {
cx.update_global(|settings: &mut SettingsStore, cx| {
@ -145,6 +147,20 @@ impl<'a> NeovimBackedTestContext<'a> {
})
}
pub async fn set_scroll_height(&mut self, rows: u32) {
// match Zed's scrolling behavior
self.neovim
.set_option(&format!("scrolloff={}", VERTICAL_SCROLL_MARGIN))
.await;
// +2 to account for the vim command UI at the bottom.
self.neovim.set_option(&format!("lines={}", rows + 2)).await;
let window = self.window;
let line_height =
self.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
window.simulate_resize(vec2f(1000., (rows as f32) * line_height), &mut self.cx);
}
pub async fn set_neovim_option(&mut self, option: &str) {
self.neovim.set_option(option).await;
}
@ -288,18 +304,18 @@ impl<'a> NeovimBackedTestContext<'a> {
&mut self,
keystrokes: [&str; COUNT],
initial_state: &str,
) -> Option<(ContextHandle, ContextHandle)> {
) {
if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
match possible_exempted_keystrokes {
Some(exempted_keystrokes) => {
if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
// This keystroke was exempted for this insertion text
return None;
return;
}
}
None => {
// All keystrokes for this insertion text are exempted
return None;
return;
}
}
}
@ -307,7 +323,6 @@ impl<'a> NeovimBackedTestContext<'a> {
let _state_context = self.set_shared_state(initial_state).await;
let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
self.assert_state_matches().await;
Some((_state_context, _keystroke_context))
}
pub async fn assert_binding_matches_all<const COUNT: usize>(

View file

@ -65,7 +65,13 @@ impl NeovimConnection {
// Ensure we don't create neovim connections in parallel
let _lock = NEOVIM_LOCK.lock();
let (nvim, join_handle, child) = new_child_cmd(
&mut Command::new("nvim").arg("--embed").arg("--clean"),
&mut Command::new("nvim")
.arg("--embed")
.arg("--clean")
// disable swap (otherwise after about 1000 test runs you run out of swap file names)
.arg("-n")
// disable writing files (just in case)
.arg("-m"),
handler,
)
.await

View file

@ -1,6 +1,7 @@
#[cfg(test)]
mod test;
mod command;
mod editor_events;
mod insert;
mod mode_indicator;
@ -13,6 +14,7 @@ mod visual;
use anyhow::Result;
use collections::{CommandPaletteFilter, HashMap};
use command_palette::CommandPaletteInterceptor;
use editor::{movement, Editor, EditorMode, Event};
use gpui::{
actions, impl_actions, keymap_matcher::KeymapContext, keymap_matcher::MatchResult, Action,
@ -63,6 +65,7 @@ pub fn init(cx: &mut AppContext) {
insert::init(cx);
object::init(cx);
motion::init(cx);
command::init(cx);
// Vim Actions
cx.add_action(|_: &mut Workspace, &SwitchMode(mode): &SwitchMode, cx| {
@ -469,6 +472,12 @@ impl Vim {
}
});
if self.enabled {
cx.set_global::<CommandPaletteInterceptor>(Box::new(command::command_interceptor));
} else if cx.has_global::<CommandPaletteInterceptor>() {
let _ = cx.remove_global::<CommandPaletteInterceptor>();
}
cx.update_active_window(|cx| {
if self.enabled {
let active_editor = cx

View file

@ -1,3 +1,4 @@
use anyhow::Result;
use std::{cmp, sync::Arc};
use collections::HashMap;
@ -28,6 +29,8 @@ actions!(
VisualDelete,
VisualYank,
OtherEnd,
SelectNext,
SelectPrevious,
]
);
@ -46,6 +49,9 @@ pub fn init(cx: &mut AppContext) {
cx.add_action(other_end);
cx.add_action(delete);
cx.add_action(yank);
cx.add_action(select_next);
cx.add_action(select_previous);
}
pub fn visual_motion(motion: Motion, times: Option<usize>, cx: &mut WindowContext) {
@ -384,6 +390,50 @@ pub(crate) fn visual_replace(text: Arc<str>, cx: &mut WindowContext) {
});
}
pub fn select_next(
_: &mut Workspace,
_: &SelectNext,
cx: &mut ViewContext<Workspace>,
) -> Result<()> {
Vim::update(cx, |vim, cx| {
let count =
vim.take_count(cx)
.unwrap_or_else(|| if vim.state().mode.is_visual() { 1 } else { 2 });
vim.update_active_editor(cx, |editor, cx| {
for _ in 0..count {
match editor.select_next(&Default::default(), cx) {
Err(a) => return Err(a),
_ => {}
}
}
Ok(())
})
})
.unwrap_or(Ok(()))
}
pub fn select_previous(
_: &mut Workspace,
_: &SelectPrevious,
cx: &mut ViewContext<Workspace>,
) -> Result<()> {
Vim::update(cx, |vim, cx| {
let count =
vim.take_count(cx)
.unwrap_or_else(|| if vim.state().mode.is_visual() { 1 } else { 2 });
vim.update_active_editor(cx, |editor, cx| {
for _ in 0..count {
match editor.select_previous(&Default::default(), cx) {
Err(a) => return Err(a),
_ => {}
}
}
Ok(())
})
})
.unwrap_or(Ok(()))
}
#[cfg(test)]
mod test {
use indoc::indoc;

View file

@ -0,0 +1,6 @@
{"Put":{"state":"ˇa\nb\nc"}}
{"Key":":"}
{"Key":"j"}
{"Key":"enter"}
{"Key":"^"}
{"Get":{"state":"ˇa b\nc","mode":"Normal"}}

View file

@ -0,0 +1,5 @@
{"Put":{"state":"ˇa\nb\nc"}}
{"Key":":"}
{"Key":"3"}
{"Key":"enter"}
{"Get":{"state":"a\nb\nˇc","mode":"Normal"}}

View file

@ -0,0 +1,29 @@
{"Put":{"state":"ˇa\nb\nc"}}
{"Key":":"}
{"Key":"%"}
{"Key":"s"}
{"Key":"/"}
{"Key":"b"}
{"Key":"/"}
{"Key":"d"}
{"Key":"enter"}
{"Get":{"state":"a\nˇd\nc","mode":"Normal"}}
{"Key":":"}
{"Key":"%"}
{"Key":"s"}
{"Key":":"}
{"Key":"."}
{"Key":":"}
{"Key":"\\"}
{"Key":"0"}
{"Key":"\\"}
{"Key":"0"}
{"Key":"enter"}
{"Get":{"state":"aa\ndd\nˇcc","mode":"Normal"}}
{"Key":":"}
{"Key":"%"}
{"Key":"s"}
{"Key":"/"}
{"Key":"/"}
{"Key":"/"}
{"Key":"enter"}

View file

@ -0,0 +1,11 @@
{"Put":{"state":"ˇa\nb\na\nc"}}
{"Key":":"}
{"Key":"/"}
{"Key":"b"}
{"Key":"enter"}
{"Get":{"state":"a\nˇb\na\nc","mode":"Normal"}}
{"Key":":"}
{"Key":"?"}
{"Key":"a"}
{"Key":"enter"}
{"Get":{"state":"ˇa\nb\na\nc","mode":"Normal"}}

View file

@ -0,0 +1,22 @@
{"SetOption":{"value":"scrolloff=3"}}
{"SetOption":{"value":"lines=12"}}
{"Put":{"state":"ˇaa\nbb\ncc\ndd\nee\nff\ngg\nhh\nii\njj\nkk\nll\nmm\nnn\noo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz"}}
{"Key":"4"}
{"Key":"j"}
{"Key":"ctrl-d"}
{"Get":{"state":"aa\nbb\ncc\ndd\nee\nff\ngg\nhh\nii\nˇjj\nkk\nll\nmm\nnn\noo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz","mode":"Normal"}}
{"Key":"ctrl-d"}
{"Get":{"state":"aa\nbb\ncc\ndd\nee\nff\ngg\nhh\nii\njj\nkk\nll\nmm\nnn\nˇoo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz","mode":"Normal"}}
{"Key":"g"}
{"Key":"g"}
{"Key":"ctrl-d"}
{"Get":{"state":"aa\nbb\ncc\ndd\nee\nff\ngg\nhh\nˇii\njj\nkk\nll\nmm\nnn\noo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz","mode":"Normal"}}
{"Key":"ctrl-u"}
{"Get":{"state":"aa\nbb\ncc\nˇdd\nee\nff\ngg\nhh\nii\njj\nkk\nll\nmm\nnn\noo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz","mode":"Normal"}}
{"Key":"ctrl-d"}
{"Key":"ctrl-d"}
{"Key":"4"}
{"Key":"j"}
{"Key":"ctrl-u"}
{"Key":"ctrl-u"}
{"Get":{"state":"aa\nbb\ncc\ndd\nee\nff\ngg\nˇhh\nii\njj\nkk\nll\nmm\nnn\noo\npp\nqq\nrr\nss\ntt\nuu\nvv\nww\nxx\nyy\nzz","mode":"Normal"}}