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.

project: Honor document selectors of didChange and didSave registrations (#65253)

Shuhei Kadowaki1563b405f9e2
diff --git a/crates/project/src/buffer_store.rs b/crates/project/src/buffer_store.rs
index 6e3a570a5e1..e522ea00bc7 100644
--- a/crates/project/src/buffer_store.rs
+++ b/crates/project/src/buffer_store.rs
@@ -387,12 +387,14 @@ impl RemoteBufferStore {
}
impl LocalBufferStore {
+ /// `old_file` is given when saving the buffer to a new path, holding the file the buffer had
+ /// before, if any.
fn save_local_buffer(
&self,
buffer_handle: Entity<Buffer>,
worktree: Entity<Worktree>,
path: Arc<RelPath>,
- mut has_changed_file: bool,
+ old_file: Option<Option<Arc<dyn language::File>>>,
cx: &mut Context<BufferStore>,
) -> Task<Result<()>> {
let buffer = buffer_handle.read(cx);
@@ -404,12 +406,10 @@ impl LocalBufferStore {
let version = buffer.version();
let buffer_id = buffer.remote_id();
let file = buffer.file().cloned();
- if file
- .as_ref()
- .is_some_and(|file| file.disk_state() == DiskState::New)
- {
- has_changed_file = true;
- }
+ let has_changed_file = old_file.is_some()
+ || file
+ .as_ref()
+ .is_some_and(|file| file.disk_state() == DiskState::New);
let save = worktree.update(cx, |worktree, cx| {
worktree.write_file(path, text, line_ending, encoding, has_bom, cx)
@@ -439,10 +439,17 @@ impl LocalBufferStore {
.log_err();
}
})?;
+ if has_changed_file {
+ buffer_handle.update(cx, |buffer, cx| buffer.file_updated(new_file, cx));
+ }
+ // Report the new path before the save, so that observers like language servers know
+ // the document by its new path when they learn about the save.
+ if let Some(old_file) = old_file {
+ this.update(cx, |this, cx| {
+ this.did_change_buffer_file_path(buffer_handle.clone(), old_file, cx)
+ })?;
+ }
buffer_handle.update(cx, |buffer, cx| {
- if has_changed_file {
- buffer.file_updated(new_file, cx);
- }
buffer.did_save(version.clone(), mtime, cx);
});
Ok(())
@@ -660,7 +667,7 @@ impl LocalBufferStore {
return Task::ready(Err(anyhow!("buffer doesn't have a file")));
};
let worktree = file.worktree.clone();
- self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
+ self.save_local_buffer(buffer, worktree, file.path.clone(), None, cx)
}
fn save_buffer_as(
@@ -676,7 +683,8 @@ impl LocalBufferStore {
else {
return Task::ready(Err(anyhow!("no such worktree")));
};
- self.save_local_buffer(buffer, worktree, path.path, true, cx)
+ let old_file = buffer.read(cx).file().cloned();
+ self.save_local_buffer(buffer, worktree, path.path, Some(old_file), cx)
}
#[ztracing::instrument(skip_all)]
@@ -994,26 +1002,34 @@ impl BufferStore {
path: ProjectPath,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
- let old_file = buffer.read(cx).file().cloned();
- let task = match &self.state {
- BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
+ match &self.state {
+ BufferStoreState::Local(this) => this.save_buffer_as(buffer, path, cx),
BufferStoreState::Remote(this) => {
- this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
- }
- };
- cx.spawn(async move |this, cx| {
- task.await?;
- this.update(cx, |this, cx| {
- old_file.clone().and_then(|file| {
- this.path_to_buffer_id.remove(&ProjectPath {
- worktree_id: file.worktree_id(cx),
- path: file.path().clone(),
+ let old_file = buffer.read(cx).file().cloned();
+ let task = this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx);
+ cx.spawn(async move |this, cx| {
+ task.await?;
+ this.update(cx, |this, cx| {
+ this.did_change_buffer_file_path(buffer, old_file, cx)
})
- });
+ })
+ }
+ }
+ }
- cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
- })
- })
+ fn did_change_buffer_file_path(
+ &mut self,
+ buffer: Entity<Buffer>,
+ old_file: Option<Arc<dyn language::File>>,
+ cx: &mut Context<Self>,
+ ) {
+ if let Some(file) = &old_file {
+ self.path_to_buffer_id.remove(&ProjectPath {
+ worktree_id: file.worktree_id(cx),
+ path: file.path().clone(),
+ });
+ }
+ cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
}
fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 5085e907aa0..62b71b1089a 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -305,7 +305,8 @@ pub struct DocumentDiagnostics {
#[derive(Clone, Debug)]
struct DocumentSelectorContext {
- language_id: String,
+ /// `None` for documents without a language, which no `language` filter matches.
+ language_id: Option<String>,
scheme: &'static str,
}
@@ -6018,7 +6019,7 @@ impl LspStore {
.find(|adapter| &adapter.name() == server_name)
.map(|adapter| adapter.language_id(language))?;
Some(DocumentSelectorContext {
- language_id,
+ language_id: Some(language_id),
scheme: "file",
})
}
@@ -9599,10 +9600,15 @@ impl LspStore {
cx: &mut Context<Self>,
) -> Option<()> {
let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
+ let local = self.as_local()?;
Some(
- self.as_local()?
+ local
.language_servers_for_buffer(buffer, cx)
- .map(|i| i.1.clone())
+ .map(|(adapter, server)| {
+ let sync_kind =
+ text_document_sync_kind_for_buffer(local, buffer, adapter, server);
+ (server.clone(), sync_kind)
+ })
.collect(),
)
})?;
@@ -9617,9 +9623,7 @@ impl LspStore {
let next_snapshot = buffer.text_snapshot();
let line_ending = next_snapshot.line_ending();
- for language_server in language_servers {
- let language_server = language_server.clone();
-
+ for (language_server, document_sync_kind) in language_servers {
let buffer_snapshots = self
.as_local_mut()?
.buffer_snapshots
@@ -9663,15 +9667,6 @@ impl LspStore {
.collect()
};
- let document_sync_kind = language_server
- .capabilities()
- .text_document_sync
- .as_ref()
- .and_then(|sync| match sync {
- lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
- lsp::TextDocumentSyncCapability::Options(options) => options.change,
- });
-
let build_change = || {
if line_ending_changed {
build_full_change()
@@ -9732,22 +9727,33 @@ impl LspStore {
};
let local = self.as_local()?;
- for server in local.language_servers_for_worktree(worktree_id) {
- if let Some(include_text) = include_text(server.as_ref()) {
- let text = if include_text {
- Some(buffer.read(cx).text())
- } else {
- None
+ // `didSave` registrations may select documents that were never opened in the server,
+ // so every server of the worktree is a candidate.
+ let servers_to_notify = local
+ .language_servers_for_worktree(worktree_id)
+ .filter_map(|server| {
+ let LanguageServerState::Running { adapter, .. } =
+ local.language_servers.get(&server.server_id())?
+ else {
+ return None;
};
- server
- .notify::<lsp::notification::DidSaveTextDocument>(
- lsp::DidSaveTextDocumentParams {
- text_document: text_document.clone(),
- text,
- },
- )
- .ok();
- }
+ let include_text =
+ did_save_include_text_for_buffer(local, buffer.read(cx), adapter, server)?;
+ Some((server.clone(), include_text))
+ })
+ .collect::<Vec<_>>();
+ for (server, include_text) in servers_to_notify {
+ let text = if include_text {
+ Some(buffer.read(cx).text())
+ } else {
+ None
+ };
+ server
+ .notify::<lsp::notification::DidSaveTextDocument>(lsp::DidSaveTextDocumentParams {
+ text_document: text_document.clone(),
+ text,
+ })
+ .ok();
}
let language_servers = buffer.update(cx, |buffer, cx| {
@@ -14937,12 +14943,14 @@ impl LspStore {
fn document_selector_context_for_buffer(
buffer: &Buffer,
adapter: &CachedLspAdapter,
-) -> Option<DocumentSelectorContext> {
- let language = buffer.language()?;
- Some(document_selector_context_for_language(
- &language.name(),
- adapter,
- ))
+) -> DocumentSelectorContext {
+ match buffer.language() {
+ Some(language) => document_selector_context_for_language(&language.name(), adapter),
+ None => DocumentSelectorContext {
+ language_id: None,
+ scheme: "file",
+ },
+ }
}
fn document_selector_context_for_language(
@@ -14950,7 +14958,7 @@ fn document_selector_context_for_language(
adapter: &CachedLspAdapter,
) -> DocumentSelectorContext {
DocumentSelectorContext {
- language_id: adapter.language_id(language),
+ language_id: Some(adapter.language_id(language)),
scheme: "file",
}
}
@@ -14965,7 +14973,7 @@ fn document_selector_matches(
document_selector.iter().any(|filter| {
if let Some(language) = &filter.language
- && language != &context.language_id
+ && context.language_id.as_ref() != Some(language)
{
return false;
}
@@ -15023,10 +15031,7 @@ fn dynamic_text_document_registration_allows_buffer(
buffer: &Buffer,
adapter: &CachedLspAdapter,
) -> bool {
- let Some(context) = document_selector_context_for_buffer(buffer, adapter) else {
- return true;
- };
-
+ let context = document_selector_context_for_buffer(buffer, adapter);
document_selector_matches(registration.document_selector.as_ref(), &context)
}
@@ -16813,23 +16818,86 @@ fn related_information_from_lsp(
)
}
-fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
- match server.capabilities().text_document_sync.as_ref()? {
- lsp::TextDocumentSyncCapability::Options(opts) => match opts.save.as_ref()? {
- // Server wants didSave but didn't specify includeText.
- lsp::TextDocumentSyncSaveOptions::Supported(true) => Some(false),
- // Server doesn't want didSave at all.
- lsp::TextDocumentSyncSaveOptions::Supported(false) => None,
- // Server provided SaveOptions.
- lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
- Some(save_options.include_text.unwrap_or(false))
- }
- },
- // We do not have any save info. Kind affects didChange only.
- lsp::TextDocumentSyncCapability::Kind(_) => None,
+/// Returns `None` when the server does not want `didSave` for the buffer, otherwise whether
+/// the notification should include the buffer's text.
+fn did_save_include_text_for_buffer(
+ local: &LocalLspStore,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+ server: &LanguageServer,
+) -> Option<bool> {
+ fn save_options(
+ capabilities: &lsp::ServerCapabilities,
+ ) -> Option<&lsp::TextDocumentSyncSaveOptions> {
+ match capabilities.text_document_sync.as_ref()? {
+ lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
+ // We do not have any save info. Kind affects didChange only.
+ lsp::TextDocumentSyncCapability::Kind(_) => None,
+ }
+ }
+
+ let server_id = server.server_id();
+ let opened_in_server = local
+ .buffers_opened_in_servers
+ .get(&buffer.remote_id())
+ .is_some_and(|servers| servers.contains(&server_id));
+ let context = document_selector_context_for_buffer(buffer, adapter);
+ // Later registrations take precedence over earlier ones. Registrations without a selector
+ // stand for the documents the client selects for the server, like the static options.
+ let registered_save_options = local
+ .language_server_dynamic_registrations
+ .get(&server_id)
+ .and_then(|registrations| registrations.text_documents.get("textDocument/didSave"))
+ .into_iter()
+ .flat_map(|registrations| registrations.values())
+ .filter(|registration| match registration.document_selector {
+ Some(_) => document_selector_matches(registration.document_selector.as_ref(), &context),
+ None => opened_in_server,
+ })
+ .filter_map(|registration| save_options(&registration.server_capabilities))
+ .next_back();
+ // Static options only cover the documents the server was opened with, while
+ // registrations may select any document, like the manifests a server reloads on save.
+ let save_options = match registered_save_options {
+ Some(save_options) => save_options,
+ None if opened_in_server => {
+ save_options(local.initial_server_capabilities.get(&server_id)?)?
+ }
+ None => return None,
+ };
+ match save_options {
+ // Server wants didSave but didn't specify includeText.
+ lsp::TextDocumentSyncSaveOptions::Supported(true) => Some(false),
+ // Server doesn't want didSave at all.
+ lsp::TextDocumentSyncSaveOptions::Supported(false) => None,
+ // Server provided SaveOptions.
+ lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
+ Some(save_options.include_text.unwrap_or(false))
+ }
}
}
+fn text_document_sync_kind_for_buffer(
+ local: &LocalLspStore,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+ server: &LanguageServer,
+) -> Option<lsp::TextDocumentSyncKind> {
+ // Later registrations take precedence over earlier ones and the static options.
+ text_document_capabilities_for_buffer(local, "textDocument/didChange", buffer, adapter, server)
+ .filter_map(|capabilities| {
+ match capabilities
+ .server_capabilities
+ .text_document_sync
+ .as_ref()?
+ {
+ lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
+ lsp::TextDocumentSyncCapability::Options(options) => options.change,
+ }
+ })
+ .last()
+}
+
/// Completion items are displayed in a `UniformList`.
/// Usually, those items are single-line strings, but in LSP responses,
/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
@@ -17476,7 +17544,7 @@ mod tests {
fn rust_file_context() -> DocumentSelectorContext {
DocumentSelectorContext {
- language_id: "rust".to_string(),
+ language_id: Some("rust".to_string()),
scheme: "file",
}
}
diff --git a/crates/project/src/lsp_store/dynamic_registration.rs b/crates/project/src/lsp_store/dynamic_registration.rs
index 73a5a1cdf6b..7572f4a5ef8 100644
--- a/crates/project/src/lsp_store/dynamic_registration.rs
+++ b/crates/project/src/lsp_store/dynamic_registration.rs
@@ -218,6 +218,113 @@ impl LspStore {
}))
}
+ /// `didChange` and `didSave` registrations both carry their options in
+ /// `textDocumentSync`, so they cannot share the per-field bookkeeping of
+ /// [`Self::register_dynamic_text_document_capability`].
+ fn register_dynamic_text_document_sync(
+ &mut self,
+ server: &LanguageServer,
+ method: &str,
+ registration_id: String,
+ document_selector: Option<lsp::DocumentSelector>,
+ sync_options: lsp::TextDocumentSyncOptions,
+ cx: &mut Context<Self>,
+ ) -> anyhow::Result<()> {
+ let local = self
+ .as_local_mut()
+ .context("Expected LSP Store to be local")?;
+ local
+ .language_server_dynamic_registrations
+ .entry(server.server_id())
+ .or_default()
+ .text_documents
+ .entry(method.to_owned())
+ .or_default()
+ .insert(
+ registration_id,
+ DynamicTextDocumentRegistration {
+ document_selector,
+ server_capabilities: lsp::ServerCapabilities {
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ sync_options,
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ },
+ );
+ self.mirror_dynamic_text_document_sync(server, cx)
+ }
+
+ fn unregister_dynamic_text_document_sync(
+ &mut self,
+ server: &LanguageServer,
+ unregistration: &lsp::Unregistration,
+ cx: &mut Context<Self>,
+ ) -> anyhow::Result<()> {
+ let local = self
+ .as_local_mut()
+ .context("Expected LSP Store to be local")?;
+ let removed = local
+ .language_server_dynamic_registrations
+ .get_mut(&server.server_id())
+ .and_then(|registrations| registrations.text_documents.get_mut(&unregistration.method))
+ .and_then(|registrations| registrations.shift_remove(&unregistration.id));
+ if removed.is_none() {
+ log::warn!(
+ "Attempted to unregister non-existent {} registration with ID {}",
+ unregistration.method,
+ unregistration.id
+ );
+ return Ok(());
+ }
+ self.mirror_dynamic_text_document_sync(server, cx)
+ }
+
+ /// Mirrors the most recent `didChange` and `didSave` registrations (or the static
+ /// options, without any) into the server's merged capabilities, for consumers that
+ /// cannot evaluate document selectors.
+ fn mirror_dynamic_text_document_sync(
+ &mut self,
+ server: &LanguageServer,
+ cx: &mut Context<Self>,
+ ) -> anyhow::Result<()> {
+ let server_id = server.server_id();
+ let local = self.as_local().context("Expected LSP Store to be local")?;
+ let mut initial_capabilities = local
+ .initial_server_capabilities
+ .get(&server_id)
+ .cloned()
+ .unwrap_or_default();
+ let mut sync_options = take_text_document_sync_options(&mut initial_capabilities);
+ let text_document_registrations = local
+ .language_server_dynamic_registrations
+ .get(&server_id)
+ .map(|registrations| &registrations.text_documents);
+ let latest_sync_options = |method: &str| {
+ let (_, registration) = text_document_registrations?.get(method)?.last()?;
+ match registration
+ .server_capabilities
+ .text_document_sync
+ .as_ref()?
+ {
+ lsp::TextDocumentSyncCapability::Options(options) => Some(options.clone()),
+ lsp::TextDocumentSyncCapability::Kind(_) => None,
+ }
+ };
+ if let Some(options) = latest_sync_options("textDocument/didChange") {
+ sync_options.change = options.change;
+ }
+ if let Some(options) = latest_sync_options("textDocument/didSave") {
+ sync_options.save = options.save;
+ }
+ server.update_capabilities(|capabilities| {
+ capabilities.text_document_sync =
+ Some(lsp::TextDocumentSyncCapability::Options(sync_options));
+ });
+ self.notify_server_capabilities_updated(server, cx);
+ Ok(())
+ }
+
/// Returns `true` when the registration changed the server's active capability value:
/// duplicate-ID replacements of non-active registrations and (re-)registrations with
/// options identical to the active ones do not.
@@ -700,48 +807,49 @@ impl LspStore {
}
}
"textDocument/didChange" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(sync_kind) = reg
.register_options
.and_then(|opts| opts.get("syncKind").cloned())
.map(serde_json::from_value::<lsp::TextDocumentSyncKind>)
.transpose()?
{
- server.update_capabilities(|capabilities| {
- let mut sync_options = take_text_document_sync_options(capabilities);
- sync_options.change = Some(sync_kind);
- capabilities.text_document_sync =
- Some(lsp::TextDocumentSyncCapability::Options(sync_options));
- });
- self.notify_server_capabilities_updated(&server, cx);
+ self.register_dynamic_text_document_sync(
+ &server,
+ &reg.method,
+ reg.id,
+ document_selector,
+ lsp::TextDocumentSyncOptions {
+ change: Some(sync_kind),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ cx,
+ )?;
}
}
"textDocument/didSave" => {
- if let Some(include_text) = reg
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
+ let include_text = reg
.register_options
- .map(|opts| {
- let transpose = opts
- .get("includeText")
- .cloned()
- .map(serde_json::from_value::<Option<bool>>)
- .transpose();
- match transpose {
- Ok(value) => Ok(value.flatten()),
- Err(e) => Err(e),
- }
- })
+ .and_then(|opts| opts.get("includeText").cloned())
+ .map(serde_json::from_value::<Option<bool>>)
.transpose()?
- {
- server.update_capabilities(|capabilities| {
- let mut sync_options = take_text_document_sync_options(capabilities);
- sync_options.save =
- Some(TextDocumentSyncSaveOptions::SaveOptions(lsp::SaveOptions {
- include_text,
- }));
- capabilities.text_document_sync =
- Some(lsp::TextDocumentSyncCapability::Options(sync_options));
- });
- self.notify_server_capabilities_updated(&server, cx);
- }
+ .flatten();
+ self.register_dynamic_text_document_sync(
+ &server,
+ &reg.method,
+ reg.id,
+ document_selector,
+ lsp::TextDocumentSyncOptions {
+ save: Some(TextDocumentSyncSaveOptions::SaveOptions(
+ lsp::SaveOptions { include_text },
+ )),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ cx,
+ )?;
}
"textDocument/codeLens" => {
let document_selector =
@@ -1120,23 +1228,8 @@ impl LspStore {
self.refresh_semantic_tokens(server_id, cx);
}
}
- "textDocument/didChange" => {
- server.update_capabilities(|capabilities| {
- let mut sync_options = take_text_document_sync_options(capabilities);
- sync_options.change = None;
- capabilities.text_document_sync =
- Some(lsp::TextDocumentSyncCapability::Options(sync_options));
- });
- self.notify_server_capabilities_updated(&server, cx);
- }
- "textDocument/didSave" => {
- server.update_capabilities(|capabilities| {
- let mut sync_options = take_text_document_sync_options(capabilities);
- sync_options.save = None;
- capabilities.text_document_sync =
- Some(lsp::TextDocumentSyncCapability::Options(sync_options));
- });
- self.notify_server_capabilities_updated(&server, cx);
+ "textDocument/didChange" | "textDocument/didSave" => {
+ self.unregister_dynamic_text_document_sync(&server, unreg, cx)?;
}
"textDocument/inlayHint" => {
if self
diff --git a/crates/project/tests/integration/dynamic_registration.rs b/crates/project/tests/integration/dynamic_registration.rs
index ae5da9cb3a5..fdc8f37f409 100644
--- a/crates/project/tests/integration/dynamic_registration.rs
+++ b/crates/project/tests/integration/dynamic_registration.rs
@@ -2744,6 +2744,302 @@ async fn test_multiple_did_change_watched_files_registrations(cx: &mut gpui::Tes
);
}
+#[gpui::test]
+async fn test_did_change_registration_respects_document_selector(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, mut fake_server) = setup_dynamic_registration_test(
+ cx,
+ lsp::ServerCapabilities {
+ // Test builds send incremental changes even without a sync kind, so the static
+ // `FULL` sync tells the fallback to the static options apart from no sync at all.
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Kind(
+ lsp::TextDocumentSyncKind::FULL,
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ )
+ .await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/didChange";
+
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ let uri = lsp::Uri::from_file_path(path!("/the-root/a.rs")).unwrap();
+ let sync_options = |sync_kind: lsp::TextDocumentSyncKind| {
+ Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ change: Some(sync_kind),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ ))
+ };
+
+ register_capability(
+ &fake_server,
+ method,
+ "change-python",
+ Some(json!({
+ "documentSelector": [{ "language": "python" }],
+ "syncKind": 2,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).text_document_sync,
+ sync_options(lsp::TextDocumentSyncKind::INCREMENTAL),
+ "expected the latest registration to be mirrored into the merged capabilities",
+ );
+ assert_eq!(
+ edit_and_receive_change(&buffer, &mut fake_server, cx).await,
+ (uri.clone(), false),
+ "expected the static full sync for a document outside the registration's selector",
+ );
+
+ register_capability(
+ &fake_server,
+ method,
+ "change-rust",
+ Some(json!({
+ "documentSelector": [{ "language": "rust" }],
+ "syncKind": 2,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ edit_and_receive_change(&buffer, &mut fake_server, cx).await,
+ (uri.clone(), true),
+ "expected the matching registration's incremental sync to be used",
+ );
+
+ unregister_capabilities(&fake_server, method, &["change-python", "change-rust"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).text_document_sync,
+ sync_options(lsp::TextDocumentSyncKind::FULL),
+ "expected unregistering to restore the static sync kind",
+ );
+ assert_eq!(
+ edit_and_receive_change(&buffer, &mut fake_server, cx).await,
+ (uri, false),
+ "expected the static full sync after unregistering",
+ );
+}
+
+#[gpui::test]
+async fn test_did_save_registration_respects_document_selector(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, mut fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let method = "textDocument/didSave";
+
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ let uri = lsp::Uri::from_file_path(path!("/the-root/a.rs")).unwrap();
+ let save = async |cx: &mut gpui::TestAppContext| {
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ };
+
+ // A save notified through this registration would carry the buffer's text.
+ register_capability(
+ &fake_server,
+ method,
+ "save-python",
+ Some(json!({
+ "documentSelector": [{ "language": "python" }],
+ "includeText": true,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ save(cx).await;
+
+ register_capability(
+ &fake_server,
+ method,
+ "save-rust",
+ Some(json!({
+ "documentSelector": [{ "language": "rust" }],
+ "includeText": false,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ save(cx).await;
+ let params = fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await;
+ assert_eq!(
+ (params.text_document.uri, params.text),
+ (uri.clone(), None),
+ "expected only the registration matching the document to notify its saves",
+ );
+
+ unregister_capabilities(&fake_server, method, &["save-python", "save-rust"]).await;
+ register_capability(&fake_server, method, "save-all", None).await;
+ cx.executor().run_until_parked();
+ save(cx).await;
+ let params = fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await;
+ assert_eq!(
+ (params.text_document.uri, params.text),
+ (uri, None),
+ "expected a registration without options to apply to every document, without text",
+ );
+}
+
+#[gpui::test]
+async fn test_did_save_registration_selects_documents_not_opened_in_server(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, mut fake_server) = setup_dynamic_registration_test(
+ cx,
+ lsp::ServerCapabilities {
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ save: Some(lsp::TextDocumentSyncSaveOptions::Supported(true)),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ )
+ .await;
+ let fs = project.read_with(cx, |project, _| project.fs().as_fake());
+ fs.insert_tree(path!("/the-root"), json!({ "Cargo.toml": "" }))
+ .await;
+ let method = "textDocument/didSave";
+
+ let (rust_buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let manifest_buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/the-root/Cargo.toml"), cx)
+ })
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let rust_uri = lsp::Uri::from_file_path(path!("/the-root/a.rs")).unwrap();
+ let manifest_uri = lsp::Uri::from_file_path(path!("/the-root/Cargo.toml")).unwrap();
+ let save = async |buffer: &Entity<Buffer>, cx: &mut gpui::TestAppContext| {
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ };
+
+ // The static save capability does not cover the manifest, so the next notification is
+ // the one for the Rust buffer.
+ save(&manifest_buffer, cx).await;
+ save(&rust_buffer, cx).await;
+ assert_eq!(
+ fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await
+ .text_document
+ .uri,
+ rust_uri,
+ "expected the static save capability to only cover documents opened in the server",
+ );
+
+ // The manifest has no language, so a registration for a language does not select it.
+ register_capability(
+ &fake_server,
+ method,
+ "save-rust",
+ Some(json!({ "documentSelector": [{ "language": "rust" }] })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ save(&manifest_buffer, cx).await;
+ save(&rust_buffer, cx).await;
+ assert_eq!(
+ fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await
+ .text_document
+ .uri,
+ rust_uri,
+ "expected a language filter not to select a document without a language",
+ );
+
+ // A registration without a selector stands for the documents the server was opened with.
+ register_capability(&fake_server, method, "save-opened", None).await;
+ cx.executor().run_until_parked();
+ save(&manifest_buffer, cx).await;
+ save(&rust_buffer, cx).await;
+ assert_eq!(
+ fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await
+ .text_document
+ .uri,
+ rust_uri,
+ "expected a registration without a selector to only cover documents opened in the server",
+ );
+
+ // Like the registration rust-analyzer makes to reload its workspace on manifest saves.
+ register_capability(
+ &fake_server,
+ method,
+ "save-files",
+ Some(json!({
+ "documentSelector": [{ "scheme": "file" }],
+ "includeText": false,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ save(&manifest_buffer, cx).await;
+ let params = fake_server
+ .receive_notification::<lsp::notification::DidSaveTextDocument>()
+ .await;
+ assert_eq!(
+ (params.text_document.uri, params.text),
+ (manifest_uri, None),
+ "expected a registration selecting the manifest to notify its saves",
+ );
+}
+
+/// Returns the URI of the change notification and whether the change was incremental.
+async fn edit_and_receive_change(
+ buffer: &Entity<Buffer>,
+ fake_server: &mut lsp::FakeLanguageServer,
+ cx: &mut gpui::TestAppContext,
+) -> (lsp::Uri, bool) {
+ buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "x")], None, cx));
+ let params = fake_server
+ .receive_notification::<lsp::notification::DidChangeTextDocument>()
+ .await;
+ let [change] = params.content_changes.as_slice() else {
+ panic!("expected a single content change, got {params:?}");
+ };
+ (params.text_document.uri, change.range.is_some())
+}
+
async fn setup_dynamic_registration_test(
cx: &mut gpui::TestAppContext,
capabilities: lsp::ServerCapabilities,
diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs
index 62e30539191..2887f32b1c0 100644
--- a/crates/project/tests/integration/project_tests.rs
+++ b/crates/project/tests/integration/project_tests.rs
@@ -1757,6 +1757,128 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
assert_eq!(server.server_id(), LanguageServerId(1));
}
+#[gpui::test]
+async fn test_save_as_notifies_language_servers_of_the_document_at_its_new_path(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "", "b.rs": "" }))
+ .await;
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ save: Some(lsp::TextDocumentSyncSaveOptions::Supported(true)),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (_running_buffer, _running_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/b.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let notifications = Arc::new(Mutex::new(Vec::new()));
+ let file_name = |uri: &lsp::Uri| {
+ uri.to_file_path()
+ .ok()
+ .and_then(|path| Some(path.file_name()?.to_string_lossy().into_owned()))
+ .unwrap_or_else(|| uri.to_string())
+ };
+ fake_server.handle_notification::<lsp::notification::DidOpenTextDocument, _>({
+ let notifications = notifications.clone();
+ move |params, _| {
+ notifications
+ .lock()
+ .push(format!("open {}", file_name(&params.text_document.uri)))
+ }
+ });
+ fake_server.handle_notification::<lsp::notification::DidSaveTextDocument, _>({
+ let notifications = notifications.clone();
+ move |params, _| {
+ notifications
+ .lock()
+ .push(format!("save {}", file_name(&params.text_document.uri)))
+ }
+ });
+ fake_server.handle_notification::<lsp::notification::DidCloseTextDocument, _>({
+ let notifications = notifications.clone();
+ move |params, _| {
+ notifications
+ .lock()
+ .push(format!("close {}", file_name(&params.text_document.uri)))
+ }
+ });
+
+ let worktree_id = project.read_with(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+ let save_as = async |buffer: &Entity<Buffer>, path: &str, cx: &mut gpui::TestAppContext| {
+ project
+ .update(cx, |project, cx| {
+ project.save_buffer_as(
+ buffer.clone(),
+ ProjectPath {
+ worktree_id,
+ path: rel_path(path).into(),
+ },
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ std::mem::take(&mut *notifications.lock())
+ };
+
+ // An untitled buffer only becomes a document of the server by being saved, so the server
+ // must learn about the document before its save.
+ let untitled_buffer = project.update(cx, |project, cx| {
+ project.create_local_buffer("fn main() {}", Some(rust_lang()), true, cx)
+ });
+ let _untitled_handle = project.update(cx, |project, cx| {
+ project.register_buffer_with_language_servers(&untitled_buffer, cx)
+ });
+ cx.executor().run_until_parked();
+ assert_eq!(
+ save_as(&untitled_buffer, "new.rs", cx).await,
+ vec!["open new.rs".to_string(), "save new.rs".to_string()],
+ );
+
+ let (renamed_buffer, _renamed_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ notifications.lock().clear();
+ assert_eq!(
+ save_as(&renamed_buffer, "renamed.rs", cx).await,
+ vec![
+ "close a.rs".to_string(),
+ "open renamed.rs".to_string(),
+ "save renamed.rs".to_string(),
+ ],
+ );
+}
+
#[gpui::test]
async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
init_test(cx);
@@ -1980,19 +2102,20 @@ async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
)
);
- // Save notifications are reported to all servers.
- project
- .update(cx, |project, cx| project.save_buffer(toml_buffer, cx))
- .await
- .unwrap();
+ // Static save capabilities only cover the documents a server was opened with, so saving
+ // the TOML buffer notifies no server: the next save notifications are for their own buffers.
+ for buffer in [toml_buffer, rust_buffer2.clone(), json_buffer.clone()] {
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer, cx))
+ .await
+ .unwrap();
+ }
assert_eq!(
fake_rust_server
.receive_notification::<lsp::notification::DidSaveTextDocument>()
.await
.text_document,
- lsp::TextDocumentIdentifier::new(
- lsp::Uri::from_file_path(path!("/dir/Cargo.toml")).unwrap()
- )
+ lsp::TextDocumentIdentifier::new(lsp::Uri::from_file_path(path!("/dir/test2.rs")).unwrap())
);
assert_eq!(
fake_json_server
@@ -2000,7 +2123,7 @@ async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
.await
.text_document,
lsp::TextDocumentIdentifier::new(
- lsp::Uri::from_file_path(path!("/dir/Cargo.toml")).unwrap()
+ lsp::Uri::from_file_path(path!("/dir/package.json")).unwrap()
)
);