@@ -232,15 +232,29 @@ impl Editor {
233 match action {
233 match action {
234 Action::Replace => {
234 Action::Replace => {
235− let view = view!(self);
235+ let (view, doc) = current_ref!(self);
236− let jump = (
236+ // If the current view is an empty scratch buffer and is not displayed in any other views, delete it.
237− view.doc,
237+ // Boolean value is determined before the call to `view_mut` because the operation requires a borrow
238− self.documents[view.doc].selection(view.id).clone(),
238+ // of `self.tree`, which is mutably borrowed when `view_mut` is called.
239− );
239+ let remove_empty_scratch = !doc.is_modified()
240−
240+ // If the buffer has no path and is not modified, it is an empty scratch buffer.
241+ && doc.path().is_none()
242+ // Ensure the buffer is not displayed in any other splits.
246+ .any(|(_, v)| v.doc == doc.id && v.id != view.id);
241 let view = view_mut!(self);
247 let view = view_mut!(self);
248+ if remove_empty_scratch {
249+ // Copy `doc.id` into a variable before calling `self.documents.remove`, which requires a mutable
250+ // borrow, invalidating direct access to `doc.id`.
252+ self.documents.remove(id);
254+ let jump = (view.doc, doc.selection(view.id).clone());
242− view.jumps.push(jump);
255+ view.jumps.push(jump);
243− view.last_accessed_doc = Some(view.doc);
256+ view.last_accessed_doc = Some(view.doc);
244 view.doc = id;
258 view.doc = id;
245 view.offset = Position::default();
259 view.offset = Position::default();