vim: Add global marks (#25702)

Closes https://github.com/zed-industries/zed/issues/13111

Release Notes:

- vim: Added global marks `'[A-Z]`
- vim: Added persistence for global (and local) marks. When re-opening
the same workspace your previous marks will be available.

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
This commit is contained in:
AidanV 2025-03-14 22:58:34 -07:00 committed by GitHub
parent 148131786f
commit 265caed15e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 982 additions and 281 deletions

347
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -326,6 +326,13 @@ impl Bind for Arc<Path> {
self.as_ref().bind(statement, start_index)
}
}
impl Column for Arc<Path> {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let blob = statement.column_blob(start_index)?;
PathBuf::try_from_bytes(blob).map(|path| (Arc::from(path.as_path()), start_index + 1))
}
}
impl StaticColumnCount for PathBuf {}
impl Bind for PathBuf {

View file

@ -22,6 +22,7 @@ async-trait = { workspace = true, "optional" = true }
collections.workspace = true
command_palette.workspace = true
command_palette_hooks.workspace = true
db.workspace = true
editor.workspace = true
futures.workspace = true
gpui.workspace = true
@ -32,6 +33,7 @@ log.workspace = true
multi_buffer.workspace = true
nvim-rs = { git = "https://github.com/KillTheMule/nvim-rs", branch = "master", features = ["use_tokio"], optional = true }
picker.workspace = true
project.workspace = true
regex.workspace = true
schemars.workspace = true
search.workspace = true
@ -40,6 +42,7 @@ serde_derive.workspace = true
serde_json.workspace = true
settings.workspace = true
task.workspace = true
text.workspace = true
theme.workspace = true
tokio = { version = "1.15", features = ["full"], optional = true }
ui.workspace = true

View file

@ -1,4 +1,6 @@
use editor::{display_map::ToDisplayPoint, movement, scroll::Autoscroll, Bias, Direction, Editor};
use editor::{
display_map::ToDisplayPoint, movement, scroll::Autoscroll, Anchor, Bias, Direction, Editor,
};
use gpui::{actions, Context, Window};
use crate::{state::Mode, Vim};
@ -48,8 +50,10 @@ impl Vim {
}
pub(crate) fn push_to_change_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some((map, selections)) = self.update_editor(window, cx, |_, editor, _, cx| {
editor.selections.all_adjusted_display(cx)
let Some((map, selections, buffer)) = self.update_editor(window, cx, |_, editor, _, cx| {
let (map, selections) = editor.selections.all_adjusted_display(cx);
let buffer = editor.buffer().clone();
(map, selections, buffer)
}) else {
return;
};
@ -65,7 +69,7 @@ impl Vim {
})
.unwrap_or(false);
let new_positions = selections
let new_positions: Vec<Anchor> = selections
.into_iter()
.map(|s| {
let point = if self.mode == Mode::Insert {
@ -81,7 +85,8 @@ impl Vim {
if pop_state {
self.change_list.pop();
}
self.change_list.push(new_positions);
self.change_list.push(new_positions.clone());
self.set_mark(".".to_string(), new_positions, &buffer, window, cx)
}
}

View file

@ -37,7 +37,7 @@ use crate::{
JoinLines,
},
object::Object,
state::Mode,
state::{Mark, Mode},
visual::VisualDeleteLine,
ToggleRegistersView, Vim,
};
@ -284,6 +284,7 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
true,
true,
vec![Point::new(range.start.0, 0)..end],
window,
cx,
)
}
@ -594,9 +595,14 @@ impl Position {
}
}
Position::Mark { name, offset } => {
let Some(mark) = vim.marks.get(&name.to_string()).and_then(|vec| vec.last()) else {
let Some(Mark::Local(anchors)) =
vim.get_mark(&name.to_string(), editor, window, cx)
else {
return Err(anyhow!("mark {} not set", name));
};
let Some(mark) = anchors.last() else {
return Err(anyhow!("mark {} contains empty anchors", name));
};
mark.to_point(&snapshot.buffer_snapshot)
.row
.saturating_add_signed(*offset)

View file

@ -254,7 +254,7 @@ impl Vim {
});
});
vim.copy_selections_content(editor, false, cx);
vim.copy_selections_content(editor, false, window, cx);
editor.insert("", window, cx);
});
}

View file

