Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Persist selections for editors (#25083)
Kirill Bulatov80458ffb9605
diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rsindex 7b6181310f6..5f86b468439 100644--- a/crates/editor/src/display_map.rs+++ b/crates/editor/src/display_map.rs@@ -2778,6 +2778,7 @@ pub mod tests {fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {let settings = SettingsStore::test(cx);cx.set_global(settings);+ workspace::init_settings(cx);language::init(cx);crate::init(cx);Project::init_settings(cx);diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex e17236a71da..50f54849625 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -106,6 +106,7 @@ use language::{use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};use linked_editing_ranges::refresh_linked_ranges;use mouse_context_menu::MouseContextMenu;+use persistence::DB;pub use proposed_changes_editor::{ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,};@@ -171,8 +172,14 @@ use ui::{Tooltip,};use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};-use workspace::item::{ItemHandle, PreviewTabsSettings};-use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};+use workspace::{+ item::{ItemHandle, PreviewTabsSettings},+ ItemId, RestoreOnStartupBehavior,+};+use workspace::{+ notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},+ WorkspaceSettings,+};use workspace::{searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,};@@ -763,6 +770,7 @@ pub struct Editor {selection_mark_mode: bool,toggle_fold_multiple_buffers: Task<()>,_scroll_cursor_center_top_bottom_task: Task<()>,+ serialize_selections: Task<()>,}#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]@@ -1475,6 +1483,7 @@ impl Editor {_scroll_cursor_center_top_bottom_task: Task::ready(()),selection_mark_mode: false,toggle_fold_multiple_buffers: Task::ready(()),+ serialize_selections: Task::ready(()),text_style_refinement: None,load_diff_task: load_uncommitted_diff,};@@ -2181,9 +2190,37 @@ impl Editor {self.blink_manager.update(cx, BlinkManager::pause_blinking);cx.emit(EditorEvent::SelectionsChanged { local });- if self.selections.disjoint_anchors().len() == 1 {+ let selections = &self.selections.disjoint;+ if selections.len() == 1 {cx.emit(SearchEvent::ActiveMatchChanged)}+ if local+ && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None+ {+ if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {+ let background_executor = cx.background_executor().clone();+ let editor_id = cx.entity().entity_id().as_u64() as ItemId;+ let snapshot = self.buffer().read(cx).snapshot(cx);+ let selections = selections.clone();+ self.serialize_selections = cx.background_spawn(async move {+ background_executor.timer(Duration::from_millis(100)).await;+ let selections = selections+ .iter()+ .map(|selection| {+ (+ selection.start.to_offset(&snapshot),+ selection.end.to_offset(&snapshot),+ )+ })+ .collect();+ DB.save_editor_selections(editor_id, workspace_id, selections)+ .await+ .context("persisting editor selections")+ .log_err();+ });+ }+ }+cx.notify();}@@ -2197,7 +2234,7 @@ impl Editor {self.change_selections_inner(autoscroll, true, window, cx, change)}- pub fn change_selections_inner<R>(+ fn change_selections_inner<R>(&mut self,autoscroll: Option<Autoscroll>,request_completions: bool,@@ -14982,6 +15019,31 @@ impl Editor {pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {self.load_diff_task.clone()}++ fn read_selections_from_db(+ &mut self,+ item_id: u64,+ workspace_id: WorkspaceId,+ window: &mut Window,+ cx: &mut Context<Editor>,+ ) {+ if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {+ return;+ }+ let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {+ return;+ };+ if selections.is_empty() {+ return;+ }++ let snapshot = self.buffer.read(cx).snapshot(cx);+ self.change_selections(None, window, cx, |s| {+ s.select_ranges(selections.into_iter().map(|(start, end)| {+ snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)+ }));+ });+ }}fn get_uncommitted_diff_for_buffer(diff --git a/crates/editor/src/items.rs b/crates/editor/src/items.rsindex 8a15bbb10cc..7f40092f0b7 100644--- a/crates/editor/src/items.rs+++ b/crates/editor/src/items.rs@@ -1079,6 +1079,7 @@ impl SerializableItem for Editor {cx.new(|cx| {let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);+ editor.read_selections_from_db(item_id, workspace_id, window, cx);editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);editor})@@ -1134,6 +1135,12 @@ impl SerializableItem for Editor {let mut editor =Editor::for_buffer(buffer, Some(project), window, cx);+ editor.read_selections_from_db(+ item_id,+ workspace_id,+ window,+ cx,+ );editor.read_scroll_position_from_db(item_id,workspace_id,@@ -1152,6 +1159,7 @@ impl SerializableItem for Editor {window.spawn(cx, |mut cx| async move {let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;editor.update_in(&mut cx, |editor, window, cx| {+ editor.read_selections_from_db(item_id, workspace_id, window, cx);editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);})?;Ok(editor)diff --git a/crates/editor/src/movement.rs b/crates/editor/src/movement.rsindex 556c15cc9b1..d070feb262d 100644--- a/crates/editor/src/movement.rs+++ b/crates/editor/src/movement.rs@@ -1184,6 +1184,7 @@ mod tests {fn init_test(cx: &mut gpui::App) {let settings_store = SettingsStore::test(cx);cx.set_global(settings_store);+ workspace::init_settings(cx);theme::init(theme::LoadThemes::JustBase, cx);language::init(cx);crate::init(cx);diff --git a/crates/editor/src/persistence.rs b/crates/editor/src/persistence.rsindex 48955124175..e8d2ed05d43 100644--- a/crates/editor/src/persistence.rs+++ b/crates/editor/src/persistence.rs@@ -2,6 +2,7 @@ use anyhow::Result;use db::sqlez::bindable::{Bind, Column, StaticColumnCount};use db::sqlez::statement::Statement;use fs::MTime;+use itertools::Itertools as _;use std::path::PathBuf;use db::sqlez_macros::sql;@@ -134,9 +135,26 @@ define_connection!(ALTER TABLE editors ADD COLUMN mtime_seconds INTEGER DEFAULT NULL;ALTER TABLE editors ADD COLUMN mtime_nanos INTEGER DEFAULT NULL;),+ sql! (+ CREATE TABLE editor_selections (+ item_id INTEGER NOT NULL,+ editor_id INTEGER NOT NULL,+ workspace_id INTEGER NOT NULL,+ start INTEGER NOT NULL,+ end INTEGER NOT NULL,+ PRIMARY KEY(item_id),+ FOREIGN KEY(editor_id, workspace_id) REFERENCES editors(item_id, workspace_id)+ ON DELETE CASCADE+ ) STRICT;+ ),];);+// https://www.sqlite.org/limits.html+// > <..> the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER,+// > which defaults to <..> 32766 for SQLite versions after 3.32.0.+const MAX_QUERY_PLACEHOLDERS: usize = 32000;+impl EditorDb {query! {pub fn get_serialized_editor(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<SerializedEditor>> {@@ -188,6 +206,68 @@ impl EditorDb {}}+ query! {+ pub fn get_editor_selections(+ editor_id: ItemId,+ workspace_id: WorkspaceId+ ) -> Result<Vec<(usize, usize)>> {+ SELECT start, end+ FROM editor_selections+ WHERE editor_id = ?1 AND workspace_id = ?2+ }+ }++ pub async fn save_editor_selections(+ &self,+ editor_id: ItemId,+ workspace_id: WorkspaceId,+ selections: Vec<(usize, usize)>,+ ) -> Result<()> {+ let mut first_selection;+ let mut last_selection = 0_usize;+ for (count, placeholders) in std::iter::once("(?1, ?2, ?, ?)")+ .cycle()+ .take(selections.len())+ .chunks(MAX_QUERY_PLACEHOLDERS / 4)+ .into_iter()+ .map(|chunk| {+ let mut count = 0;+ let placeholders = chunk+ .inspect(|_| {+ count += 1;+ })+ .join(", ");+ (count, placeholders)+ })+ .collect::<Vec<_>>()+ {+ first_selection = last_selection;+ last_selection = last_selection + count;+ let query = format!(+ r#"+DELETE FROM editor_selections WHERE editor_id = ?1 AND workspace_id = ?2;++INSERT INTO editor_selections (editor_id, workspace_id, start, end)+VALUES {placeholders};+"#+ );++ let selections = selections[first_selection..last_selection].to_vec();+ self.write(move |conn| {+ let mut statement = Statement::prepare(conn, query)?;+ statement.bind(&editor_id, 1)?;+ let mut next_index = statement.bind(&workspace_id, 2)?;+ for (start, end) in selections {+ next_index = statement.bind(&start, next_index)?;+ next_index = statement.bind(&end, next_index)?;+ }+ statement.exec()+ })+ .await?;+ }+ Ok(())+ }+pub async fn delete_unloaded_items(&self,workspace: WorkspaceId,diff --git a/crates/language_tools/src/lsp_log_tests.rs b/crates/language_tools/src/lsp_log_tests.rsindex 5d318d0afad..707d2ca0221 100644--- a/crates/language_tools/src/lsp_log_tests.rs+++ b/crates/language_tools/src/lsp_log_tests.rs@@ -109,6 +109,7 @@ fn init_test(cx: &mut gpui::TestAppContext) {cx.update(|cx| {let settings_store = SettingsStore::test(cx);cx.set_global(settings_store);+ workspace::init_settings(cx);theme::init(theme::LoadThemes::JustBase, cx);release_channel::init(SemanticVersion::default(), cx);language::init(cx);diff --git a/crates/search/src/buffer_search.rs b/crates/search/src/buffer_search.rsindex 5cc644e2534..3a9a48e0856 100644--- a/crates/search/src/buffer_search.rs+++ b/crates/search/src/buffer_search.rs@@ -1511,6 +1511,7 @@ mod tests {cx.update(|cx| {let store = settings::SettingsStore::test(cx);cx.set_global(store);+ workspace::init_settings(cx);editor::init(cx);language::init(cx);diff --git a/crates/workspace/src/workspace_settings.rs b/crates/workspace/src/workspace_settings.rsindex f6d3a176d68..575b4ac2616 100644--- a/crates/workspace/src/workspace_settings.rs+++ b/crates/workspace/src/workspace_settings.rs@@ -71,7 +71,7 @@ impl CloseWindowWhenNoItems {}}-#[derive(Copy, Clone, Default, Serialize, Deserialize, JsonSchema)]+#[derive(Copy, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum RestoreOnStartupBehavior {/// Always start with an empty editor