Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
editor: Fix panic when restoring empty selections on undo/redo (#59372)
Neel969c6c719ca1
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex dbc177e7a93..36b5209a5c0 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -1387,11 +1387,15 @@ struct DeferredSelectionEffectsState {history_entry: SelectionHistoryEntry,}+#[derive(Clone, Debug)]+pub struct TransactionSelections {+ pub undo: Arc<[Selection<Anchor>]>,+ pub redo: Option<Arc<[Selection<Anchor>]>>,+}+#[derive(Default)]struct SelectionHistory {- #[allow(clippy::type_complexity)]- selections_by_transaction:- HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,+ selections_by_transaction: HashMap<TransactionId, TransactionSelections>,mode: SelectionHistoryMode,undo_stack: VecDeque<SelectionHistoryEntry>,redo_stack: VecDeque<SelectionHistoryEntry>,@@ -1411,23 +1415,23 @@ impl SelectionHistory {);return;}- self.selections_by_transaction- .insert(transaction_id, (selections, None));+ self.selections_by_transaction.insert(+ transaction_id,+ TransactionSelections {+ undo: selections,+ redo: None,+ },+ );}- #[allow(clippy::type_complexity)]- fn transaction(- &self,- transaction_id: TransactionId,- ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {+ fn transaction(&self, transaction_id: TransactionId) -> Option<&TransactionSelections> {self.selections_by_transaction.get(&transaction_id)}- #[allow(clippy::type_complexity)]fn transaction_mut(&mut self,transaction_id: TransactionId,- ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {+ ) -> Option<&mut TransactionSelections> {self.selections_by_transaction.get_mut(&transaction_id)}@@ -7495,26 +7499,31 @@ impl Editor {});}+ fn restore_selections(+ &mut self,+ selections: Option<Arc<[Selection<Anchor>]>>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if let Some(selections) = selections.filter(|selections| !selections.is_empty()) {+ self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {+ s.select_anchors(selections.to_vec());+ });+ }+ }+pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {if self.read_only(cx) {return;}if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {- if let Some((selections, _)) =- self.selection_history.transaction(transaction_id).cloned()- {- self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {- s.select_anchors(selections.to_vec());- });- } else {- log::error!(- "No entry in selection_history found for undo. \- This may correspond to a bug where undo does not update the selection. \- If this is occurring, please add details to \- https://github.com/zed-industries/zed/issues/22692"- );+ let transaction = self.selection_history.transaction(transaction_id);+ if transaction.is_none() {+ log::error!("No selection history for undone transaction; selection unchanged");}+ let selections = transaction.map(|transaction| transaction.undo.clone());+ self.restore_selections(selections, window, cx);self.request_autoscroll(Autoscroll::fit(), cx);self.unmark_text(window, cx);self.refresh_edit_prediction(@@ -7535,20 +7544,11 @@ impl Editor {}if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {- if let Some((_, Some(selections))) =- self.selection_history.transaction(transaction_id).cloned()- {- self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {- s.select_anchors(selections.to_vec());- });- } else {- log::error!(- "No entry in selection_history found for redo. \- This may correspond to a bug where undo does not update the selection. \- If this is occurring, please add details to \- https://github.com/zed-industries/zed/issues/22692"- );- }+ let selections = self+ .selection_history+ .transaction(transaction_id)+ .and_then(|transaction| transaction.redo.clone());+ self.restore_selections(selections, window, cx);self.request_autoscroll(Autoscroll::fit(), cx);self.unmark_text(window, cx);self.refresh_edit_prediction(@@ -8061,7 +8061,7 @@ impl Editor {// will take you back to where you made the last edit, instead of staying where you scrolledself.selection_history.transaction(transaction_id_prev)- .map(|t| t.0.clone())+ .map(|t| t.undo.clone())}).unwrap_or_else(|| self.selections.disjoint_anchors_arc());@@ -8287,10 +8287,8 @@ impl Editor {.buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx)){- if let Some((_, end_selections)) =- self.selection_history.transaction_mut(transaction_id)- {- *end_selections = Some(self.selections.disjoint_anchors_arc());+ if let Some(transaction) = self.selection_history.transaction_mut(transaction_id) {+ transaction.redo = Some(self.selections.disjoint_anchors_arc());} else {log::error!("unexpectedly ended a transaction that wasn't started by this editor");}@@ -8305,7 +8303,7 @@ impl Editor {pub fn modify_transaction_selection_history(&mut self,transaction_id: TransactionId,- modify: impl FnOnce(&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)),+ modify: impl FnOnce(&mut TransactionSelections),) -> bool {self.selection_history.transaction_mut(transaction_id)diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rsindex 145ceaa6943..4acdae8d281 100644--- a/crates/editor/src/editor_tests.rs+++ b/crates/editor/src/editor_tests.rs@@ -323,6 +323,39 @@ fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {});}+#[gpui::test]+fn test_undo_redo_with_empty_history_selections_does_not_panic(cx: &mut TestAppContext) {+ init_test(cx, |_| {});++ let now = Instant::now();+ let buffer = cx.new(|cx| language::Buffer::local("123456", cx));+ let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));+ let editor = cx.add_window(|window, cx| build_editor(buffer, window, cx));++ _ = editor.update(cx, |editor, window, cx| {+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {+ s.select_ranges([MultiBufferOffset(0)..MultiBufferOffset(0)])+ });+ editor.start_transaction_at(now, window, cx);+ editor.insert("a", window, cx);+ let transaction_id = editor+ .end_transaction_at(now, cx)+ .expect("transaction should be created");+ assert_eq!(editor.text(cx), "a123456");++ editor.modify_transaction_selection_history(transaction_id, |selections| {+ selections.undo = Vec::new().into();+ selections.redo = Some(Vec::new().into());+ });++ editor.undo(&Undo, window, cx);+ assert_eq!(editor.text(cx), "123456");++ editor.redo(&Redo, window, cx);+ assert_eq!(editor.text(cx), "a123456");+ });+}+#[gpui::test]fn test_accessibility_keyboard_word_completion(cx: &mut TestAppContext) {init_test(cx, |_| {});diff --git a/crates/vim/src/command.rs b/crates/vim/src/command.rsindex 274fabac9a7..df6a911329b 100644--- a/crates/vim/src/command.rs+++ b/crates/vim/src/command.rs@@ -835,8 +835,8 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {{let last_sel = editor.selections.disjoint_anchors_arc();editor.modify_transaction_selection_history(tx_id, |old| {- old.0 = old.0.get(..1).unwrap_or(&[]).into();- old.1 = Some(last_sel);+ old.undo = old.undo.get(..1).unwrap_or(&[]).into();+ old.redo = Some(last_sel);});}});diff --git a/crates/vim/src/normal.rs b/crates/vim/src/normal.rsindex d91af01a542..389eeb88e61 100644--- a/crates/vim/src/normal.rs+++ b/crates/vim/src/normal.rs@@ -160,10 +160,11 @@ pub(crate) fn register(editor: &mut Editor, cx: &mut Context<Vim>) {let transaction_id = vim.visual_delete(false, window, cx);if let (Some(original_selections), Some(transaction_id)) =(original_selections, transaction_id)+ && !original_selections.is_empty(){let updated = vim.update_editor(cx, |_, editor, _| {editor.modify_transaction_selection_history(transaction_id, |selections| {- selections.0 = original_selections;+ selections.undo = original_selections;})});debug_assert_ne!(updated, Some(false));