Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Fix on-type formatting using a stale position when autoindent is pending (#65769)

Jacob Wolfd27ad54dd617
diff --git a/crates/editor/src/completions.rs b/crates/editor/src/completions.rs
index c4dec369732..afffe818b01 100644
--- a/crates/editor/src/completions.rs
+++ b/crates/editor/src/completions.rs
@@ -230,16 +230,27 @@ impl Editor {
// Cursors are right-biased, so an edit inserting text at one drags it along. Pin a
// left-biased copy, keyed by the current anchor so cursors the user moves are skipped.
- let snapshot = self.buffer.read(cx).snapshot(cx);
- let cursors_to_pin = self
+ let cursor_heads = self
.selections
.disjoint_anchors()
.iter()
.filter(|selection| selection.start == selection.end)
- .map(|selection| (selection.head(), snapshot.anchor_before(selection.head())))
- .collect::<HashMap<_, _>>();
+ .map(|selection| selection.head())
+ .collect::<Vec<_>>();
Some(cx.spawn_in(window, async move |editor, cx| {
+ if let Some(waiter) =
+ buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())
+ {
+ waiter.await?;
+ }
+ let cursors_to_pin = editor.update(cx, |editor, cx| {
+ let snapshot = editor.buffer.read(cx).snapshot(cx);
+ cursor_heads
+ .into_iter()
+ .map(|head| (head, snapshot.anchor_before(head)))
+ .collect::<HashMap<_, _>>()
+ })?;
if let Some(transaction) = on_type_formatting.await? {
let (formatted_buffer_id, formatted_ranges) = buffer.update(cx, |buffer, _| {
let formatted_ranges = buffer
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs
index f04c9234379..8e937198187 100644
--- a/crates/editor/src/editor_tests.rs
+++ b/crates/editor/src/editor_tests.rs
@@ -28774,6 +28774,47 @@ async fn test_on_type_formatting_is_applied_after_autoindent(cx: &mut TestAppCon
assert!(request.next().await.is_none());
}
+#[gpui::test]
+async fn test_on_type_formatting_position_stays_after_trigger_while_autoindent_is_pending(
+ cx: &mut TestAppContext,
+) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
+ first_trigger_character: "=".to_string(),
+ more_trigger_character: None,
+ }),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state("fn f() {\n let n ˇ1\n}\n");
+ cx.update_buffer(|buffer, _| buffer.set_sync_parse_timeout(None));
+
+ let mut request =
+ cx.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(|_, params, _| async move {
+ assert_eq!(params.ch, "=");
+ assert_eq!(
+ params.text_document_position.position,
+ lsp::Position::new(1, 11)
+ );
+ Ok(Some(vec![]))
+ });
+
+ cx.update_editor(|editor, window, cx| {
+ editor.handle_input("=", window, cx);
+ editor.handle_input("2", window, cx);
+ });
+ cx.run_until_parked();
+
+ cx.assert_editor_state("fn f() {\n let n =2ˇ1\n}\n");
+ assert!(request.next().await.is_some());
+}
+
#[gpui::test]
async fn test_on_type_formatting_not_scheduled_without_server_support(cx: &mut TestAppContext) {
init_test(cx, |_| {});
@@ -28869,6 +28910,230 @@ async fn test_on_type_formatting_does_not_rewind_over_intervening_edits(cx: &mut
cx.assert_editor_state("let a = b.cxˇ;\n");
}
+#[gpui::test]
+async fn test_on_type_formatting_after_newline_uses_autoindented_position(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ for async_autoindent in [false, true] {
+ let mut cx = EditorLspTestContext::new_typescript(
+ lsp::ServerCapabilities {
+ document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
+ first_trigger_character: "\n".to_string(),
+ more_trigger_character: None,
+ }),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state("function foo() {ˇ}\n");
+ if async_autoindent {
+ cx.update_buffer(|buffer, _| buffer.set_sync_parse_timeout(None));
+ }
+
+ // Mirrors Ruby LSP closing a block: a newline and the closing keyword inserted at the cursor.
+ let mut request = cx.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
+ |_, params, _| async move {
+ let position = params.text_document_position.position;
+ assert_eq!(position, lsp::Position::new(1, 4));
+ Ok(Some(vec![
+ lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: "\n".to_string(),
+ },
+ lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: "end".to_string(),
+ },
+ ]))
+ },
+ );
+
+ cx.update_editor(|editor, window, cx| editor.newline(&Newline, window, cx));
+ cx.run_until_parked();
+
+ cx.assert_editor_state("function foo() {\n ˇ\nend\n}\n");
+ assert!(request.next().await.is_some());
+ }
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_after_newline_keeps_whitespace_after_cursor(
+ cx: &mut TestAppContext,
+) {
+ init_test(cx, |settings| {
+ settings.defaults.auto_indent = Some(settings::AutoIndentMode::None)
+ });
+ for whitespace in [" ", "\t\t", " \t "] {
+ assert_on_type_formatting_request_position(
+ false,
+ "\n",
+ &format!("function f() {{ˇ{whitespace}let n = 1;\n}}\n"),
+ |editor, window, cx| editor.newline(&Newline, window, cx),
+ lsp::Position::new(1, 0),
+ &format!("function f() {{\nˇ{whitespace}let n = 1;\n}}\n"),
+ cx,
+ )
+ .await;
+ }
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_after_newline_ignores_subsequent_input(cx: &mut TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.auto_indent = Some(settings::AutoIndentMode::None)
+ });
+ assert_on_type_formatting_request_position(
+ false,
+ "\n",
+ "function f() {}ˇ",
+ |editor, window, cx| {
+ editor.newline(&Newline, window, cx);
+ editor.handle_input("function g() {}\nfunction h() {}", window, cx);
+ },
+ lsp::Position::new(1, 0),
+ "function f() {}\nfunction g() {}\nfunction h() {}ˇ",
+ cx,
+ )
+ .await;
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_after_newline_with_existing_indent(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ for async_autoindent in [false, true] {
+ for (whitespace, expected_whitespace, expected_column) in [
+ (" ", "ˇ ", 0),
+ (" ", "ˇ ", 0),
+ ("\t", " ˇ", 4),
+ ] {
+ assert_on_type_formatting_request_position(
+ async_autoindent,
+ "\n",
+ &format!("function f() {{ˇ{whitespace}let n = 1;\n}}\n"),
+ |editor, window, cx| editor.newline(&Newline, window, cx),
+ lsp::Position::new(1, expected_column),
+ &format!("function f() {{\n{expected_whitespace}let n = 1;\n}}\n"),
+ cx,
+ )
+ .await;
+ }
+ }
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_after_newline_ignores_input_while_autoindent_is_pending(
+ cx: &mut TestAppContext,
+) {
+ init_test(cx, |_| {});
+ for (previous_line, input, expected_line, expected_column) in [
+ (" let n = 1;", "n", " nˇ", 4),
+ (" let n = 1;", "n;\nn", " n;\n nˇ", 4),
+ (" let n = 1;", " n", " nˇ", 3),
+ ("", " n", " nˇ", 3),
+ (" let n = 1;", "\tn", " \tnˇ", 3),
+ ] {
+ assert_on_type_formatting_request_position(
+ true,
+ "\n",
+ &format!("function f() {{\n{previous_line}ˇ\n}}\n"),
+ |editor, window, cx| {
+ editor.newline(&Newline, window, cx);
+ editor.handle_input(input, window, cx);
+ },
+ lsp::Position::new(2, expected_column),
+ &format!("function f() {{\n{previous_line}\n{expected_line}\n}}\n"),
+ cx,
+ )
+ .await;
+ }
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_after_outdenting_trigger(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ for async_autoindent in [false, true] {
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
+ first_trigger_character: "}".to_string(),
+ more_trigger_character: None,
+ }),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state("fn f() {\n let n = 1;\n ˇ\n");
+ if async_autoindent {
+ cx.update_buffer(|buffer, _| buffer.set_sync_parse_timeout(None));
+ }
+
+ let mut request = cx.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
+ |_, params, _| async move {
+ assert_eq!(
+ params.text_document_position.position,
+ lsp::Position::new(2, 1)
+ );
+ Ok(Some(vec![]))
+ },
+ );
+
+ cx.update_editor(|editor, window, cx| editor.handle_input("}", window, cx));
+ cx.run_until_parked();
+
+ cx.assert_editor_state("fn f() {\n let n = 1;\n}ˇ\n");
+ assert!(request.next().await.is_some());
+ }
+}
+
+#[gpui::test]
+async fn test_on_type_formatting_does_not_pin_cursor_moved_while_autoindent_is_pending(
+ cx: &mut TestAppContext,
+) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorLspTestContext::new_typescript(
+ lsp::ServerCapabilities {
+ document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
+ first_trigger_character: ";".to_string(),
+ more_trigger_character: None,
+ }),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state("function f() {\n let a=1ˇ\n}\n");
+ cx.update_buffer(|buffer, _| buffer.set_sync_parse_timeout(None));
+
+ let mut request =
+ cx.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(|_, _, _| async move {
+ Ok(Some(vec![
+ lsp::TextEdit {
+ range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 9)),
+ new_text: " ".to_string(),
+ },
+ lsp::TextEdit {
+ range: lsp::Range::new(lsp::Position::new(1, 10), lsp::Position::new(1, 10)),
+ new_text: " ".to_string(),
+ },
+ ]))
+ });
+
+ cx.update_editor(|editor, window, cx| {
+ editor.handle_input(";", window, cx);
+ editor.move_left(&MoveLeft, window, cx);
+ editor.move_left(&MoveLeft, window, cx);
+ });
+ cx.run_until_parked();
+
+ cx.assert_editor_state("function f() {\n let a = ˇ1;\n}\n");
+ assert!(request.next().await.is_some());
+}
+
#[gpui::test]
async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppContext) {
init_test(cx, |_| {});
@@ -50737,3 +51002,44 @@ async fn test_soft_wrap_indent_updated_on_file_move_between_directories(
.unwrap();
assert_eq!(snapshot.soft_wrap_indent(DisplayRow(0)), Some(0));
}
+
+async fn assert_on_type_formatting_request_position(
+ async_autoindent: bool,
+ trigger: &'static str,
+ initial_state: &str,
+ edit: impl FnOnce(&mut Editor, &mut Window, &mut Context<Editor>),
+ expected_position: lsp::Position,
+ expected_state: &str,
+ cx: &mut TestAppContext,
+) {
+ let mut cx = EditorLspTestContext::new_typescript(
+ lsp::ServerCapabilities {
+ document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
+ first_trigger_character: trigger.to_string(),
+ more_trigger_character: None,
+ }),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state(initial_state);
+ if async_autoindent {
+ cx.update_buffer(|buffer, _| buffer.set_sync_parse_timeout(None));
+ }
+
+ let mut request = cx.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
+ move |_, params, _| async move {
+ assert_eq!(params.ch, trigger);
+ assert_eq!(params.text_document_position.position, expected_position);
+ Ok(Some(vec![]))
+ },
+ );
+
+ cx.update_editor(edit);
+ cx.run_until_parked();
+
+ cx.assert_editor_state(expected_state);
+ assert!(request.next().await.is_some());
+}
diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs
index bdee4377695..1d4988b427e 100644
--- a/crates/language/src/buffer.rs
+++ b/crates/language/src/buffer.rs
@@ -119,7 +119,7 @@ pub struct Buffer {
language: Option<Arc<Language>>,
content_language_detection_enabled: bool,
autoindent_requests: Vec<Arc<AutoindentRequest>>,
- wait_for_autoindent_txs: Vec<oneshot::Sender<()>>,
+ wait_for_autoindent_txs: Vec<oneshot::Sender<Option<clock::Lamport>>>,
pending_autoindent: Option<Task<()>>,
sync_parse_timeout: Option<Duration>,
syntax_map: Mutex<SyntaxMap>,
@@ -2125,7 +2125,7 @@ impl Buffer {
} else {
self.autoindent_requests.clear();
for tx in self.wait_for_autoindent_txs.drain(..) {
- tx.send(()).ok();
+ tx.send(None).ok();
}
}
}
@@ -2316,9 +2316,7 @@ impl Buffer {
cx: &mut Context<Self>,
) {
self.autoindent_requests.clear();
- for tx in self.wait_for_autoindent_txs.drain(..) {
- tx.send(()).ok();
- }
+ let wait_for_autoindent_txs = mem::take(&mut self.wait_for_autoindent_txs);
let edits: Vec<_> = indent_sizes
.into_iter()
@@ -2329,10 +2327,13 @@ impl Buffer {
.collect();
let preserve_preview = self.preserve_preview();
- self.edit(edits, None, cx);
+ let edit_id = self.edit(edits, None, cx);
if preserve_preview {
self.refresh_preview();
}
+ for tx in wait_for_autoindent_txs {
+ tx.send(edit_id).ok();
+ }
}
/// Create a minimal edit that will cause the given row to be indented
@@ -2741,7 +2742,10 @@ impl Buffer {
self.text.give_up_waiting();
}
- pub fn wait_for_autoindent_applied(&mut self) -> Option<oneshot::Receiver<()>> {
+ /// Resolves with the id of the edit that applied the pending autoindent, if it changed anything.
+ pub fn wait_for_autoindent_applied(
+ &mut self,
+ ) -> Option<oneshot::Receiver<Option<clock::Lamport>>> {
let mut rx = None;
if !self.autoindent_requests.is_empty() {
let channel = oneshot::channel();
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 62b71b1089a..06e71a9d44d 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -7110,18 +7110,24 @@ impl LspStore {
return None;
}
- let position = position.to_point_utf16(buffer.read(cx));
+ let position = {
+ let buffer = buffer.read(cx);
+ let position = position.to_point_utf16(buffer);
+ buffer.anchor_before(position)
+ };
Some(self.on_type_format_impl(buffer, position, trigger, push_to_history, cx))
}
fn on_type_format_impl(
&mut self,
buffer: Entity<Buffer>,
- position: PointUtf16,
+ position: Anchor,
trigger: String,
push_to_history: bool,
cx: &mut Context<Self>,
) -> Task<Result<Option<Transaction>>> {
+ let autoindent_applied =
+ buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied());
let options = buffer.update(cx, |buffer, cx| {
lsp_command::lsp_formatting_options(
LanguageSettings::for_buffer_at(buffer, position, cx).as_ref(),
@@ -7129,11 +7135,21 @@ impl LspStore {
});
cx.spawn(async move |this, cx| {
- if let Some(waiter) =
- buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())
- {
- waiter.await?;
- }
+ let autoindent_edit_id = match autoindent_applied {
+ Some(waiter) => waiter.await?,
+ None => None,
+ };
+ let position = buffer.read_with(cx, |buffer, _| {
+ let offset = position.to_offset(buffer);
+ let offset = autoindent_edit_id
+ .and_then(|edit_id| {
+ buffer
+ .edited_ranges_for_edit_ids::<usize>([&edit_id])
+ .find(|range| range.start == offset)
+ })
+ .map_or(offset, |range| range.end);
+ offset.to_point_utf16(buffer)
+ });
cx.update(|cx| {
this.update(cx, |this, cx| {
this.request_lsp(