@ -25,7 +25,7 @@ impl Vim {
let count = Vim::take_count(cx).unwrap_or(1);
self.stop_recording_immediately(action.boxed_clone(), cx);
if count <= 1 || Vim::globals(cx).dot_replaying {
self.create_mark("^".into(), false, window, cx);
self.create_mark("^".into(), window, cx);
self.update_editor(window, cx, |_, editor, window, cx| {
editor.dismiss_menus_and_popups(false, window, cx);
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {

View file

@ -1889,7 +1889,7 @@ pub(crate) fn end_of_line(
}
}
fn sentence_backwards(
pub(crate) fn sentence_backwards(
map: &DisplaySnapshot,
point: DisplayPoint,
mut times: usize,
@ -1935,7 +1935,11 @@ fn sentence_backwards(
DisplayPoint::zero()
}
fn sentence_forwards(map: &DisplaySnapshot, point: DisplayPoint, mut times: usize) -> DisplayPoint {
pub(crate) fn sentence_forwards(
map: &DisplaySnapshot,
point: DisplayPoint,
mut times: usize,
) -> DisplayPoint {
let start = point.to_point(map).to_offset(&map.buffer_snapshot);
let mut chars = map.buffer_chars_at(start).peekable();

View file

@ -18,7 +18,7 @@ use crate::{
indent::IndentDirection,
motion::{self, first_non_whitespace, next_line_end, right, Motion},
object::Object,
state::{Mode, Operator},
state::{Mark, Mode, Operator},
surrounds::SurroundsType,
Vim,
};
@ -355,11 +355,13 @@ impl Vim {
self.start_recording(cx);
self.switch_mode(Mode::Insert, false, window, cx);
self.update_editor(window, cx, |vim, editor, window, cx| {
if let Some(marks) = vim.marks.get("^") {
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
s.select_anchor_ranges(marks.iter().map(|mark| *mark..*mark))
});
}
let Some(Mark::Local(marks)) = vim.get_mark("^", editor, window, cx) else {
return;
};
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
s.select_anchor_ranges(marks.iter().map(|mark| *mark..*mark))
});
});
}

View file

@ -76,7 +76,7 @@ impl Vim {
}
});
});
vim.copy_selections_content(editor, motion.linewise(), cx);
vim.copy_selections_content(editor, motion.linewise(), window, cx);
editor.insert("", window, cx);
editor.refresh_inline_completion(true, false, window, cx);
});
@ -107,7 +107,7 @@ impl Vim {
});
});
if objects_found {
vim.copy_selections_content(editor, false, cx);
vim.copy_selections_content(editor, false, window, cx);
editor.insert("", window, cx);
editor.refresh_inline_completion(true, false, window, cx);
}

View file

@ -60,7 +60,7 @@ impl Vim {
}
});
});
vim.copy_selections_content(editor, motion.linewise(), cx);
vim.copy_selections_content(editor, motion.linewise(), window, cx);
editor.insert("", window, cx);
// Fixup cursor position after the deletion
@ -148,7 +148,7 @@ impl Vim {
}
});
});
vim.copy_selections_content(editor, false, cx);
vim.copy_selections_content(editor, false, window, cx);
editor.insert("", window, cx);
// Fixup cursor position after the deletion

View file

@ -1,39 +1,34 @@
use std::{ops::Range, sync::Arc};
use std::{ops::Range, path::Path, sync::Arc};
use editor::{
display_map::{DisplaySnapshot, ToDisplayPoint},
movement,
scroll::Autoscroll,
Anchor, Bias, DisplayPoint,
Anchor, Bias, DisplayPoint, Editor, MultiBuffer,
};
use gpui::{Context, Window};
use gpui::{Context, Entity, EntityId, UpdateGlobal, Window};
use language::SelectionGoal;
use text::Point;
use ui::App;
use workspace::OpenOptions;
use crate::{
motion::{self, Motion},
state::Mode,
state::{Mark, Mode, VimGlobals},
Vim,
};
impl Vim {
pub fn create_mark(
&mut self,
text: Arc<str>,
tail: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(anchors) = self.update_editor(window, cx, |_, editor, _, _| {
editor
pub fn create_mark(&mut self, text: Arc<str>, window: &mut Window, cx: &mut Context<Self>) {
self.update_editor(window, cx, |vim, editor, window, cx| {
let anchors = editor
.selections
.disjoint_anchors()
.iter()
.map(|s| if tail { s.tail() } else { s.head() })
.collect::<Vec<_>>()
}) else {
return;
};
self.marks.insert(text.to_string(), anchors);
.map(|s| s.head())
.collect::<Vec<_>>();
vim.set_mark(text.to_string(), anchors, editor.buffer(), window, cx);
});
self.clear_operator(window, cx);
}
@ -55,7 +50,7 @@ impl Vim {
let mut ends = vec![];
let mut reversed = vec![];
self.update_editor(window, cx, |_, editor, _, cx| {
self.update_editor(window, cx, |vim, editor, window, cx| {
let (map, selections) = editor.selections.all_display(cx);
for selection in selections {
let end = movement::saturating_left(&map, selection.end);
@ -69,13 +64,121 @@ impl Vim {
);
reversed.push(selection.reversed)
}
vim.set_mark("<".to_string(), starts, editor.buffer(), window, cx);
vim.set_mark(">".to_string(), ends, editor.buffer(), window, cx);
});
self.marks.insert("<".to_string(), starts);
self.marks.insert(">".to_string(), ends);
self.stored_visual_mode.replace((mode, reversed));
}
fn open_buffer_mark(
&mut self,
line: bool,
entity_id: EntityId,
anchors: Vec<Anchor>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(workspace) = self.workspace(window) else {
return;
};
workspace.update(cx, |workspace, cx| {
let item = workspace.items(cx).find(|item| {
item.act_as::<Editor>(cx)
.is_some_and(|editor| editor.read(cx).buffer().entity_id() == entity_id)
});
let Some(item) = item.cloned() else {
return;
};
if let Some(pane) = workspace.pane_for(item.as_ref()) {
pane.update(cx, |pane, cx| {
if let Some(index) = pane.index_for_item(item.as_ref()) {
pane.activate_item(index, true, true, window, cx);
}
});
};
item.act_as::<Editor>(cx).unwrap().update(cx, |editor, cx| {
let map = editor.snapshot(window, cx);
let mut ranges: Vec<Range<Anchor>> = Vec::new();
for mut anchor in anchors {
if line {
let mut point = anchor.to_display_point(&map.display_snapshot);
point = motion::first_non_whitespace(&map.display_snapshot, false, point);
anchor = map
.display_snapshot
.buffer_snapshot
.anchor_before(point.to_point(&map.display_snapshot));
}
if ranges.last() != Some(&(anchor..anchor)) {
ranges.push(anchor..anchor);
}
}
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
s.select_anchor_ranges(ranges)
});
})
});
return;
}
fn open_path_mark(
&mut self,
line: bool,
path: Arc<Path>,
points: Vec<Point>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(workspace) = self.workspace(window) else {
return;
};
let task = workspace.update(cx, |workspace, cx| {
workspace.open_abs_path(
path.to_path_buf(),
OpenOptions {
visible: Some(workspace::OpenVisible::All),
focus: Some(true),
..Default::default()
},
window,
cx,
)
});
cx.spawn_in(window, |this, mut cx| async move {
let editor = task.await?;
this.update_in(&mut cx, |_, window, cx| {
if let Some(editor) = editor.act_as::<Editor>(cx) {
editor.update(cx, |editor, cx| {
let map = editor.snapshot(window, cx);
let points: Vec<_> = points
.into_iter()
.map(|p| {
if line {
let point = p.to_display_point(&map.display_snapshot);
motion::first_non_whitespace(
&map.display_snapshot,
false,
point,
)
.to_point(&map.display_snapshot)
} else {
p
}
})
.collect();
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
s.select_ranges(points.into_iter().map(|p| p..p))
})
})
}
})
})
.detach_and_log_err(cx);
}
pub fn jump(
&mut self,
text: Arc<str>,
@ -84,25 +187,22 @@ impl Vim {
cx: &mut Context<Self>,
) {
self.pop_operator(window, cx);
let anchors = match &*text {
"{" | "}" => self.update_editor(window, cx, |_, editor, _, cx| {
let (map, selections) = editor.selections.all_display(cx);
selections
.into_iter()
.map(|selection| {
let point = if &*text == "{" {
movement::start_of_paragraph(&map, selection.head(), 1)
} else {
movement::end_of_paragraph(&map, selection.head(), 1)
};
map.buffer_snapshot
.anchor_before(point.to_offset(&map, Bias::Left))
})
.collect::<Vec<Anchor>>()
}),
"." => self.change_list.last().cloned(),
_ => self.marks.get(&*text).cloned(),
let mark = self
.update_editor(window, cx, |vim, editor, window, cx| {
vim.get_mark(&text, editor, window, cx)
})
.flatten();
let anchors = match mark {
None => None,
Some(Mark::Local(anchors)) => Some(anchors),
Some(Mark::Buffer(entity_id, anchors)) => {
self.open_buffer_mark(line, entity_id, anchors, window, cx);
return;
}
Some(Mark::Path(path, points)) => {
self.open_path_mark(line, path, points, window, cx);
return;
}
};
let Some(mut anchors) = anchors else { return };
@ -144,7 +244,7 @@ impl Vim {
}
}
if !should_jump {
if !should_jump && !ranges.is_empty() {
editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
s.select_anchor_ranges(ranges)
});
@ -158,6 +258,62 @@ impl Vim {
}
}
}
pub fn set_mark(
&mut self,
name: String,
anchors: Vec<Anchor>,
buffer_entity: &Entity<MultiBuffer>,
window: &mut Window,
cx: &mut App,
) {
let Some(workspace) = self.workspace(window) else {
return;
};
let entity_id = workspace.entity_id();
Vim::update_globals(cx, |vim_globals, cx| {
let Some(marks_state) = vim_globals.marks.get(&entity_id) else {
return;
};
marks_state.update(cx, |ms, cx| {
ms.set_mark(name.clone(), buffer_entity, anchors, cx);
});
});
}
pub fn get_mark(
&self,
name: &str,
editor: &mut Editor,
window: &mut Window,
cx: &mut App,
) -> Option<Mark> {
if matches!(name, "{" | "}" | "(" | ")") {
let (map, selections) = editor.selections.all_display(cx);
let anchors = selections
.into_iter()
.map(|selection| {
let point = match name {
"{" => movement::start_of_paragraph(&map, selection.head(), 1),
"}" => movement::end_of_paragraph(&map, selection.head(), 1),
"(" => motion::sentence_backwards(&map, selection.head(), 1),
")" => motion::sentence_forwards(&map, selection.head(), 1),
_ => unreachable!(),
};
map.buffer_snapshot
.anchor_before(point.to_offset(&map, Bias::Left))
})
.collect::<Vec<Anchor>>();
return Some(Mark::Local(anchors));
}
VimGlobals::update_global(cx, |globals, cx| {
let workspace_id = self.workspace(window)?.entity_id();
globals
.marks
.get_mut(&workspace_id)?
.update(cx, |ms, cx| ms.get_mark(name, editor.buffer(), cx))
})
}
}
pub fn jump_motion(

View file

@ -50,7 +50,7 @@ impl Vim {
.filter(|sel| sel.len() > 1 && vim.mode != Mode::VisualLine);
if !action.preserve_clipboard && vim.mode.is_visual() {
vim.copy_selections_content(editor, vim.mode == Mode::VisualLine, cx);
vim.copy_selections_content(editor, vim.mode == Mode::VisualLine, window, cx);
}
let (display_map, current_selections) = editor.selections.all_adjusted_display(cx);

View file

@ -75,7 +75,7 @@ impl Vim {
}
})
});
vim.copy_selections_content(editor, line_mode, cx);
vim.copy_selections_content(editor, line_mode, window, cx);
let selections = editor.selections.all::<Point>(cx).into_iter();
let edits = selections.map(|selection| (selection.start..selection.end, ""));
editor.edit(edits, cx);

View file

@ -36,7 +36,7 @@ impl Vim {
motion.expand_selection(map, selection, times, true, &text_layout_details);
});
});
vim.yank_selections_content(editor, motion.linewise(), cx);
vim.yank_selections_content(editor, motion.linewise(), window, cx);
editor.change_selections(None, window, cx, |s| {
s.move_with(|_, selection| {
let (head, goal) = original_positions.remove(&selection.id).unwrap();
@ -66,7 +66,7 @@ impl Vim {
start_positions.insert(selection.id, start_position);
});
});
vim.yank_selections_content(editor, false, cx);
vim.yank_selections_content(editor, false, window, cx);
editor.change_selections(None, window, cx, |s| {
s.move_with(|_, selection| {
let (head, goal) = start_positions.remove(&selection.id).unwrap();
@ -82,6 +82,7 @@ impl Vim {
&mut self,
editor: &mut Editor,
linewise: bool,
window: &mut Window,
cx: &mut Context<Editor>,
) {
self.copy_ranges(
@ -94,6 +95,7 @@ impl Vim {
.iter()
.map(|s| s.range())
.collect(),
window,
cx,
)
}
@ -102,6 +104,7 @@ impl Vim {
&mut self,
editor: &mut Editor,
linewise: bool,
window: &mut Window,
cx: &mut Context<Editor>,
) {
self.copy_ranges(
@ -114,6 +117,7 @@ impl Vim {
.iter()
.map(|s| s.range())
.collect(),
window,
cx,
)
}
@ -124,28 +128,35 @@ impl Vim {
linewise: bool,
is_yank: bool,
selections: Vec<Range<Point>>,
window: &mut Window,
cx: &mut Context<Editor>,
) {
let buffer = editor.buffer().read(cx).snapshot(cx);
let mut text = String::new();
let mut clipboard_selections = Vec::with_capacity(selections.len());
let mut ranges_to_highlight = Vec::new();
self.marks.insert(
self.set_mark(
"[".to_string(),
selections
.iter()
.map(|s| buffer.anchor_before(s.start))
.collect(),
editor.buffer(),
window,
cx,
);
self.marks.insert(
self.set_mark(
"]".to_string(),
selections
.iter()
.map(|s| buffer.anchor_after(s.end))
.collect(),
editor.buffer(),
window,
cx,
);
let mut text = String::new();
let mut clipboard_selections = Vec::with_capacity(selections.len());
let mut ranges_to_highlight = Vec::new();
{
let mut is_first = true;
for selection in selections.iter() {

View file

@ -3,27 +3,34 @@ use crate::normal::repeat::Replayer;
use crate::surrounds::SurroundsType;
use crate::{motion::Motion, object::Object};
use crate::{ToggleRegistersView, UseSystemClipboard, Vim, VimSettings};
use anyhow::Result;
use collections::HashMap;
use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
use db::define_connection;
use db::sqlez_macros::sql;
use editor::display_map::{is_invisible, replacement};
use editor::{Anchor, ClipboardSelection, Editor};
use editor::{Anchor, ClipboardSelection, Editor, MultiBuffer};
use gpui::{
Action, App, BorrowAppContext, ClipboardEntry, ClipboardItem, Entity, Global, HighlightStyle,
StyledText, Task, TextStyle, WeakEntity,
Action, App, AppContext, BorrowAppContext, ClipboardEntry, ClipboardItem, Entity, EntityId,
Global, HighlightStyle, StyledText, Subscription, Task, TextStyle, WeakEntity,
};
use language::Point;
use language::{Buffer, BufferEvent, BufferId, Point};
use picker::{Picker, PickerDelegate};
use project::{Project, ProjectItem, ProjectPath};
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsStore};
use std::borrow::BorrowMut;
use std::path::Path;
use std::{fmt::Display, ops::Range, sync::Arc};
use text::Bias;
use theme::ThemeSettings;
use ui::{
h_flex, rems, ActiveTheme, Context, Div, FluentBuilder, KeyBinding, ParentElement,
SharedString, Styled, StyledTypography, Window,
};
use util::ResultExt;
use workspace::searchable::Direction;
use workspace::Workspace;
use workspace::{Workspace, WorkspaceDb, WorkspaceId};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum Mode {
@ -179,7 +186,7 @@ impl From<String> for Register {
}
}
#[derive(Default, Clone)]
#[derive(Default)]
pub struct VimGlobals {
pub last_find: Option<Motion>,
@ -208,7 +215,399 @@ pub struct VimGlobals {
pub recordings: HashMap<char, Vec<ReplayableAction>>,
pub focused_vim: Option<WeakEntity<Vim>>,
pub marks: HashMap<EntityId, Entity<MarksState>>,
}
pub struct MarksState {
workspace: WeakEntity<Workspace>,
multibuffer_marks: HashMap<EntityId, HashMap<String, Vec<Anchor>>>,
buffer_marks: HashMap<BufferId, HashMap<String, Vec<text::Anchor>>>,
watched_buffers: HashMap<BufferId, (MarkLocation, Subscription, Subscription)>,
serialized_marks: HashMap<Arc<Path>, HashMap<String, Vec<Point>>>,
global_marks: HashMap<String, MarkLocation>,
_subscription: Subscription,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum MarkLocation {
Buffer(EntityId),
Path(Arc<Path>),
}
pub enum Mark {
Local(Vec<Anchor>),
Buffer(EntityId, Vec<Anchor>),
Path(Arc<Path>, Vec<Point>),
}
impl MarksState {
pub fn new(workspace: &Workspace, cx: &mut App) -> Entity<MarksState> {
cx.new(|cx| {
let buffer_store = workspace.project().read(cx).buffer_store().clone();
let subscription =
cx.subscribe(
&buffer_store,
move |this: &mut Self, _, event, cx| match event {
project::buffer_store::BufferStoreEvent::BufferAdded(buffer) => {
this.on_buffer_loaded(buffer, cx);
}
_ => {}
},
);
let mut this = Self {
workspace: workspace.weak_handle(),
multibuffer_marks: HashMap::default(),
buffer_marks: HashMap::default(),
watched_buffers: HashMap::default(),
serialized_marks: HashMap::default(),
global_marks: HashMap::default(),
_subscription: subscription,
};
this.load(cx);
this
})
}
fn workspace_id(&self, cx: &App) -> Option<WorkspaceId> {
self.workspace
.read_with(cx, |workspace, _| workspace.database_id())
.ok()
.flatten()
}
fn project(&self, cx: &App) -> Option<Entity<Project>> {
self.workspace
.read_with(cx, |workspace, _| workspace.project().clone())
.ok()
}
fn load(&mut self, cx: &mut Context<Self>) {
cx.spawn(|this, mut cx| async move {
let Some(workspace_id) = this.update(&mut cx, |this, cx| this.workspace_id(cx))? else {
return Ok(());
};
let (marks, paths) = cx
.background_spawn(async move {
let marks = DB.get_marks(workspace_id)?;
let paths = DB.get_global_marks_paths(workspace_id)?;
anyhow::Ok((marks, paths))
})
.await?;
this.update(&mut cx, |this, cx| this.loaded(marks, paths, cx))
})
.detach_and_log_err(cx);
}
fn loaded(
&mut self,
marks: Vec<SerializedMark>,
global_mark_paths: Vec<(String, Arc<Path>)>,
cx: &mut Context<Self>,
) {
let Some(project) = self.project(cx) else {
return;
};
for mark in marks {
self.serialized_marks
.entry(mark.path)
.or_default()
.insert(mark.name, mark.points);
}
for (name, path) in global_mark_paths {
self.global_marks
.insert(name, MarkLocation::Path(path.clone()));
let project_path = project
.read(cx)
.worktrees(cx)
.filter_map(|worktree| {
let relative = path.strip_prefix(worktree.read(cx).abs_path()).ok()?;
Some(ProjectPath {
worktree_id: worktree.read(cx).id(),
path: relative.into(),
})
})
.next();
if let Some(buffer) = project_path
.and_then(|project_path| project.read(cx).get_open_buffer(&project_path, cx))
{
self.on_buffer_loaded(&buffer, cx)
}
}
}
pub fn on_buffer_loaded(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<Self>) {
let Some(project) = self.project(cx) else {
return;
};
let Some(project_path) = buffer_handle.read(cx).project_path(cx) else {
return;
};
let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) else {
return;
};
let abs_path: Arc<Path> = abs_path.into();
let Some(serialized_marks) = self.serialized_marks.get(&abs_path) else {
return;
};
let mut loaded_marks = HashMap::default();
let buffer = buffer_handle.read(cx);
for (name, points) in serialized_marks.iter() {
loaded_marks.insert(
name.clone(),
points
.iter()
.map(|point| buffer.anchor_before(buffer.clip_point(*point, Bias::Left)))
.collect(),
);
}
self.buffer_marks.insert(buffer.remote_id(), loaded_marks);
self.watch_buffer(MarkLocation::Path(abs_path), buffer_handle, cx)
}
fn serialize_buffer_marks(
&mut self,
path: Arc<Path>,
buffer: &Entity<Buffer>,
cx: &mut Context<Self>,
) {
let new_points: HashMap<String, Vec<Point>> =
if let Some(anchors) = self.buffer_marks.get(&buffer.read(cx).remote_id()) {
anchors
.iter()
.map(|(name, anchors)| {
(
name.clone(),
buffer
.read(cx)
.summaries_for_anchors::<Point, _>(anchors)
.collect(),
)
})
.collect()
} else {
HashMap::default()
};
let old_points = self.serialized_marks.get(&path.clone());
if old_points == Some(&new_points) {
return;
}
let mut to_write = HashMap::default();
for (key, value) in &new_points {
if self.is_global_mark(key) {
if self.global_marks.get(key) != Some(&MarkLocation::Path(path.clone())) {
if let Some(workspace_id) = self.workspace_id(cx) {
let path = path.clone();
let key = key.clone();
cx.background_spawn(async move {
DB.set_global_mark_path(workspace_id, key, path).await
})
.detach_and_log_err(cx);
}
self.global_marks
.insert(key.clone(), MarkLocation::Path(path.clone()));
}
}
if old_points.and_then(|o| o.get(key)) != Some(value) {
to_write.insert(key.clone(), value.clone());
}
}
self.serialized_marks.insert(path.clone(), new_points);
if let Some(workspace_id) = self.workspace_id(cx) {
cx.background_spawn(async move {
DB.set_marks(workspace_id, path.clone(), to_write).await?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
}
fn is_global_mark(&self, key: &str) -> bool {
key.chars()
.next()
.is_some_and(|c| c.is_uppercase() || c.is_digit(10))
}
fn rename_buffer(
&mut self,
old_path: MarkLocation,
new_path: Arc<Path>,
buffer: &Entity<Buffer>,
cx: &mut Context<Self>,
) {
if let MarkLocation::Buffer(entity_id) = old_path {
if let Some(old_marks) = self.multibuffer_marks.remove(&entity_id) {
let buffer_marks = old_marks
.into_iter()
.map(|(k, v)| (k, v.into_iter().map(|anchor| anchor.text_anchor).collect()))
.collect();
self.buffer_marks
.insert(buffer.read(cx).remote_id(), buffer_marks);
}
}
self.watch_buffer(MarkLocation::Path(new_path.clone()), buffer, cx);
self.serialize_buffer_marks(new_path, buffer, cx);
}
fn path_for_buffer(&self, buffer: &Entity<Buffer>, cx: &App) -> Option<Arc<Path>> {
let project_path = buffer.read(cx).project_path(cx)?;
let project = self.project(cx)?;
let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
Some(abs_path.into())
}
fn points_at(
&self,
location: &MarkLocation,
multi_buffer: &Entity<MultiBuffer>,
cx: &App,
) -> bool {
match location {
MarkLocation::Buffer(entity_id) => entity_id == &multi_buffer.entity_id(),
MarkLocation::Path(path) => {
let Some(singleton) = multi_buffer.read(cx).as_singleton() else {
return false;
};
self.path_for_buffer(&singleton, cx).as_ref() == Some(path)
}
}
}
pub fn watch_buffer(
&mut self,
mark_location: MarkLocation,
buffer_handle: &Entity<Buffer>,
cx: &mut Context<Self>,
) {
let on_change = cx.subscribe(buffer_handle, move |this, buffer, event, cx| match event {
BufferEvent::Edited => {
if let Some(path) = this.path_for_buffer(&buffer, cx) {
this.serialize_buffer_marks(path, &buffer, cx);
}
}
BufferEvent::FileHandleChanged => {
let buffer_id = buffer.read(cx).remote_id();
if let Some(old_path) = this
.watched_buffers
.get(&buffer_id.clone())
.map(|(path, _, _)| path.clone())
{
if let Some(new_path) = this.path_for_buffer(&buffer, cx) {
this.rename_buffer(old_path, new_path, &buffer, cx)
}
}
}
_ => {}
});
let on_release = cx.observe_release(buffer_handle, |this, buffer, _| {
this.watched_buffers.remove(&buffer.remote_id());
this.buffer_marks.remove(&buffer.remote_id());
});
self.watched_buffers.insert(
buffer_handle.read(cx).remote_id(),
(mark_location, on_change, on_release),
);
}
pub fn set_mark(
&mut self,
name: String,
multibuffer: &Entity<MultiBuffer>,
anchors: Vec<Anchor>,
cx: &mut Context<Self>,
) {
let buffer = multibuffer.read(cx).as_singleton();
let abs_path = buffer.as_ref().and_then(|b| self.path_for_buffer(&b, cx));
let Some(abs_path) = abs_path else {
self.multibuffer_marks
.entry(multibuffer.entity_id())
.or_default()
.insert(name.clone(), anchors);
if self.is_global_mark(&name) {
self.global_marks
.insert(name.clone(), MarkLocation::Buffer(multibuffer.entity_id()));
}
if let Some(buffer) = buffer {
let buffer_id = buffer.read(cx).remote_id();
if !self.watched_buffers.contains_key(&buffer_id) {
self.watch_buffer(MarkLocation::Buffer(multibuffer.entity_id()), &buffer, cx)
}
}
return;
};
let buffer = buffer.unwrap();
let buffer_id = buffer.read(cx).remote_id();
self.buffer_marks.entry(buffer_id).or_default().insert(
name.clone(),
anchors
.into_iter()
.map(|anchor| anchor.text_anchor)
.collect(),
);
if !self.watched_buffers.contains_key(&buffer_id) {
self.watch_buffer(MarkLocation::Path(abs_path.clone()), &buffer, cx)
}
self.serialize_buffer_marks(abs_path, &buffer, cx)
}
pub fn get_mark(
&self,
name: &str,
multi_buffer: &Entity<MultiBuffer>,
cx: &App,
) -> Option<Mark> {
let target = self.global_marks.get(name);
if !self.is_global_mark(name) || target.is_some_and(|t| self.points_at(t, multi_buffer, cx))
{
if let Some(anchors) = self.multibuffer_marks.get(&multi_buffer.entity_id()) {
return Some(Mark::Local(anchors.get(name)?.clone()));
}
let singleton = multi_buffer.read(cx).as_singleton()?;
let excerpt_id = *multi_buffer.read(cx).excerpt_ids().first().unwrap();
let buffer_id = singleton.read(cx).remote_id();
if let Some(anchors) = self.buffer_marks.get(&buffer_id) {
let text_anchors = anchors.get(name)?;
let anchors = text_anchors
.into_iter()
.map(|anchor| Anchor::in_buffer(excerpt_id, buffer_id, *anchor))
.collect();
return Some(Mark::Local(anchors));
}
}
match target? {
MarkLocation::Buffer(entity_id) => {
let anchors = self.multibuffer_marks.get(&entity_id)?;
return Some(Mark::Buffer(*entity_id, anchors.get(name)?.clone()));
}
MarkLocation::Path(path) => {
let points = self.serialized_marks.get(path)?;
return Some(Mark::Path(path.clone(), points.get(name)?.clone()));
}
}
}
}
impl Global for VimGlobals {}
impl VimGlobals {
@ -228,8 +627,15 @@ impl VimGlobals {
})
.detach();
let mut was_enabled = None;
cx.observe_global::<SettingsStore>(move |cx| {
if Vim::enabled(cx) {
let is_enabled = Vim::enabled(cx);
if was_enabled == Some(is_enabled) {
return;
}
was_enabled = Some(is_enabled);
if is_enabled {
KeyBinding::set_vim_mode(cx, true);
CommandPaletteFilter::update_global(cx, |filter, _| {
filter.show_namespace(Vim::NAMESPACE);
@ -237,6 +643,17 @@ impl VimGlobals {
CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
interceptor.set(Box::new(command_interceptor));
});
for window in cx.windows() {
if let Some(workspace) = window.downcast::<Workspace>() {
workspace
.update(cx, |workspace, _, cx| {
Vim::update_globals(cx, |globals, cx| {
globals.register_workspace(workspace, cx)
});
})
.ok();
}
}
} else {
KeyBinding::set_vim_mode(cx, false);
*Vim::globals(cx) = VimGlobals::default();
@ -249,6 +666,21 @@ impl VimGlobals {
}
})
.detach();
cx.observe_new(|workspace: &mut Workspace, _, cx| {
Vim::update_globals(cx, |globals, cx| globals.register_workspace(workspace, cx));
})
.detach()
}
fn register_workspace(&mut self, workspace: &Workspace, cx: &mut Context<Workspace>) {
let entity_id = cx.entity_id();
self.marks.insert(entity_id, MarksState::new(workspace, cx));
cx.observe_release(&cx.entity(), move |_, _, cx| {
Vim::update_globals(cx, |globals, _| {
globals.marks.remove(&entity_id);
})
})
.detach();
}
pub(crate) fn write_registers(
@ -799,3 +1231,111 @@ impl RegistersView {
.modal(true)
}
}
define_connection! (
pub static ref DB: VimDb<WorkspaceDb> = &[
sql! (
CREATE TABLE vim_marks (
workspace_id INTEGER,
mark_name TEXT,
path BLOB,
value TEXT
);
CREATE UNIQUE INDEX idx_vim_marks ON vim_marks (workspace_id, mark_name, path);
),
sql! (
CREATE TABLE vim_global_marks_paths(
workspace_id INTEGER,
mark_name TEXT,
path BLOB
);
CREATE UNIQUE INDEX idx_vim_global_marks_paths
ON vim_global_marks_paths(workspace_id, mark_name);
),
];
);
struct SerializedMark {
path: Arc<Path>,
name: String,
points: Vec<Point>,
}
impl VimDb {
pub(crate) async fn set_marks(
&self,
workspace_id: WorkspaceId,
path: Arc<Path>,
marks: HashMap<String, Vec<Point>>,
) -> Result<()> {
let result = self
.write(move |conn| {
let mut query = conn.exec_bound(sql!(
INSERT OR REPLACE INTO vim_marks
(workspace_id, mark_name, path, value)
VALUES
(?, ?, ?, ?)
))?;
for (mark_name, value) in marks {
let pairs: Vec<(u32, u32)> = value
.into_iter()
.map(|point| (point.row, point.column))
.collect();
let serialized = serde_json::to_string(&pairs)?;
query((workspace_id, mark_name, path.clone(), serialized))?;
}
Ok(())
})
.await;
result
}
fn get_marks(&self, workspace_id: WorkspaceId) -> Result<Vec<SerializedMark>> {
let result: Vec<(Arc<Path>, String, String)> = self.select_bound(sql!(
SELECT path, mark_name, value FROM vim_marks
WHERE workspace_id = ?
))?(workspace_id)?;
Ok(result
.into_iter()
.filter_map(|(path, name, value)| {
let pairs: Vec<(u32, u32)> = serde_json::from_str(&value).log_err()?;
Some(SerializedMark {
path,
name,
points: pairs
.into_iter()
.map(|(row, column)| Point { row, column })
.collect(),
})
})
.collect())
}
pub(crate) async fn set_global_mark_path(
&self,
workspace_id: WorkspaceId,
mark_name: String,
path: Arc<Path>,
) -> Result<()> {
self.write(move |conn| {
conn.exec_bound(sql!(
INSERT OR REPLACE INTO vim_global_marks_paths
(workspace_id, mark_name, path)
VALUES
(?, ?, ?)
))?((workspace_id, mark_name, path))
})
.await
}
pub fn get_global_marks_paths(
&self,
workspace_id: WorkspaceId,
) -> Result<Vec<(String, Arc<Path>)>> {
self.select_bound(sql!(
SELECT mark_name, path FROM vim_global_marks_paths
WHERE workspace_id = ?
))?(workspace_id)
}
}

View file

@ -26,7 +26,7 @@ use editor::{
Anchor, Bias, Editor, EditorEvent, EditorMode, EditorSettings, ToPoint,
};
use gpui::{
actions, impl_actions, Action, App, AppContext as _, Axis, Context, Entity, EventEmitter,
actions, impl_actions, Action, App, AppContext, Axis, Context, Entity, EventEmitter,
KeyContext, KeystrokeEvent, Render, Subscription, Task, WeakEntity, Window,
};
use insert::{NormalBefore, TemporaryNormal};
@ -314,7 +314,6 @@ pub(crate) struct Vim {
operator_stack: Vec<Operator>,
pub(crate) replacements: Vec<(Range<editor::Anchor>, String)>,
pub(crate) marks: HashMap<String, Vec<Anchor>>,
pub(crate) stored_visual_mode: Option<(Mode, Vec<bool>)>,
pub(crate) change_list: Vec<Vec<Anchor>>,
pub(crate) change_list_position: Option<usize>,
@ -362,7 +361,6 @@ impl Vim {
operator_stack: Vec::new(),
replacements: Vec::new(),
marks: HashMap::default(),
stored_visual_mode: None,
change_list: Vec::new(),
change_list_position: None,
@ -1573,7 +1571,7 @@ impl Vim {
}
_ => self.clear_operator(window, cx),
},
Some(Operator::Mark) => self.create_mark(text, false, window, cx),
Some(Operator::Mark) => self.create_mark(text, window, cx),
Some(Operator::RecordRegister) => {
self.record_register(text.chars().next().unwrap(), window, cx)
}

View file

@ -17,7 +17,7 @@ use workspace::searchable::Direction;
use crate::{
motion::{first_non_whitespace, next_line_end, start_of_line, Motion},
object::Object,
state::{Mode, Operator},
state::{Mark, Mode, Operator},
Vim,
};
@ -107,14 +107,20 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
let Some((stored_mode, reversed)) = vim.stored_visual_mode.take() else {
return;
};
let Some((start, end)) = vim.marks.get("<").zip(vim.marks.get(">")) else {
let marks = vim
.update_editor(window, cx, |vim, editor, window, cx| {
vim.get_mark("<", editor, window, cx)
.zip(vim.get_mark(">", editor, window, cx))
})
.flatten();
let Some((Mark::Local(start), Mark::Local(end))) = marks else {
return;
};
let ranges = start
.iter()
.zip(end)
.zip(reversed)
.map(|((start, end), reversed)| (*start, *end, reversed))
.map(|((start, end), reversed)| (*start, end, reversed))
.collect::<Vec<_>>();
if vim.mode.is_visual() {
@ -499,7 +505,7 @@ impl Vim {
selection.goal = SelectionGoal::None;
});
});
vim.copy_selections_content(editor, line_mode, cx);
vim.copy_selections_content(editor, line_mode, window, cx);
editor.insert("", window, cx);
// Fixup cursor position after the deletion
@ -528,7 +534,7 @@ impl Vim {
self.update_editor(window, cx, |vim, editor, window, cx| {
let line_mode = line_mode || editor.selections.line_mode;
editor.selections.line_mode = line_mode;
vim.yank_selections_content(editor, line_mode, cx);
vim.yank_selections_content(editor, line_mode, window, cx);
editor.change_selections(None, window, cx, |s| {
s.move_with(|map, selection| {
if line_mode {