1pub mod clangd_ext;
2pub mod lsp_ext_command;
3pub mod rust_analyzer_ext;
4
5use crate::{
6 CodeAction, ColorPresentation, Completion, CompletionResponse, CompletionSource,
7 CoreCompletion, DocumentColor, Hover, InlayHint, LspAction, LspPullDiagnostics, ProjectItem,
8 ProjectPath, ProjectTransaction, PulledDiagnostics, ResolveState, Symbol, ToolchainStore,
9 buffer_store::{BufferStore, BufferStoreEvent},
10 environment::ProjectEnvironment,
11 lsp_command::{self, *},
12 lsp_store,
13 manifest_tree::{
14 AdapterQuery, LanguageServerTree, LanguageServerTreeNode, LaunchDisposition,
15 ManifestQueryDelegate, ManifestTree,
16 },
17 prettier_store::{self, PrettierStore, PrettierStoreEvent},
18 project_settings::{LspSettings, ProjectSettings},
19 relativize_path, resolve_path,
20 toolchain_store::{EmptyToolchainStore, ToolchainStoreEvent},
21 worktree_store::{WorktreeStore, WorktreeStoreEvent},
22 yarn::YarnPathStore,
23};
24use anyhow::{Context as _, Result, anyhow};
25use async_trait::async_trait;
26use client::{TypedEnvelope, proto};
27use clock::Global;
28use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
29use futures::{
30 AsyncWriteExt, Future, FutureExt, StreamExt,
31 future::{Shared, join_all},
32 select, select_biased,
33 stream::FuturesUnordered,
34};
35use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
36use gpui::{
37 App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString, Task,
38 WeakEntity,
39};
40use http_client::HttpClient;
41use itertools::Itertools as _;
42use language::{
43 Bias, BinaryStatus, Buffer, BufferSnapshot, CachedLspAdapter, CodeLabel, Diagnostic,
44 DiagnosticEntry, DiagnosticSet, DiagnosticSourceKind, Diff, File as _, Language, LanguageName,
45 LanguageRegistry, LanguageToolchainStore, LocalFile, LspAdapter, LspAdapterDelegate, Patch,
46 PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
47 language_settings::{
48 FormatOnSave, Formatter, LanguageSettings, SelectedFormatter, language_settings,
49 },
50 point_to_lsp,
51 proto::{
52 deserialize_anchor, deserialize_lsp_edit, deserialize_version, serialize_anchor,
53 serialize_lsp_edit, serialize_version,
54 },
55 range_from_lsp, range_to_lsp,
56};
57use lsp::{
58 CodeActionKind, CompletionContext, DiagnosticSeverity, DiagnosticTag,
59 DidChangeWatchedFilesRegistrationOptions, Edit, FileOperationFilter, FileOperationPatternKind,
60 FileOperationRegistrationOptions, FileRename, FileSystemWatcher, LanguageServer,
61 LanguageServerBinary, LanguageServerBinaryOptions, LanguageServerId, LanguageServerName,
62 LanguageServerSelector, LspRequestFuture, MessageActionItem, MessageType, OneOf,
63 RenameFilesParams, SymbolKind, TextEdit, WillRenameFiles, WorkDoneProgressCancelParams,
64 WorkspaceFolder, notification::DidRenameFiles,
65};
66use node_runtime::read_package_installed_version;
67use parking_lot::Mutex;
68use postage::{mpsc, sink::Sink, stream::Stream, watch};
69use rand::prelude::*;
70
71use rpc::{
72 AnyProtoClient,
73 proto::{FromProto, ToProto},
74};
75use serde::Serialize;
76use settings::{Settings, SettingsLocation, SettingsStore};
77use sha2::{Digest, Sha256};
78use smol::channel::Sender;
79use snippet::Snippet;
80use std::{
81 any::Any,
82 borrow::Cow,
83 cell::RefCell,
84 cmp::{Ordering, Reverse},
85 convert::TryInto,
86 ffi::OsStr,
87 iter, mem,
88 ops::{ControlFlow, Range},
89 path::{self, Path, PathBuf},
90 rc::Rc,
91 sync::Arc,
92 time::{Duration, Instant},
93};
94use text::{Anchor, BufferId, LineEnding, OffsetRangeExt};
95use url::Url;
96use util::{
97 ConnectionResult, ResultExt as _, debug_panic, defer, maybe, merge_json_value_into,
98 paths::{PathExt, SanitizedPath},
99 post_inc,
100};
101
102pub use fs::*;
103pub use language::Location;
104#[cfg(any(test, feature = "test-support"))]
105pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
106pub use worktree::{
107 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
108 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
109};
110
111const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
112pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum FormatTrigger {
116 Save,
117 Manual,
118}
119
120pub enum LspFormatTarget {
121 Buffers,
122 Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
123}
124
125pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
126
127impl FormatTrigger {
128 fn from_proto(value: i32) -> FormatTrigger {
129 match value {
130 0 => FormatTrigger::Save,
131 1 => FormatTrigger::Manual,
132 _ => FormatTrigger::Save,
133 }
134 }
135}
136
137pub struct LocalLspStore {
138 weak: WeakEntity<LspStore>,
139 worktree_store: Entity<WorktreeStore>,
140 toolchain_store: Entity<ToolchainStore>,
141 http_client: Arc<dyn HttpClient>,
142 environment: Entity<ProjectEnvironment>,
143 fs: Arc<dyn Fs>,
144 languages: Arc<LanguageRegistry>,
145 language_server_ids: HashMap<(WorktreeId, LanguageServerName), BTreeSet<LanguageServerId>>,
146 yarn: Entity<YarnPathStore>,
147 pub language_servers: HashMap<LanguageServerId, LanguageServerState>,
148 buffers_being_formatted: HashSet<BufferId>,
149 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
150 language_server_watched_paths: HashMap<LanguageServerId, LanguageServerWatchedPaths>,
151 language_server_paths_watched_for_rename:
152 HashMap<LanguageServerId, RenamePathsWatchedForServer>,
153 language_server_watcher_registrations:
154 HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
155 supplementary_language_servers:
156 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
157 prettier_store: Entity<PrettierStore>,
158 next_diagnostic_group_id: usize,
159 diagnostics: HashMap<
160 WorktreeId,
161 HashMap<
162 Arc<Path>,
163 Vec<(
164 LanguageServerId,
165 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
166 )>,
167 >,
168 >,
169 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
170 _subscription: gpui::Subscription,
171 lsp_tree: Entity<LanguageServerTree>,
172 registered_buffers: HashMap<BufferId, usize>,
173 buffers_opened_in_servers: HashMap<BufferId, HashSet<LanguageServerId>>,
174 buffer_pull_diagnostics_result_ids: HashMap<LanguageServerId, HashMap<PathBuf, Option<String>>>,
175}
176
177impl LocalLspStore {
178 /// Returns the running language server for the given ID. Note if the language server is starting, it will not be returned.
179 pub fn running_language_server_for_id(
180 &self,
181 id: LanguageServerId,
182 ) -> Option<&Arc<LanguageServer>> {
183 let language_server_state = self.language_servers.get(&id)?;
184
185 match language_server_state {
186 LanguageServerState::Running { server, .. } => Some(server),
187 LanguageServerState::Starting { .. } => None,
188 }
189 }
190
191 fn start_language_server(
192 &mut self,
193 worktree_handle: &Entity<Worktree>,
194 delegate: Arc<LocalLspAdapterDelegate>,
195 adapter: Arc<CachedLspAdapter>,
196 settings: Arc<LspSettings>,
197 cx: &mut App,
198 ) -> LanguageServerId {
199 let worktree = worktree_handle.read(cx);
200 let worktree_id = worktree.id();
201 let root_path = worktree.abs_path();
202 let key = (worktree_id, adapter.name.clone());
203
204 let override_options = settings.initialization_options.clone();
205
206 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
207
208 let server_id = self.languages.next_language_server_id();
209 log::info!(
210 "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
211 adapter.name.0
212 );
213
214 let binary = self.get_language_server_binary(adapter.clone(), delegate.clone(), true, cx);
215 let pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
216 let pending_server = cx.spawn({
217 let adapter = adapter.clone();
218 let server_name = adapter.name.clone();
219 let stderr_capture = stderr_capture.clone();
220 #[cfg(any(test, feature = "test-support"))]
221 let lsp_store = self.weak.clone();
222 let pending_workspace_folders = pending_workspace_folders.clone();
223 async move |cx| {
224 let binary = binary.await?;
225 #[cfg(any(test, feature = "test-support"))]
226 if let Some(server) = lsp_store
227 .update(&mut cx.clone(), |this, cx| {
228 this.languages.create_fake_language_server(
229 server_id,
230 &server_name,
231 binary.clone(),
232 &mut cx.to_async(),
233 )
234 })
235 .ok()
236 .flatten()
237 {
238 return Ok(server);
239 }
240
241 lsp::LanguageServer::new(
242 stderr_capture,
243 server_id,
244 server_name,
245 binary,
246 &root_path,
247 adapter.code_action_kinds(),
248 pending_workspace_folders,
249 cx,
250 )
251 }
252 });
253
254 let startup = {
255 let server_name = adapter.name.0.clone();
256 let delegate = delegate as Arc<dyn LspAdapterDelegate>;
257 let key = key.clone();
258 let adapter = adapter.clone();
259 let lsp_store = self.weak.clone();
260 let pending_workspace_folders = pending_workspace_folders.clone();
261 let fs = self.fs.clone();
262 let pull_diagnostics = ProjectSettings::get_global(cx)
263 .diagnostics
264 .lsp_pull_diagnostics
265 .enabled;
266 cx.spawn(async move |cx| {
267 let result = async {
268 let toolchains =
269 lsp_store.update(cx, |lsp_store, cx| lsp_store.toolchain_store(cx))?;
270 let language_server = pending_server.await?;
271
272 let workspace_config = Self::workspace_configuration_for_adapter(
273 adapter.adapter.clone(),
274 fs.as_ref(),
275 &delegate,
276 toolchains.clone(),
277 cx,
278 )
279 .await?;
280
281 let mut initialization_options = Self::initialization_options_for_adapter(
282 adapter.adapter.clone(),
283 fs.as_ref(),
284 &delegate,
285 )
286 .await?;
287
288 match (&mut initialization_options, override_options) {
289 (Some(initialization_options), Some(override_options)) => {
290 merge_json_value_into(override_options, initialization_options);
291 }
292 (None, override_options) => initialization_options = override_options,
293 _ => {}
294 }
295
296 let initialization_params = cx.update(|cx| {
297 let mut params =
298 language_server.default_initialize_params(pull_diagnostics, cx);
299 params.initialization_options = initialization_options;
300 adapter.adapter.prepare_initialize_params(params, cx)
301 })??;
302
303 Self::setup_lsp_messages(
304 lsp_store.clone(),
305 fs,
306 &language_server,
307 delegate.clone(),
308 adapter.clone(),
309 );
310
311 let did_change_configuration_params =
312 Arc::new(lsp::DidChangeConfigurationParams {
313 settings: workspace_config,
314 });
315 let language_server = cx
316 .update(|cx| {
317 language_server.initialize(
318 initialization_params,
319 did_change_configuration_params.clone(),
320 cx,
321 )
322 })?
323 .await
324 .inspect_err(|_| {
325 if let Some(lsp_store) = lsp_store.upgrade() {
326 lsp_store
327 .update(cx, |lsp_store, cx| {
328 lsp_store.cleanup_lsp_data(server_id);
329 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id))
330 })
331 .ok();
332 }
333 })?;
334
335 language_server
336 .notify::<lsp::notification::DidChangeConfiguration>(
337 &did_change_configuration_params,
338 )
339 .ok();
340
341 anyhow::Ok(language_server)
342 }
343 .await;
344
345 match result {
346 Ok(server) => {
347 lsp_store
348 .update(cx, |lsp_store, mut cx| {
349 lsp_store.insert_newly_running_language_server(
350 adapter,
351 server.clone(),
352 server_id,
353 key,
354 pending_workspace_folders,
355 &mut cx,
356 );
357 })
358 .ok();
359 stderr_capture.lock().take();
360 Some(server)
361 }
362
363 Err(err) => {
364 let log = stderr_capture.lock().take().unwrap_or_default();
365 delegate.update_status(
366 adapter.name(),
367 BinaryStatus::Failed {
368 error: format!("{err}\n-- stderr--\n{log}"),
369 },
370 );
371 let message =
372 format!("Failed to start language server {server_name:?}: {err:#?}");
373 log::error!("{message}");
374 log::error!("server stderr: {log}");
375 None
376 }
377 }
378 })
379 };
380 let state = LanguageServerState::Starting {
381 startup,
382 pending_workspace_folders,
383 };
384
385 self.languages
386 .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
387
388 self.language_servers.insert(server_id, state);
389 self.language_server_ids
390 .entry(key)
391 .or_default()
392 .insert(server_id);
393 server_id
394 }
395
396 fn get_language_server_binary(
397 &self,
398 adapter: Arc<CachedLspAdapter>,
399 delegate: Arc<dyn LspAdapterDelegate>,
400 allow_binary_download: bool,
401 cx: &mut App,
402 ) -> Task<Result<LanguageServerBinary>> {
403 let settings = ProjectSettings::get(
404 Some(SettingsLocation {
405 worktree_id: delegate.worktree_id(),
406 path: Path::new(""),
407 }),
408 cx,
409 )
410 .lsp
411 .get(&adapter.name)
412 .and_then(|s| s.binary.clone());
413
414 if settings.as_ref().is_some_and(|b| b.path.is_some()) {
415 let settings = settings.unwrap();
416
417 return cx.spawn(async move |_| {
418 let mut env = delegate.shell_env().await;
419 env.extend(settings.env.unwrap_or_default());
420
421 Ok(LanguageServerBinary {
422 path: PathBuf::from(&settings.path.unwrap()),
423 env: Some(env),
424 arguments: settings
425 .arguments
426 .unwrap_or_default()
427 .iter()
428 .map(Into::into)
429 .collect(),
430 })
431 });
432 }
433 let lsp_binary_options = LanguageServerBinaryOptions {
434 allow_path_lookup: !settings
435 .as_ref()
436 .and_then(|b| b.ignore_system_version)
437 .unwrap_or_default(),
438 allow_binary_download,
439 };
440 let toolchains = self.toolchain_store.read(cx).as_language_toolchain_store();
441 cx.spawn(async move |cx| {
442 let binary_result = adapter
443 .clone()
444 .get_language_server_command(delegate.clone(), toolchains, lsp_binary_options, cx)
445 .await;
446
447 delegate.update_status(adapter.name.clone(), BinaryStatus::None);
448
449 let mut binary = binary_result?;
450 let mut shell_env = delegate.shell_env().await;
451
452 shell_env.extend(binary.env.unwrap_or_default());
453
454 if let Some(settings) = settings {
455 if let Some(arguments) = settings.arguments {
456 binary.arguments = arguments.into_iter().map(Into::into).collect();
457 }
458 if let Some(env) = settings.env {
459 shell_env.extend(env);
460 }
461 }
462
463 binary.env = Some(shell_env);
464 Ok(binary)
465 })
466 }
467
468 fn setup_lsp_messages(
469 this: WeakEntity<LspStore>,
470 fs: Arc<dyn Fs>,
471 language_server: &LanguageServer,
472 delegate: Arc<dyn LspAdapterDelegate>,
473 adapter: Arc<CachedLspAdapter>,
474 ) {
475 let name = language_server.name();
476 let server_id = language_server.server_id();
477 language_server
478 .on_notification::<lsp::notification::PublishDiagnostics, _>({
479 let adapter = adapter.clone();
480 let this = this.clone();
481 move |mut params, cx| {
482 let adapter = adapter.clone();
483 if let Some(this) = this.upgrade() {
484 this.update(cx, |this, cx| {
485 {
486 let buffer = params
487 .uri
488 .to_file_path()
489 .map(|file_path| this.get_buffer(&file_path, cx))
490 .ok()
491 .flatten();
492 adapter.process_diagnostics(&mut params, server_id, buffer);
493 }
494
495 this.merge_diagnostics(
496 server_id,
497 params,
498 None,
499 DiagnosticSourceKind::Pushed,
500 &adapter.disk_based_diagnostic_sources,
501 |_, diagnostic, cx| match diagnostic.source_kind {
502 DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => {
503 adapter.retain_old_diagnostic(diagnostic, cx)
504 }
505 DiagnosticSourceKind::Pulled => true,
506 },
507 cx,
508 )
509 .log_err();
510 })
511 .ok();
512 }
513 }
514 })
515 .detach();
516 language_server
517 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
518 let adapter = adapter.adapter.clone();
519 let delegate = delegate.clone();
520 let this = this.clone();
521 let fs = fs.clone();
522 move |params, cx| {
523 let adapter = adapter.clone();
524 let delegate = delegate.clone();
525 let this = this.clone();
526 let fs = fs.clone();
527 let mut cx = cx.clone();
528 async move {
529 let toolchains =
530 this.update(&mut cx, |this, cx| this.toolchain_store(cx))?;
531
532 let workspace_config = Self::workspace_configuration_for_adapter(
533 adapter.clone(),
534 fs.as_ref(),
535 &delegate,
536 toolchains.clone(),
537 &mut cx,
538 )
539 .await?;
540
541 Ok(params
542 .items
543 .into_iter()
544 .map(|item| {
545 if let Some(section) = &item.section {
546 workspace_config
547 .get(section)
548 .cloned()
549 .unwrap_or(serde_json::Value::Null)
550 } else {
551 workspace_config.clone()
552 }
553 })
554 .collect())
555 }
556 }
557 })
558 .detach();
559
560 language_server
561 .on_request::<lsp::request::WorkspaceFoldersRequest, _, _>({
562 let this = this.clone();
563 move |_, cx| {
564 let this = this.clone();
565 let mut cx = cx.clone();
566 async move {
567 let Some(server) = this
568 .read_with(&mut cx, |this, _| this.language_server_for_id(server_id))?
569 else {
570 return Ok(None);
571 };
572 let root = server.workspace_folders();
573 Ok(Some(
574 root.iter()
575 .cloned()
576 .map(|uri| WorkspaceFolder {
577 uri,
578 name: Default::default(),
579 })
580 .collect(),
581 ))
582 }
583 }
584 })
585 .detach();
586 // Even though we don't have handling for these requests, respond to them to
587 // avoid stalling any language server like `gopls` which waits for a response
588 // to these requests when initializing.
589 language_server
590 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
591 let this = this.clone();
592 move |params, cx| {
593 let this = this.clone();
594 let mut cx = cx.clone();
595 async move {
596 this.update(&mut cx, |this, _| {
597 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
598 {
599 if let lsp::NumberOrString::String(token) = params.token {
600 status.progress_tokens.insert(token);
601 }
602 }
603 })?;
604
605 Ok(())
606 }
607 }
608 })
609 .detach();
610
611 language_server
612 .on_request::<lsp::request::RegisterCapability, _, _>({
613 let this = this.clone();
614 move |params, cx| {
615 let this = this.clone();
616 let mut cx = cx.clone();
617 async move {
618 for reg in params.registrations {
619 match reg.method.as_str() {
620 "workspace/didChangeWatchedFiles" => {
621 if let Some(options) = reg.register_options {
622 let options = serde_json::from_value(options)?;
623 this.update(&mut cx, |this, cx| {
624 this.as_local_mut()?.on_lsp_did_change_watched_files(
625 server_id, ®.id, options, cx,
626 );
627 Some(())
628 })?;
629 }
630 }
631 "textDocument/rangeFormatting" => {
632 this.read_with(&mut cx, |this, _| {
633 if let Some(server) = this.language_server_for_id(server_id)
634 {
635 let options = reg
636 .register_options
637 .map(|options| {
638 serde_json::from_value::<
639 lsp::DocumentRangeFormattingOptions,
640 >(
641 options
642 )
643 })
644 .transpose()?;
645 let provider = match options {
646 None => OneOf::Left(true),
647 Some(options) => OneOf::Right(options),
648 };
649 server.update_capabilities(|capabilities| {
650 capabilities.document_range_formatting_provider =
651 Some(provider);
652 })
653 }
654 anyhow::Ok(())
655 })??;
656 }
657 "textDocument/onTypeFormatting" => {
658 this.read_with(&mut cx, |this, _| {
659 if let Some(server) = this.language_server_for_id(server_id)
660 {
661 let options = reg
662 .register_options
663 .map(|options| {
664 serde_json::from_value::<
665 lsp::DocumentOnTypeFormattingOptions,
666 >(
667 options
668 )
669 })
670 .transpose()?;
671 if let Some(options) = options {
672 server.update_capabilities(|capabilities| {
673 capabilities
674 .document_on_type_formatting_provider =
675 Some(options);
676 })
677 }
678 }
679 anyhow::Ok(())
680 })??;
681 }
682 "textDocument/formatting" => {
683 this.read_with(&mut cx, |this, _| {
684 if let Some(server) = this.language_server_for_id(server_id)
685 {
686 let options = reg
687 .register_options
688 .map(|options| {
689 serde_json::from_value::<
690 lsp::DocumentFormattingOptions,
691 >(
692 options
693 )
694 })
695 .transpose()?;
696 let provider = match options {
697 None => OneOf::Left(true),
698 Some(options) => OneOf::Right(options),
699 };
700 server.update_capabilities(|capabilities| {
701 capabilities.document_formatting_provider =
702 Some(provider);
703 })
704 }
705 anyhow::Ok(())
706 })??;
707 }
708 "workspace/didChangeConfiguration" => {
709 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
710 }
711 "textDocument/rename" => {
712 this.read_with(&mut cx, |this, _| {
713 if let Some(server) = this.language_server_for_id(server_id)
714 {
715 let options = reg
716 .register_options
717 .map(|options| {
718 serde_json::from_value::<lsp::RenameOptions>(
719 options,
720 )
721 })
722 .transpose()?;
723 let options = match options {
724 None => OneOf::Left(true),
725 Some(options) => OneOf::Right(options),
726 };
727
728 server.update_capabilities(|capabilities| {
729 capabilities.rename_provider = Some(options);
730 })
731 }
732 anyhow::Ok(())
733 })??;
734 }
735 _ => log::warn!("unhandled capability registration: {reg:?}"),
736 }
737 }
738 Ok(())
739 }
740 }
741 })
742 .detach();
743
744 language_server
745 .on_request::<lsp::request::UnregisterCapability, _, _>({
746 let this = this.clone();
747 move |params, cx| {
748 let this = this.clone();
749 let mut cx = cx.clone();
750 async move {
751 for unreg in params.unregisterations.iter() {
752 match unreg.method.as_str() {
753 "workspace/didChangeWatchedFiles" => {
754 this.update(&mut cx, |this, cx| {
755 this.as_local_mut()?
756 .on_lsp_unregister_did_change_watched_files(
757 server_id, &unreg.id, cx,
758 );
759 Some(())
760 })?;
761 }
762 "workspace/didChangeConfiguration" => {
763 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
764 }
765 "textDocument/rename" => {
766 this.read_with(&mut cx, |this, _| {
767 if let Some(server) = this.language_server_for_id(server_id)
768 {
769 server.update_capabilities(|capabilities| {
770 capabilities.rename_provider = None
771 })
772 }
773 })?;
774 }
775 "textDocument/rangeFormatting" => {
776 this.read_with(&mut cx, |this, _| {
777 if let Some(server) = this.language_server_for_id(server_id)
778 {
779 server.update_capabilities(|capabilities| {
780 capabilities.document_range_formatting_provider =
781 None
782 })
783 }
784 })?;
785 }
786 "textDocument/onTypeFormatting" => {
787 this.read_with(&mut cx, |this, _| {
788 if let Some(server) = this.language_server_for_id(server_id)
789 {
790 server.update_capabilities(|capabilities| {
791 capabilities.document_on_type_formatting_provider =
792 None;
793 })
794 }
795 })?;
796 }
797 "textDocument/formatting" => {
798 this.read_with(&mut cx, |this, _| {
799 if let Some(server) = this.language_server_for_id(server_id)
800 {
801 server.update_capabilities(|capabilities| {
802 capabilities.document_formatting_provider = None;
803 })
804 }
805 })?;
806 }
807 _ => log::warn!("unhandled capability unregistration: {unreg:?}"),
808 }
809 }
810 Ok(())
811 }
812 }
813 })
814 .detach();
815
816 language_server
817 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
818 let adapter = adapter.clone();
819 let this = this.clone();
820 move |params, cx| {
821 let mut cx = cx.clone();
822 let this = this.clone();
823 let adapter = adapter.clone();
824 async move {
825 LocalLspStore::on_lsp_workspace_edit(
826 this.clone(),
827 params,
828 server_id,
829 adapter.clone(),
830 &mut cx,
831 )
832 .await
833 }
834 }
835 })
836 .detach();
837
838 language_server
839 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
840 let this = this.clone();
841 move |(), cx| {
842 let this = this.clone();
843 let mut cx = cx.clone();
844 async move {
845 this.update(&mut cx, |this, cx| {
846 cx.emit(LspStoreEvent::RefreshInlayHints);
847 this.downstream_client.as_ref().map(|(client, project_id)| {
848 client.send(proto::RefreshInlayHints {
849 project_id: *project_id,
850 })
851 })
852 })?
853 .transpose()?;
854 Ok(())
855 }
856 }
857 })
858 .detach();
859
860 language_server
861 .on_request::<lsp::request::CodeLensRefresh, _, _>({
862 let this = this.clone();
863 move |(), cx| {
864 let this = this.clone();
865 let mut cx = cx.clone();
866 async move {
867 this.update(&mut cx, |this, cx| {
868 cx.emit(LspStoreEvent::RefreshCodeLens);
869 this.downstream_client.as_ref().map(|(client, project_id)| {
870 client.send(proto::RefreshCodeLens {
871 project_id: *project_id,
872 })
873 })
874 })?
875 .transpose()?;
876 Ok(())
877 }
878 }
879 })
880 .detach();
881
882 language_server
883 .on_request::<lsp::request::WorkspaceDiagnosticRefresh, _, _>({
884 let this = this.clone();
885 move |(), cx| {
886 let this = this.clone();
887 let mut cx = cx.clone();
888 async move {
889 this.update(&mut cx, |lsp_store, _| {
890 lsp_store.pull_workspace_diagnostics(server_id);
891 lsp_store
892 .downstream_client
893 .as_ref()
894 .map(|(client, project_id)| {
895 client.send(proto::PullWorkspaceDiagnostics {
896 project_id: *project_id,
897 server_id: server_id.to_proto(),
898 })
899 })
900 })?
901 .transpose()?;
902 Ok(())
903 }
904 }
905 })
906 .detach();
907
908 language_server
909 .on_request::<lsp::request::ShowMessageRequest, _, _>({
910 let this = this.clone();
911 let name = name.to_string();
912 move |params, cx| {
913 let this = this.clone();
914 let name = name.to_string();
915 let mut cx = cx.clone();
916 async move {
917 let actions = params.actions.unwrap_or_default();
918 let (tx, rx) = smol::channel::bounded(1);
919 let request = LanguageServerPromptRequest {
920 level: match params.typ {
921 lsp::MessageType::ERROR => PromptLevel::Critical,
922 lsp::MessageType::WARNING => PromptLevel::Warning,
923 _ => PromptLevel::Info,
924 },
925 message: params.message,
926 actions,
927 response_channel: tx,
928 lsp_name: name.clone(),
929 };
930
931 let did_update = this
932 .update(&mut cx, |_, cx| {
933 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
934 })
935 .is_ok();
936 if did_update {
937 let response = rx.recv().await.ok();
938 Ok(response)
939 } else {
940 Ok(None)
941 }
942 }
943 }
944 })
945 .detach();
946 language_server
947 .on_notification::<lsp::notification::ShowMessage, _>({
948 let this = this.clone();
949 let name = name.to_string();
950 move |params, cx| {
951 let this = this.clone();
952 let name = name.to_string();
953 let mut cx = cx.clone();
954
955 let (tx, _) = smol::channel::bounded(1);
956 let request = LanguageServerPromptRequest {
957 level: match params.typ {
958 lsp::MessageType::ERROR => PromptLevel::Critical,
959 lsp::MessageType::WARNING => PromptLevel::Warning,
960 _ => PromptLevel::Info,
961 },
962 message: params.message,
963 actions: vec![],
964 response_channel: tx,
965 lsp_name: name.clone(),
966 };
967
968 let _ = this.update(&mut cx, |_, cx| {
969 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
970 });
971 }
972 })
973 .detach();
974
975 let disk_based_diagnostics_progress_token =
976 adapter.disk_based_diagnostics_progress_token.clone();
977
978 language_server
979 .on_notification::<lsp::notification::Progress, _>({
980 let this = this.clone();
981 move |params, cx| {
982 if let Some(this) = this.upgrade() {
983 this.update(cx, |this, cx| {
984 this.on_lsp_progress(
985 params,
986 server_id,
987 disk_based_diagnostics_progress_token.clone(),
988 cx,
989 );
990 })
991 .ok();
992 }
993 }
994 })
995 .detach();
996
997 language_server
998 .on_notification::<lsp::notification::LogMessage, _>({
999 let this = this.clone();
1000 move |params, cx| {
1001 if let Some(this) = this.upgrade() {
1002 this.update(cx, |_, cx| {
1003 cx.emit(LspStoreEvent::LanguageServerLog(
1004 server_id,
1005 LanguageServerLogType::Log(params.typ),
1006 params.message,
1007 ));
1008 })
1009 .ok();
1010 }
1011 }
1012 })
1013 .detach();
1014
1015 language_server
1016 .on_notification::<lsp::notification::LogTrace, _>({
1017 let this = this.clone();
1018 move |params, cx| {
1019 let mut cx = cx.clone();
1020 if let Some(this) = this.upgrade() {
1021 this.update(&mut cx, |_, cx| {
1022 cx.emit(LspStoreEvent::LanguageServerLog(
1023 server_id,
1024 LanguageServerLogType::Trace(params.verbose),
1025 params.message,
1026 ));
1027 })
1028 .ok();
1029 }
1030 }
1031 })
1032 .detach();
1033
1034 rust_analyzer_ext::register_notifications(this.clone(), language_server);
1035 clangd_ext::register_notifications(this, language_server, adapter);
1036 }
1037
1038 fn shutdown_language_servers_on_quit(
1039 &mut self,
1040 _: &mut Context<LspStore>,
1041 ) -> impl Future<Output = ()> + use<> {
1042 let shutdown_futures = self
1043 .language_servers
1044 .drain()
1045 .map(|(_, server_state)| Self::shutdown_server(server_state))
1046 .collect::<Vec<_>>();
1047
1048 async move {
1049 join_all(shutdown_futures).await;
1050 }
1051 }
1052
1053 async fn shutdown_server(server_state: LanguageServerState) -> anyhow::Result<()> {
1054 match server_state {
1055 LanguageServerState::Running { server, .. } => {
1056 if let Some(shutdown) = server.shutdown() {
1057 shutdown.await;
1058 }
1059 }
1060 LanguageServerState::Starting { startup, .. } => {
1061 if let Some(server) = startup.await {
1062 if let Some(shutdown) = server.shutdown() {
1063 shutdown.await;
1064 }
1065 }
1066 }
1067 }
1068 Ok(())
1069 }
1070
1071 fn language_servers_for_worktree(
1072 &self,
1073 worktree_id: WorktreeId,
1074 ) -> impl Iterator<Item = &Arc<LanguageServer>> {
1075 self.language_server_ids
1076 .iter()
1077 .flat_map(move |((language_server_path, _), ids)| {
1078 ids.iter().filter_map(move |id| {
1079 if *language_server_path != worktree_id {
1080 return None;
1081 }
1082 if let Some(LanguageServerState::Running { server, .. }) =
1083 self.language_servers.get(id)
1084 {
1085 return Some(server);
1086 } else {
1087 None
1088 }
1089 })
1090 })
1091 }
1092
1093 fn language_server_ids_for_project_path(
1094 &self,
1095 project_path: ProjectPath,
1096 language: &Language,
1097 cx: &mut App,
1098 ) -> Vec<LanguageServerId> {
1099 let Some(worktree) = self
1100 .worktree_store
1101 .read(cx)
1102 .worktree_for_id(project_path.worktree_id, cx)
1103 else {
1104 return Vec::new();
1105 };
1106 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
1107 let root = self.lsp_tree.update(cx, |this, cx| {
1108 this.get(
1109 project_path,
1110 AdapterQuery::Language(&language.name()),
1111 delegate,
1112 cx,
1113 )
1114 .filter_map(|node| node.server_id())
1115 .collect::<Vec<_>>()
1116 });
1117
1118 root
1119 }
1120
1121 fn language_server_ids_for_buffer(
1122 &self,
1123 buffer: &Buffer,
1124 cx: &mut App,
1125 ) -> Vec<LanguageServerId> {
1126 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
1127 let worktree_id = file.worktree_id(cx);
1128
1129 let path: Arc<Path> = file
1130 .path()
1131 .parent()
1132 .map(Arc::from)
1133 .unwrap_or_else(|| file.path().clone());
1134 let worktree_path = ProjectPath { worktree_id, path };
1135 self.language_server_ids_for_project_path(worktree_path, language, cx)
1136 } else {
1137 Vec::new()
1138 }
1139 }
1140
1141 fn language_servers_for_buffer<'a>(
1142 &'a self,
1143 buffer: &'a Buffer,
1144 cx: &'a mut App,
1145 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1146 self.language_server_ids_for_buffer(buffer, cx)
1147 .into_iter()
1148 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
1149 LanguageServerState::Running {
1150 adapter, server, ..
1151 } => Some((adapter, server)),
1152 _ => None,
1153 })
1154 }
1155
1156 async fn execute_code_action_kind_locally(
1157 lsp_store: WeakEntity<LspStore>,
1158 mut buffers: Vec<Entity<Buffer>>,
1159 kind: CodeActionKind,
1160 push_to_history: bool,
1161 cx: &mut AsyncApp,
1162 ) -> anyhow::Result<ProjectTransaction> {
1163 // Do not allow multiple concurrent code actions requests for the
1164 // same buffer.
1165 lsp_store.update(cx, |this, cx| {
1166 let this = this.as_local_mut().unwrap();
1167 buffers.retain(|buffer| {
1168 this.buffers_being_formatted
1169 .insert(buffer.read(cx).remote_id())
1170 });
1171 })?;
1172 let _cleanup = defer({
1173 let this = lsp_store.clone();
1174 let mut cx = cx.clone();
1175 let buffers = &buffers;
1176 move || {
1177 this.update(&mut cx, |this, cx| {
1178 let this = this.as_local_mut().unwrap();
1179 for buffer in buffers {
1180 this.buffers_being_formatted
1181 .remove(&buffer.read(cx).remote_id());
1182 }
1183 })
1184 .ok();
1185 }
1186 });
1187 let mut project_transaction = ProjectTransaction::default();
1188
1189 for buffer in &buffers {
1190 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1191 buffer.update(cx, |buffer, cx| {
1192 lsp_store
1193 .as_local()
1194 .unwrap()
1195 .language_servers_for_buffer(buffer, cx)
1196 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1197 .collect::<Vec<_>>()
1198 })
1199 })?;
1200 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
1201 let actions = Self::get_server_code_actions_from_action_kinds(
1202 &lsp_store,
1203 language_server.server_id(),
1204 vec![kind.clone()],
1205 buffer,
1206 cx,
1207 )
1208 .await?;
1209 Self::execute_code_actions_on_server(
1210 &lsp_store,
1211 language_server,
1212 lsp_adapter,
1213 actions,
1214 push_to_history,
1215 &mut project_transaction,
1216 cx,
1217 )
1218 .await?;
1219 }
1220 }
1221 Ok(project_transaction)
1222 }
1223
1224 async fn format_locally(
1225 lsp_store: WeakEntity<LspStore>,
1226 mut buffers: Vec<FormattableBuffer>,
1227 push_to_history: bool,
1228 trigger: FormatTrigger,
1229 logger: zlog::Logger,
1230 cx: &mut AsyncApp,
1231 ) -> anyhow::Result<ProjectTransaction> {
1232 // Do not allow multiple concurrent formatting requests for the
1233 // same buffer.
1234 lsp_store.update(cx, |this, cx| {
1235 let this = this.as_local_mut().unwrap();
1236 buffers.retain(|buffer| {
1237 this.buffers_being_formatted
1238 .insert(buffer.handle.read(cx).remote_id())
1239 });
1240 })?;
1241
1242 let _cleanup = defer({
1243 let this = lsp_store.clone();
1244 let mut cx = cx.clone();
1245 let buffers = &buffers;
1246 move || {
1247 this.update(&mut cx, |this, cx| {
1248 let this = this.as_local_mut().unwrap();
1249 for buffer in buffers {
1250 this.buffers_being_formatted
1251 .remove(&buffer.handle.read(cx).remote_id());
1252 }
1253 })
1254 .ok();
1255 }
1256 });
1257
1258 let mut project_transaction = ProjectTransaction::default();
1259
1260 for buffer in &buffers {
1261 zlog::debug!(
1262 logger =>
1263 "formatting buffer '{:?}'",
1264 buffer.abs_path.as_ref().unwrap_or(&PathBuf::from("unknown")).display()
1265 );
1266 // Create an empty transaction to hold all of the formatting edits.
1267 let formatting_transaction_id = buffer.handle.update(cx, |buffer, cx| {
1268 // ensure no transactions created while formatting are
1269 // grouped with the previous transaction in the history
1270 // based on the transaction group interval
1271 buffer.finalize_last_transaction();
1272 let transaction_id = buffer
1273 .start_transaction()
1274 .context("transaction already open")?;
1275 let transaction = buffer
1276 .get_transaction(transaction_id)
1277 .expect("transaction started")
1278 .clone();
1279 buffer.end_transaction(cx);
1280 buffer.push_transaction(transaction, cx.background_executor().now());
1281 buffer.finalize_last_transaction();
1282 anyhow::Ok(transaction_id)
1283 })??;
1284
1285 let result = Self::format_buffer_locally(
1286 lsp_store.clone(),
1287 buffer,
1288 formatting_transaction_id,
1289 trigger,
1290 logger,
1291 cx,
1292 )
1293 .await;
1294
1295 buffer.handle.update(cx, |buffer, cx| {
1296 let Some(formatting_transaction) =
1297 buffer.get_transaction(formatting_transaction_id).cloned()
1298 else {
1299 zlog::warn!(logger => "no formatting transaction");
1300 return;
1301 };
1302 if formatting_transaction.edit_ids.is_empty() {
1303 zlog::debug!(logger => "no changes made while formatting");
1304 buffer.forget_transaction(formatting_transaction_id);
1305 return;
1306 }
1307 if !push_to_history {
1308 zlog::trace!(logger => "forgetting format transaction");
1309 buffer.forget_transaction(formatting_transaction.id);
1310 }
1311 project_transaction
1312 .0
1313 .insert(cx.entity(), formatting_transaction);
1314 })?;
1315
1316 result?;
1317 }
1318
1319 Ok(project_transaction)
1320 }
1321
1322 async fn format_buffer_locally(
1323 lsp_store: WeakEntity<LspStore>,
1324 buffer: &FormattableBuffer,
1325 formatting_transaction_id: clock::Lamport,
1326 trigger: FormatTrigger,
1327 logger: zlog::Logger,
1328 cx: &mut AsyncApp,
1329 ) -> Result<()> {
1330 let (adapters_and_servers, settings) = lsp_store.update(cx, |lsp_store, cx| {
1331 buffer.handle.update(cx, |buffer, cx| {
1332 let adapters_and_servers = lsp_store
1333 .as_local()
1334 .unwrap()
1335 .language_servers_for_buffer(buffer, cx)
1336 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1337 .collect::<Vec<_>>();
1338 let settings =
1339 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
1340 .into_owned();
1341 (adapters_and_servers, settings)
1342 })
1343 })?;
1344
1345 /// Apply edits to the buffer that will become part of the formatting transaction.
1346 /// Fails if the buffer has been edited since the start of that transaction.
1347 fn extend_formatting_transaction(
1348 buffer: &FormattableBuffer,
1349 formatting_transaction_id: text::TransactionId,
1350 cx: &mut AsyncApp,
1351 operation: impl FnOnce(&mut Buffer, &mut Context<Buffer>),
1352 ) -> anyhow::Result<()> {
1353 buffer.handle.update(cx, |buffer, cx| {
1354 let last_transaction_id = buffer.peek_undo_stack().map(|t| t.transaction_id());
1355 if last_transaction_id != Some(formatting_transaction_id) {
1356 anyhow::bail!("Buffer edited while formatting. Aborting")
1357 }
1358 buffer.start_transaction();
1359 operation(buffer, cx);
1360 if let Some(transaction_id) = buffer.end_transaction(cx) {
1361 buffer.merge_transactions(transaction_id, formatting_transaction_id);
1362 }
1363 Ok(())
1364 })?
1365 }
1366
1367 // handle whitespace formatting
1368 if settings.remove_trailing_whitespace_on_save {
1369 zlog::trace!(logger => "removing trailing whitespace");
1370 let diff = buffer
1371 .handle
1372 .read_with(cx, |buffer, cx| buffer.remove_trailing_whitespace(cx))?
1373 .await;
1374 extend_formatting_transaction(buffer, formatting_transaction_id, cx, |buffer, cx| {
1375 buffer.apply_diff(diff, cx);
1376 })?;
1377 }
1378
1379 if settings.ensure_final_newline_on_save {
1380 zlog::trace!(logger => "ensuring final newline");
1381 extend_formatting_transaction(buffer, formatting_transaction_id, cx, |buffer, cx| {
1382 buffer.ensure_final_newline(cx);
1383 })?;
1384 }
1385
1386 // Formatter for `code_actions_on_format` that runs before
1387 // the rest of the formatters
1388 let mut code_actions_on_format_formatter = None;
1389 let should_run_code_actions_on_format = !matches!(
1390 (trigger, &settings.format_on_save),
1391 (FormatTrigger::Save, &FormatOnSave::Off)
1392 );
1393 if should_run_code_actions_on_format {
1394 let have_code_actions_to_run_on_format = settings
1395 .code_actions_on_format
1396 .values()
1397 .any(|enabled| *enabled);
1398 if have_code_actions_to_run_on_format {
1399 zlog::trace!(logger => "going to run code actions on format");
1400 code_actions_on_format_formatter = Some(Formatter::CodeActions(
1401 settings.code_actions_on_format.clone(),
1402 ));
1403 }
1404 }
1405
1406 let formatters = match (trigger, &settings.format_on_save) {
1407 (FormatTrigger::Save, FormatOnSave::Off) => &[],
1408 (FormatTrigger::Save, FormatOnSave::List(formatters)) => formatters.as_ref(),
1409 (FormatTrigger::Manual, _) | (FormatTrigger::Save, FormatOnSave::On) => {
1410 match &settings.formatter {
1411 SelectedFormatter::Auto => {
1412 if settings.prettier.allowed {
1413 zlog::trace!(logger => "Formatter set to auto: defaulting to prettier");
1414 std::slice::from_ref(&Formatter::Prettier)
1415 } else {
1416 zlog::trace!(logger => "Formatter set to auto: defaulting to primary language server");
1417 std::slice::from_ref(&Formatter::LanguageServer { name: None })
1418 }
1419 }
1420 SelectedFormatter::List(formatter_list) => formatter_list.as_ref(),
1421 }
1422 }
1423 };
1424
1425 let formatters = code_actions_on_format_formatter.iter().chain(formatters);
1426
1427 for formatter in formatters {
1428 match formatter {
1429 Formatter::Prettier => {
1430 let logger = zlog::scoped!(logger => "prettier");
1431 zlog::trace!(logger => "formatting");
1432 let _timer = zlog::time!(logger => "Formatting buffer via prettier");
1433
1434 let prettier = lsp_store.read_with(cx, |lsp_store, _cx| {
1435 lsp_store.prettier_store().unwrap().downgrade()
1436 })?;
1437 let diff = prettier_store::format_with_prettier(&prettier, &buffer.handle, cx)
1438 .await
1439 .transpose()?;
1440 let Some(diff) = diff else {
1441 zlog::trace!(logger => "No changes");
1442 continue;
1443 };
1444
1445 extend_formatting_transaction(
1446 buffer,
1447 formatting_transaction_id,
1448 cx,
1449 |buffer, cx| {
1450 buffer.apply_diff(diff, cx);
1451 },
1452 )?;
1453 }
1454 Formatter::External { command, arguments } => {
1455 let logger = zlog::scoped!(logger => "command");
1456 zlog::trace!(logger => "formatting");
1457 let _timer = zlog::time!(logger => "Formatting buffer via external command");
1458
1459 let diff = Self::format_via_external_command(
1460 buffer,
1461 command.as_ref(),
1462 arguments.as_deref(),
1463 cx,
1464 )
1465 .await
1466 .with_context(|| {
1467 format!("Failed to format buffer via external command: {}", command)
1468 })?;
1469 let Some(diff) = diff else {
1470 zlog::trace!(logger => "No changes");
1471 continue;
1472 };
1473
1474 extend_formatting_transaction(
1475 buffer,
1476 formatting_transaction_id,
1477 cx,
1478 |buffer, cx| {
1479 buffer.apply_diff(diff, cx);
1480 },
1481 )?;
1482 }
1483 Formatter::LanguageServer { name } => {
1484 let logger = zlog::scoped!(logger => "language-server");
1485 zlog::trace!(logger => "formatting");
1486 let _timer = zlog::time!(logger => "Formatting buffer using language server");
1487
1488 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1489 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using language servers. Skipping");
1490 continue;
1491 };
1492
1493 let language_server = if let Some(name) = name.as_deref() {
1494 adapters_and_servers.iter().find_map(|(adapter, server)| {
1495 if adapter.name.0.as_ref() == name {
1496 Some(server.clone())
1497 } else {
1498 None
1499 }
1500 })
1501 } else {
1502 adapters_and_servers.first().map(|e| e.1.clone())
1503 };
1504
1505 let Some(language_server) = language_server else {
1506 log::debug!(
1507 "No language server found to format buffer '{:?}'. Skipping",
1508 buffer_path_abs.as_path().to_string_lossy()
1509 );
1510 continue;
1511 };
1512
1513 zlog::trace!(
1514 logger =>
1515 "Formatting buffer '{:?}' using language server '{:?}'",
1516 buffer_path_abs.as_path().to_string_lossy(),
1517 language_server.name()
1518 );
1519
1520 let edits = if let Some(ranges) = buffer.ranges.as_ref() {
1521 zlog::trace!(logger => "formatting ranges");
1522 Self::format_ranges_via_lsp(
1523 &lsp_store,
1524 &buffer.handle,
1525 ranges,
1526 buffer_path_abs,
1527 &language_server,
1528 &settings,
1529 cx,
1530 )
1531 .await
1532 .context("Failed to format ranges via language server")?
1533 } else {
1534 zlog::trace!(logger => "formatting full");
1535 Self::format_via_lsp(
1536 &lsp_store,
1537 &buffer.handle,
1538 buffer_path_abs,
1539 &language_server,
1540 &settings,
1541 cx,
1542 )
1543 .await
1544 .context("failed to format via language server")?
1545 };
1546
1547 if edits.is_empty() {
1548 zlog::trace!(logger => "No changes");
1549 continue;
1550 }
1551 extend_formatting_transaction(
1552 buffer,
1553 formatting_transaction_id,
1554 cx,
1555 |buffer, cx| {
1556 buffer.edit(edits, None, cx);
1557 },
1558 )?;
1559 }
1560 Formatter::CodeActions(code_actions) => {
1561 let logger = zlog::scoped!(logger => "code-actions");
1562 zlog::trace!(logger => "formatting");
1563 let _timer = zlog::time!(logger => "Formatting buffer using code actions");
1564
1565 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1566 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using code actions. Skipping");
1567 continue;
1568 };
1569 let code_action_kinds = code_actions
1570 .iter()
1571 .filter_map(|(action_kind, enabled)| {
1572 enabled.then_some(action_kind.clone().into())
1573 })
1574 .collect::<Vec<_>>();
1575 if code_action_kinds.is_empty() {
1576 zlog::trace!(logger => "No code action kinds enabled, skipping");
1577 continue;
1578 }
1579 zlog::trace!(logger => "Attempting to resolve code actions {:?}", &code_action_kinds);
1580
1581 let mut actions_and_servers = Vec::new();
1582
1583 for (index, (_, language_server)) in adapters_and_servers.iter().enumerate() {
1584 let actions_result = Self::get_server_code_actions_from_action_kinds(
1585 &lsp_store,
1586 language_server.server_id(),
1587 code_action_kinds.clone(),
1588 &buffer.handle,
1589 cx,
1590 )
1591 .await
1592 .with_context(
1593 || format!("Failed to resolve code actions with kinds {:?} for language server {}",
1594 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1595 language_server.name())
1596 );
1597 let Ok(actions) = actions_result else {
1598 // note: it may be better to set result to the error and break formatters here
1599 // but for now we try to execute the actions that we can resolve and skip the rest
1600 zlog::error!(
1601 logger =>
1602 "Failed to resolve code actions with kinds {:?} with language server {}",
1603 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1604 language_server.name()
1605 );
1606 continue;
1607 };
1608 for action in actions {
1609 actions_and_servers.push((action, index));
1610 }
1611 }
1612
1613 if actions_and_servers.is_empty() {
1614 zlog::warn!(logger => "No code actions were resolved, continuing");
1615 continue;
1616 }
1617
1618 'actions: for (mut action, server_index) in actions_and_servers {
1619 let server = &adapters_and_servers[server_index].1;
1620
1621 let describe_code_action = |action: &CodeAction| {
1622 format!(
1623 "code action '{}' with title \"{}\" on server {}",
1624 action
1625 .lsp_action
1626 .action_kind()
1627 .unwrap_or("unknown".into())
1628 .as_str(),
1629 action.lsp_action.title(),
1630 server.name(),
1631 )
1632 };
1633
1634 zlog::trace!(logger => "Executing {}", describe_code_action(&action));
1635
1636 if let Err(err) = Self::try_resolve_code_action(server, &mut action).await {
1637 zlog::error!(
1638 logger =>
1639 "Failed to resolve {}. Error: {}",
1640 describe_code_action(&action),
1641 err
1642 );
1643 continue;
1644 }
1645
1646 if let Some(edit) = action.lsp_action.edit().cloned() {
1647 // NOTE: code below duplicated from `Self::deserialize_workspace_edit`
1648 // but filters out and logs warnings for code actions that cause unreasonably
1649 // difficult handling on our part, such as:
1650 // - applying edits that call commands
1651 // which can result in arbitrary workspace edits being sent from the server that
1652 // have no way of being tied back to the command that initiated them (i.e. we
1653 // can't know which edits are part of the format request, or if the server is done sending
1654 // actions in response to the command)
1655 // - actions that create/delete/modify/rename files other than the one we are formatting
1656 // as we then would need to handle such changes correctly in the local history as well
1657 // as the remote history through the ProjectTransaction
1658 // - actions with snippet edits, as these simply don't make sense in the context of a format request
1659 // Supporting these actions is not impossible, but not supported as of yet.
1660 if edit.changes.is_none() && edit.document_changes.is_none() {
1661 zlog::trace!(
1662 logger =>
1663 "No changes for code action. Skipping {}",
1664 describe_code_action(&action),
1665 );
1666 continue;
1667 }
1668
1669 let mut operations = Vec::new();
1670 if let Some(document_changes) = edit.document_changes {
1671 match document_changes {
1672 lsp::DocumentChanges::Edits(edits) => operations.extend(
1673 edits.into_iter().map(lsp::DocumentChangeOperation::Edit),
1674 ),
1675 lsp::DocumentChanges::Operations(ops) => operations = ops,
1676 }
1677 } else if let Some(changes) = edit.changes {
1678 operations.extend(changes.into_iter().map(|(uri, edits)| {
1679 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1680 text_document:
1681 lsp::OptionalVersionedTextDocumentIdentifier {
1682 uri,
1683 version: None,
1684 },
1685 edits: edits.into_iter().map(Edit::Plain).collect(),
1686 })
1687 }));
1688 }
1689
1690 let mut edits = Vec::with_capacity(operations.len());
1691
1692 if operations.is_empty() {
1693 zlog::trace!(
1694 logger =>
1695 "No changes for code action. Skipping {}",
1696 describe_code_action(&action),
1697 );
1698 continue;
1699 }
1700 for operation in operations {
1701 let op = match operation {
1702 lsp::DocumentChangeOperation::Edit(op) => op,
1703 lsp::DocumentChangeOperation::Op(_) => {
1704 zlog::warn!(
1705 logger =>
1706 "Code actions which create, delete, or rename files are not supported on format. Skipping {}",
1707 describe_code_action(&action),
1708 );
1709 continue 'actions;
1710 }
1711 };
1712 let Ok(file_path) = op.text_document.uri.to_file_path() else {
1713 zlog::warn!(
1714 logger =>
1715 "Failed to convert URI '{:?}' to file path. Skipping {}",
1716 &op.text_document.uri,
1717 describe_code_action(&action),
1718 );
1719 continue 'actions;
1720 };
1721 if &file_path != buffer_path_abs {
1722 zlog::warn!(
1723 logger =>
1724 "File path '{:?}' does not match buffer path '{:?}'. Skipping {}",
1725 file_path,
1726 buffer_path_abs,
1727 describe_code_action(&action),
1728 );
1729 continue 'actions;
1730 }
1731
1732 let mut lsp_edits = Vec::new();
1733 for edit in op.edits {
1734 match edit {
1735 Edit::Plain(edit) => {
1736 if !lsp_edits.contains(&edit) {
1737 lsp_edits.push(edit);
1738 }
1739 }
1740 Edit::Annotated(edit) => {
1741 if !lsp_edits.contains(&edit.text_edit) {
1742 lsp_edits.push(edit.text_edit);
1743 }
1744 }
1745 Edit::Snippet(_) => {
1746 zlog::warn!(
1747 logger =>
1748 "Code actions which produce snippet edits are not supported during formatting. Skipping {}",
1749 describe_code_action(&action),
1750 );
1751 continue 'actions;
1752 }
1753 }
1754 }
1755 let edits_result = lsp_store
1756 .update(cx, |lsp_store, cx| {
1757 lsp_store.as_local_mut().unwrap().edits_from_lsp(
1758 &buffer.handle,
1759 lsp_edits,
1760 server.server_id(),
1761 op.text_document.version,
1762 cx,
1763 )
1764 })?
1765 .await;
1766 let Ok(resolved_edits) = edits_result else {
1767 zlog::warn!(
1768 logger =>
1769 "Failed to resolve edits from LSP for buffer {:?} while handling {}",
1770 buffer_path_abs.as_path(),
1771 describe_code_action(&action),
1772 );
1773 continue 'actions;
1774 };
1775 edits.extend(resolved_edits);
1776 }
1777
1778 if edits.is_empty() {
1779 zlog::warn!(logger => "No edits resolved from LSP");
1780 continue;
1781 }
1782
1783 extend_formatting_transaction(
1784 buffer,
1785 formatting_transaction_id,
1786 cx,
1787 |buffer, cx| {
1788 buffer.edit(edits, None, cx);
1789 },
1790 )?;
1791 }
1792
1793 if let Some(command) = action.lsp_action.command() {
1794 zlog::warn!(
1795 logger =>
1796 "Executing code action command '{}'. This may cause formatting to abort unnecessarily as well as splitting formatting into two entries in the undo history",
1797 &command.command,
1798 );
1799
1800 // bail early if command is invalid
1801 let server_capabilities = server.capabilities();
1802 let available_commands = server_capabilities
1803 .execute_command_provider
1804 .as_ref()
1805 .map(|options| options.commands.as_slice())
1806 .unwrap_or_default();
1807 if !available_commands.contains(&command.command) {
1808 zlog::warn!(
1809 logger =>
1810 "Cannot execute a command {} not listed in the language server capabilities of server {}",
1811 command.command,
1812 server.name(),
1813 );
1814 continue;
1815 }
1816
1817 // noop so we just ensure buffer hasn't been edited since resolving code actions
1818 extend_formatting_transaction(
1819 buffer,
1820 formatting_transaction_id,
1821 cx,
1822 |_, _| {},
1823 )?;
1824 zlog::info!(logger => "Executing command {}", &command.command);
1825
1826 lsp_store.update(cx, |this, _| {
1827 this.as_local_mut()
1828 .unwrap()
1829 .last_workspace_edits_by_language_server
1830 .remove(&server.server_id());
1831 })?;
1832
1833 let execute_command_result = server
1834 .request::<lsp::request::ExecuteCommand>(
1835 lsp::ExecuteCommandParams {
1836 command: command.command.clone(),
1837 arguments: command.arguments.clone().unwrap_or_default(),
1838 ..Default::default()
1839 },
1840 )
1841 .await
1842 .into_response();
1843
1844 if execute_command_result.is_err() {
1845 zlog::error!(
1846 logger =>
1847 "Failed to execute command '{}' as part of {}",
1848 &command.command,
1849 describe_code_action(&action),
1850 );
1851 continue 'actions;
1852 }
1853
1854 let mut project_transaction_command =
1855 lsp_store.update(cx, |this, _| {
1856 this.as_local_mut()
1857 .unwrap()
1858 .last_workspace_edits_by_language_server
1859 .remove(&server.server_id())
1860 .unwrap_or_default()
1861 })?;
1862
1863 if let Some(transaction) =
1864 project_transaction_command.0.remove(&buffer.handle)
1865 {
1866 zlog::trace!(
1867 logger =>
1868 "Successfully captured {} edits that resulted from command {}",
1869 transaction.edit_ids.len(),
1870 &command.command,
1871 );
1872 let transaction_id_project_transaction = transaction.id;
1873 buffer.handle.update(cx, |buffer, _| {
1874 // it may have been removed from history if push_to_history was
1875 // false in deserialize_workspace_edit. If so push it so we
1876 // can merge it with the format transaction
1877 // and pop the combined transaction off the history stack
1878 // later if push_to_history is false
1879 if buffer.get_transaction(transaction.id).is_none() {
1880 buffer.push_transaction(transaction, Instant::now());
1881 }
1882 buffer.merge_transactions(
1883 transaction_id_project_transaction,
1884 formatting_transaction_id,
1885 );
1886 })?;
1887 }
1888
1889 if !project_transaction_command.0.is_empty() {
1890 let extra_buffers = project_transaction_command
1891 .0
1892 .keys()
1893 .filter_map(|buffer_handle| {
1894 buffer_handle
1895 .read_with(cx, |b, cx| b.project_path(cx))
1896 .ok()
1897 .flatten()
1898 })
1899 .map(|p| p.path.to_sanitized_string())
1900 .join(", ");
1901 zlog::warn!(
1902 logger =>
1903 "Unexpected edits to buffers other than the buffer actively being formatted due to command {}. Impacted buffers: [{}].",
1904 &command.command,
1905 extra_buffers,
1906 );
1907 // NOTE: if this case is hit, the proper thing to do is to for each buffer, merge the extra transaction
1908 // into the existing transaction in project_transaction if there is one, and if there isn't one in project_transaction,
1909 // add it so it's included, and merge it into the format transaction when its created later
1910 }
1911 }
1912 }
1913 }
1914 }
1915 }
1916
1917 Ok(())
1918 }
1919
1920 pub async fn format_ranges_via_lsp(
1921 this: &WeakEntity<LspStore>,
1922 buffer_handle: &Entity<Buffer>,
1923 ranges: &[Range<Anchor>],
1924 abs_path: &Path,
1925 language_server: &Arc<LanguageServer>,
1926 settings: &LanguageSettings,
1927 cx: &mut AsyncApp,
1928 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1929 let capabilities = &language_server.capabilities();
1930 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1931 if range_formatting_provider.map_or(false, |provider| provider == &OneOf::Left(false)) {
1932 anyhow::bail!(
1933 "{} language server does not support range formatting",
1934 language_server.name()
1935 );
1936 }
1937
1938 let uri = file_path_to_lsp_url(abs_path)?;
1939 let text_document = lsp::TextDocumentIdentifier::new(uri);
1940
1941 let lsp_edits = {
1942 let mut lsp_ranges = Vec::new();
1943 this.update(cx, |_this, cx| {
1944 // TODO(#22930): In the case of formatting multibuffer selections, this buffer may
1945 // not have been sent to the language server. This seems like a fairly systemic
1946 // issue, though, the resolution probably is not specific to formatting.
1947 //
1948 // TODO: Instead of using current snapshot, should use the latest snapshot sent to
1949 // LSP.
1950 let snapshot = buffer_handle.read(cx).snapshot();
1951 for range in ranges {
1952 lsp_ranges.push(range_to_lsp(range.to_point_utf16(&snapshot))?);
1953 }
1954 anyhow::Ok(())
1955 })??;
1956
1957 let mut edits = None;
1958 for range in lsp_ranges {
1959 if let Some(mut edit) = language_server
1960 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1961 text_document: text_document.clone(),
1962 range,
1963 options: lsp_command::lsp_formatting_options(settings),
1964 work_done_progress_params: Default::default(),
1965 })
1966 .await
1967 .into_response()?
1968 {
1969 edits.get_or_insert_with(Vec::new).append(&mut edit);
1970 }
1971 }
1972 edits
1973 };
1974
1975 if let Some(lsp_edits) = lsp_edits {
1976 this.update(cx, |this, cx| {
1977 this.as_local_mut().unwrap().edits_from_lsp(
1978 &buffer_handle,
1979 lsp_edits,
1980 language_server.server_id(),
1981 None,
1982 cx,
1983 )
1984 })?
1985 .await
1986 } else {
1987 Ok(Vec::with_capacity(0))
1988 }
1989 }
1990
1991 async fn format_via_lsp(
1992 this: &WeakEntity<LspStore>,
1993 buffer: &Entity<Buffer>,
1994 abs_path: &Path,
1995 language_server: &Arc<LanguageServer>,
1996 settings: &LanguageSettings,
1997 cx: &mut AsyncApp,
1998 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1999 let logger = zlog::scoped!("lsp_format");
2000 zlog::info!(logger => "Formatting via LSP");
2001
2002 let uri = file_path_to_lsp_url(abs_path)?;
2003 let text_document = lsp::TextDocumentIdentifier::new(uri);
2004 let capabilities = &language_server.capabilities();
2005
2006 let formatting_provider = capabilities.document_formatting_provider.as_ref();
2007 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
2008
2009 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
2010 let _timer = zlog::time!(logger => "format-full");
2011 language_server
2012 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2013 text_document,
2014 options: lsp_command::lsp_formatting_options(settings),
2015 work_done_progress_params: Default::default(),
2016 })
2017 .await
2018 .into_response()?
2019 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
2020 let _timer = zlog::time!(logger => "format-range");
2021 let buffer_start = lsp::Position::new(0, 0);
2022 let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
2023 language_server
2024 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2025 text_document: text_document.clone(),
2026 range: lsp::Range::new(buffer_start, buffer_end),
2027 options: lsp_command::lsp_formatting_options(settings),
2028 work_done_progress_params: Default::default(),
2029 })
2030 .await
2031 .into_response()?
2032 } else {
2033 None
2034 };
2035
2036 if let Some(lsp_edits) = lsp_edits {
2037 this.update(cx, |this, cx| {
2038 this.as_local_mut().unwrap().edits_from_lsp(
2039 buffer,
2040 lsp_edits,
2041 language_server.server_id(),
2042 None,
2043 cx,
2044 )
2045 })?
2046 .await
2047 } else {
2048 Ok(Vec::with_capacity(0))
2049 }
2050 }
2051
2052 async fn format_via_external_command(
2053 buffer: &FormattableBuffer,
2054 command: &str,
2055 arguments: Option<&[String]>,
2056 cx: &mut AsyncApp,
2057 ) -> Result<Option<Diff>> {
2058 let working_dir_path = buffer.handle.update(cx, |buffer, cx| {
2059 let file = File::from_dyn(buffer.file())?;
2060 let worktree = file.worktree.read(cx);
2061 let mut worktree_path = worktree.abs_path().to_path_buf();
2062 if worktree.root_entry()?.is_file() {
2063 worktree_path.pop();
2064 }
2065 Some(worktree_path)
2066 })?;
2067
2068 let mut child = util::command::new_smol_command(command);
2069
2070 if let Some(buffer_env) = buffer.env.as_ref() {
2071 child.envs(buffer_env);
2072 }
2073
2074 if let Some(working_dir_path) = working_dir_path {
2075 child.current_dir(working_dir_path);
2076 }
2077
2078 if let Some(arguments) = arguments {
2079 child.args(arguments.iter().map(|arg| {
2080 if let Some(buffer_abs_path) = buffer.abs_path.as_ref() {
2081 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2082 } else {
2083 arg.replace("{buffer_path}", "Untitled")
2084 }
2085 }));
2086 }
2087
2088 let mut child = child
2089 .stdin(smol::process::Stdio::piped())
2090 .stdout(smol::process::Stdio::piped())
2091 .stderr(smol::process::Stdio::piped())
2092 .spawn()?;
2093
2094 let stdin = child.stdin.as_mut().context("failed to acquire stdin")?;
2095 let text = buffer
2096 .handle
2097 .read_with(cx, |buffer, _| buffer.as_rope().clone())?;
2098 for chunk in text.chunks() {
2099 stdin.write_all(chunk.as_bytes()).await?;
2100 }
2101 stdin.flush().await?;
2102
2103 let output = child.output().await?;
2104 anyhow::ensure!(
2105 output.status.success(),
2106 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
2107 output.status.code(),
2108 String::from_utf8_lossy(&output.stdout),
2109 String::from_utf8_lossy(&output.stderr),
2110 );
2111
2112 let stdout = String::from_utf8(output.stdout)?;
2113 Ok(Some(
2114 buffer
2115 .handle
2116 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
2117 .await,
2118 ))
2119 }
2120
2121 async fn try_resolve_code_action(
2122 lang_server: &LanguageServer,
2123 action: &mut CodeAction,
2124 ) -> anyhow::Result<()> {
2125 match &mut action.lsp_action {
2126 LspAction::Action(lsp_action) => {
2127 if !action.resolved
2128 && GetCodeActions::can_resolve_actions(&lang_server.capabilities())
2129 && lsp_action.data.is_some()
2130 && (lsp_action.command.is_none() || lsp_action.edit.is_none())
2131 {
2132 *lsp_action = Box::new(
2133 lang_server
2134 .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
2135 .await
2136 .into_response()?,
2137 );
2138 }
2139 }
2140 LspAction::CodeLens(lens) => {
2141 if !action.resolved && GetCodeLens::can_resolve_lens(&lang_server.capabilities()) {
2142 *lens = lang_server
2143 .request::<lsp::request::CodeLensResolve>(lens.clone())
2144 .await
2145 .into_response()?;
2146 }
2147 }
2148 LspAction::Command(_) => {}
2149 }
2150
2151 action.resolved = true;
2152 anyhow::Ok(())
2153 }
2154
2155 fn initialize_buffer(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<LspStore>) {
2156 let buffer = buffer_handle.read(cx);
2157
2158 let file = buffer.file().cloned();
2159 let Some(file) = File::from_dyn(file.as_ref()) else {
2160 return;
2161 };
2162 if !file.is_local() {
2163 return;
2164 }
2165
2166 let worktree_id = file.worktree_id(cx);
2167 let language = buffer.language().cloned();
2168
2169 if let Some(diagnostics) = self.diagnostics.get(&worktree_id) {
2170 for (server_id, diagnostics) in
2171 diagnostics.get(file.path()).cloned().unwrap_or_default()
2172 {
2173 self.update_buffer_diagnostics(
2174 buffer_handle,
2175 server_id,
2176 None,
2177 None,
2178 diagnostics,
2179 Vec::new(),
2180 cx,
2181 )
2182 .log_err();
2183 }
2184 }
2185 let Some(language) = language else {
2186 return;
2187 };
2188 for adapter in self.languages.lsp_adapters(&language.name()) {
2189 let servers = self
2190 .language_server_ids
2191 .get(&(worktree_id, adapter.name.clone()));
2192 if let Some(server_ids) = servers {
2193 for server_id in server_ids {
2194 let server = self
2195 .language_servers
2196 .get(server_id)
2197 .and_then(|server_state| {
2198 if let LanguageServerState::Running { server, .. } = server_state {
2199 Some(server.clone())
2200 } else {
2201 None
2202 }
2203 });
2204 let server = match server {
2205 Some(server) => server,
2206 None => continue,
2207 };
2208
2209 buffer_handle.update(cx, |buffer, cx| {
2210 buffer.set_completion_triggers(
2211 server.server_id(),
2212 server
2213 .capabilities()
2214 .completion_provider
2215 .as_ref()
2216 .and_then(|provider| {
2217 provider
2218 .trigger_characters
2219 .as_ref()
2220 .map(|characters| characters.iter().cloned().collect())
2221 })
2222 .unwrap_or_default(),
2223 cx,
2224 );
2225 });
2226 }
2227 }
2228 }
2229 }
2230
2231 pub(crate) fn reset_buffer(&mut self, buffer: &Entity<Buffer>, old_file: &File, cx: &mut App) {
2232 buffer.update(cx, |buffer, cx| {
2233 let Some(language) = buffer.language() else {
2234 return;
2235 };
2236 let path = ProjectPath {
2237 worktree_id: old_file.worktree_id(cx),
2238 path: old_file.path.clone(),
2239 };
2240 for server_id in self.language_server_ids_for_project_path(path, language, cx) {
2241 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
2242 buffer.set_completion_triggers(server_id, Default::default(), cx);
2243 }
2244 });
2245 }
2246
2247 fn update_buffer_diagnostics(
2248 &mut self,
2249 buffer: &Entity<Buffer>,
2250 server_id: LanguageServerId,
2251 result_id: Option<String>,
2252 version: Option<i32>,
2253 new_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2254 reused_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2255 cx: &mut Context<LspStore>,
2256 ) -> Result<()> {
2257 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2258 Ordering::Equal
2259 .then_with(|| b.is_primary.cmp(&a.is_primary))
2260 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2261 .then_with(|| a.severity.cmp(&b.severity))
2262 .then_with(|| a.message.cmp(&b.message))
2263 }
2264
2265 let mut diagnostics = Vec::with_capacity(new_diagnostics.len() + reused_diagnostics.len());
2266 diagnostics.extend(new_diagnostics.into_iter().map(|d| (true, d)));
2267 diagnostics.extend(reused_diagnostics.into_iter().map(|d| (false, d)));
2268
2269 diagnostics.sort_unstable_by(|(_, a), (_, b)| {
2270 Ordering::Equal
2271 .then_with(|| a.range.start.cmp(&b.range.start))
2272 .then_with(|| b.range.end.cmp(&a.range.end))
2273 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2274 });
2275
2276 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
2277
2278 let edits_since_save = std::cell::LazyCell::new(|| {
2279 let saved_version = buffer.read(cx).saved_version();
2280 Patch::new(snapshot.edits_since::<PointUtf16>(saved_version).collect())
2281 });
2282
2283 let mut sanitized_diagnostics = Vec::with_capacity(diagnostics.len());
2284
2285 for (new_diagnostic, entry) in diagnostics {
2286 let start;
2287 let end;
2288 if new_diagnostic && entry.diagnostic.is_disk_based {
2289 // Some diagnostics are based on files on disk instead of buffers'
2290 // current contents. Adjust these diagnostics' ranges to reflect
2291 // any unsaved edits.
2292 // Do not alter the reused ones though, as their coordinates were stored as anchors
2293 // and were properly adjusted on reuse.
2294 start = Unclipped((*edits_since_save).old_to_new(entry.range.start.0));
2295 end = Unclipped((*edits_since_save).old_to_new(entry.range.end.0));
2296 } else {
2297 start = entry.range.start;
2298 end = entry.range.end;
2299 }
2300
2301 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2302 ..snapshot.clip_point_utf16(end, Bias::Right);
2303
2304 // Expand empty ranges by one codepoint
2305 if range.start == range.end {
2306 // This will be go to the next boundary when being clipped
2307 range.end.column += 1;
2308 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2309 if range.start == range.end && range.end.column > 0 {
2310 range.start.column -= 1;
2311 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
2312 }
2313 }
2314
2315 sanitized_diagnostics.push(DiagnosticEntry {
2316 range,
2317 diagnostic: entry.diagnostic,
2318 });
2319 }
2320 drop(edits_since_save);
2321
2322 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2323 buffer.update(cx, |buffer, cx| {
2324 if let Some(abs_path) = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)) {
2325 self.buffer_pull_diagnostics_result_ids
2326 .entry(server_id)
2327 .or_default()
2328 .insert(abs_path, result_id);
2329 }
2330
2331 buffer.update_diagnostics(server_id, set, cx)
2332 });
2333
2334 Ok(())
2335 }
2336
2337 fn register_buffer_with_language_servers(
2338 &mut self,
2339 buffer_handle: &Entity<Buffer>,
2340 only_register_servers: HashSet<LanguageServerSelector>,
2341 cx: &mut Context<LspStore>,
2342 ) {
2343 let buffer = buffer_handle.read(cx);
2344 let buffer_id = buffer.remote_id();
2345
2346 let Some(file) = File::from_dyn(buffer.file()) else {
2347 return;
2348 };
2349 if !file.is_local() {
2350 return;
2351 }
2352
2353 let abs_path = file.abs_path(cx);
2354 let Some(uri) = file_path_to_lsp_url(&abs_path).log_err() else {
2355 return;
2356 };
2357 let initial_snapshot = buffer.text_snapshot();
2358 let worktree_id = file.worktree_id(cx);
2359
2360 let Some(language) = buffer.language().cloned() else {
2361 return;
2362 };
2363 let path: Arc<Path> = file
2364 .path()
2365 .parent()
2366 .map(Arc::from)
2367 .unwrap_or_else(|| file.path().clone());
2368 let Some(worktree) = self
2369 .worktree_store
2370 .read(cx)
2371 .worktree_for_id(worktree_id, cx)
2372 else {
2373 return;
2374 };
2375 let language_name = language.name();
2376 let (reused, delegate, servers) = self
2377 .lsp_tree
2378 .update(cx, |lsp_tree, cx| {
2379 self.reuse_existing_language_server(lsp_tree, &worktree, &language_name, cx)
2380 })
2381 .map(|(delegate, servers)| (true, delegate, servers))
2382 .unwrap_or_else(|| {
2383 let lsp_delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
2384 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
2385 let servers = self
2386 .lsp_tree
2387 .clone()
2388 .update(cx, |language_server_tree, cx| {
2389 language_server_tree
2390 .get(
2391 ProjectPath { worktree_id, path },
2392 AdapterQuery::Language(&language.name()),
2393 delegate.clone(),
2394 cx,
2395 )
2396 .collect::<Vec<_>>()
2397 });
2398 (false, lsp_delegate, servers)
2399 });
2400 let servers_and_adapters = servers
2401 .into_iter()
2402 .filter_map(|server_node| {
2403 if reused && server_node.server_id().is_none() {
2404 return None;
2405 }
2406 if !only_register_servers.is_empty() {
2407 if let Some(server_id) = server_node.server_id() {
2408 if !only_register_servers.contains(&LanguageServerSelector::Id(server_id)) {
2409 return None;
2410 }
2411 }
2412 if let Some(name) = server_node.name() {
2413 if !only_register_servers.contains(&LanguageServerSelector::Name(name)) {
2414 return None;
2415 }
2416 }
2417 }
2418
2419 let server_id = server_node.server_id_or_init(
2420 |LaunchDisposition {
2421 server_name,
2422 attach,
2423 path,
2424 settings,
2425 }| {
2426 let server_id = match attach {
2427 language::Attach::InstancePerRoot => {
2428 // todo: handle instance per root proper.
2429 if let Some(server_ids) = self
2430 .language_server_ids
2431 .get(&(worktree_id, server_name.clone()))
2432 {
2433 server_ids.iter().cloned().next().unwrap()
2434 } else {
2435 let language_name = language.name();
2436 let adapter = self.languages
2437 .lsp_adapters(&language_name)
2438 .into_iter()
2439 .find(|adapter| &adapter.name() == server_name)
2440 .expect("To find LSP adapter");
2441 let server_id = self.start_language_server(
2442 &worktree,
2443 delegate.clone(),
2444 adapter,
2445 settings,
2446 cx,
2447 );
2448 server_id
2449 }
2450 }
2451 language::Attach::Shared => {
2452 let uri = Url::from_file_path(
2453 worktree.read(cx).abs_path().join(&path.path),
2454 );
2455 let key = (worktree_id, server_name.clone());
2456 if !self.language_server_ids.contains_key(&key) {
2457 let language_name = language.name();
2458 let adapter = self.languages
2459 .lsp_adapters(&language_name)
2460 .into_iter()
2461 .find(|adapter| &adapter.name() == server_name)
2462 .expect("To find LSP adapter");
2463 self.start_language_server(
2464 &worktree,
2465 delegate.clone(),
2466 adapter,
2467 settings,
2468 cx,
2469 );
2470 }
2471 if let Some(server_ids) = self
2472 .language_server_ids
2473 .get(&key)
2474 {
2475 debug_assert_eq!(server_ids.len(), 1);
2476 let server_id = server_ids.iter().cloned().next().unwrap();
2477 if let Some(state) = self.language_servers.get(&server_id) {
2478 if let Ok(uri) = uri {
2479 state.add_workspace_folder(uri);
2480 };
2481 }
2482 server_id
2483 } else {
2484 unreachable!("Language server ID should be available, as it's registered on demand")
2485 }
2486 }
2487 };
2488 let lsp_store = self.weak.clone();
2489 let server_name = server_node.name();
2490 let buffer_abs_path = abs_path.to_string_lossy().to_string();
2491 cx.defer(move |cx| {
2492 lsp_store.update(cx, |_, cx| cx.emit(LspStoreEvent::LanguageServerUpdate {
2493 language_server_id: server_id,
2494 name: server_name,
2495 message: proto::update_language_server::Variant::RegisteredForBuffer(proto::RegisteredForBuffer {
2496 buffer_abs_path,
2497 })
2498 })).ok();
2499 });
2500 server_id
2501 },
2502 )?;
2503 let server_state = self.language_servers.get(&server_id)?;
2504 if let LanguageServerState::Running { server, adapter, .. } = server_state {
2505 Some((server.clone(), adapter.clone()))
2506 } else {
2507 None
2508 }
2509 })
2510 .collect::<Vec<_>>();
2511 for (server, adapter) in servers_and_adapters {
2512 buffer_handle.update(cx, |buffer, cx| {
2513 buffer.set_completion_triggers(
2514 server.server_id(),
2515 server
2516 .capabilities()
2517 .completion_provider
2518 .as_ref()
2519 .and_then(|provider| {
2520 provider
2521 .trigger_characters
2522 .as_ref()
2523 .map(|characters| characters.iter().cloned().collect())
2524 })
2525 .unwrap_or_default(),
2526 cx,
2527 );
2528 });
2529
2530 let snapshot = LspBufferSnapshot {
2531 version: 0,
2532 snapshot: initial_snapshot.clone(),
2533 };
2534
2535 self.buffer_snapshots
2536 .entry(buffer_id)
2537 .or_default()
2538 .entry(server.server_id())
2539 .or_insert_with(|| {
2540 server.register_buffer(
2541 uri.clone(),
2542 adapter.language_id(&language.name()),
2543 0,
2544 initial_snapshot.text(),
2545 );
2546
2547 vec![snapshot]
2548 });
2549
2550 self.buffers_opened_in_servers
2551 .entry(buffer_id)
2552 .or_default()
2553 .insert(server.server_id());
2554 cx.emit(LspStoreEvent::LanguageServerUpdate {
2555 language_server_id: server.server_id(),
2556 name: None,
2557 message: proto::update_language_server::Variant::RegisteredForBuffer(
2558 proto::RegisteredForBuffer {
2559 buffer_abs_path: abs_path.to_string_lossy().to_string(),
2560 },
2561 ),
2562 });
2563 }
2564 }
2565
2566 fn reuse_existing_language_server(
2567 &self,
2568 server_tree: &mut LanguageServerTree,
2569 worktree: &Entity<Worktree>,
2570 language_name: &LanguageName,
2571 cx: &mut App,
2572 ) -> Option<(Arc<LocalLspAdapterDelegate>, Vec<LanguageServerTreeNode>)> {
2573 if worktree.read(cx).is_visible() {
2574 return None;
2575 }
2576
2577 let worktree_store = self.worktree_store.read(cx);
2578 let servers = server_tree
2579 .instances
2580 .iter()
2581 .filter(|(worktree_id, _)| {
2582 worktree_store
2583 .worktree_for_id(**worktree_id, cx)
2584 .is_some_and(|worktree| worktree.read(cx).is_visible())
2585 })
2586 .flat_map(|(worktree_id, servers)| {
2587 servers
2588 .roots
2589 .iter()
2590 .flat_map(|(_, language_servers)| language_servers)
2591 .map(move |(_, (server_node, server_languages))| {
2592 (worktree_id, server_node, server_languages)
2593 })
2594 .filter(|(_, _, server_languages)| server_languages.contains(language_name))
2595 .map(|(worktree_id, server_node, _)| {
2596 (
2597 *worktree_id,
2598 LanguageServerTreeNode::from(Arc::downgrade(server_node)),
2599 )
2600 })
2601 })
2602 .fold(HashMap::default(), |mut acc, (worktree_id, server_node)| {
2603 acc.entry(worktree_id)
2604 .or_insert_with(Vec::new)
2605 .push(server_node);
2606 acc
2607 })
2608 .into_values()
2609 .max_by_key(|servers| servers.len())?;
2610
2611 for server_node in &servers {
2612 server_tree.register_reused(
2613 worktree.read(cx).id(),
2614 language_name.clone(),
2615 server_node.clone(),
2616 );
2617 }
2618
2619 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, worktree, cx);
2620 Some((delegate, servers))
2621 }
2622
2623 pub(crate) fn unregister_old_buffer_from_language_servers(
2624 &mut self,
2625 buffer: &Entity<Buffer>,
2626 old_file: &File,
2627 cx: &mut App,
2628 ) {
2629 let old_path = match old_file.as_local() {
2630 Some(local) => local.abs_path(cx),
2631 None => return,
2632 };
2633
2634 let Ok(file_url) = lsp::Url::from_file_path(old_path.as_path()) else {
2635 debug_panic!(
2636 "`{}` is not parseable as an URI",
2637 old_path.to_string_lossy()
2638 );
2639 return;
2640 };
2641 self.unregister_buffer_from_language_servers(buffer, &file_url, cx);
2642 }
2643
2644 pub(crate) fn unregister_buffer_from_language_servers(
2645 &mut self,
2646 buffer: &Entity<Buffer>,
2647 file_url: &lsp::Url,
2648 cx: &mut App,
2649 ) {
2650 buffer.update(cx, |buffer, cx| {
2651 let _ = self.buffer_snapshots.remove(&buffer.remote_id());
2652
2653 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2654 language_server.unregister_buffer(file_url.clone());
2655 }
2656 });
2657 }
2658
2659 fn buffer_snapshot_for_lsp_version(
2660 &mut self,
2661 buffer: &Entity<Buffer>,
2662 server_id: LanguageServerId,
2663 version: Option<i32>,
2664 cx: &App,
2665 ) -> Result<TextBufferSnapshot> {
2666 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
2667
2668 if let Some(version) = version {
2669 let buffer_id = buffer.read(cx).remote_id();
2670 let snapshots = if let Some(snapshots) = self
2671 .buffer_snapshots
2672 .get_mut(&buffer_id)
2673 .and_then(|m| m.get_mut(&server_id))
2674 {
2675 snapshots
2676 } else if version == 0 {
2677 // Some language servers report version 0 even if the buffer hasn't been opened yet.
2678 // We detect this case and treat it as if the version was `None`.
2679 return Ok(buffer.read(cx).text_snapshot());
2680 } else {
2681 anyhow::bail!("no snapshots found for buffer {buffer_id} and server {server_id}");
2682 };
2683
2684 let found_snapshot = snapshots
2685 .binary_search_by_key(&version, |e| e.version)
2686 .map(|ix| snapshots[ix].snapshot.clone())
2687 .map_err(|_| {
2688 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
2689 })?;
2690
2691 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
2692 Ok(found_snapshot)
2693 } else {
2694 Ok((buffer.read(cx)).text_snapshot())
2695 }
2696 }
2697
2698 async fn get_server_code_actions_from_action_kinds(
2699 lsp_store: &WeakEntity<LspStore>,
2700 language_server_id: LanguageServerId,
2701 code_action_kinds: Vec<lsp::CodeActionKind>,
2702 buffer: &Entity<Buffer>,
2703 cx: &mut AsyncApp,
2704 ) -> Result<Vec<CodeAction>> {
2705 let actions = lsp_store
2706 .update(cx, move |this, cx| {
2707 let request = GetCodeActions {
2708 range: text::Anchor::MIN..text::Anchor::MAX,
2709 kinds: Some(code_action_kinds),
2710 };
2711 let server = LanguageServerToQuery::Other(language_server_id);
2712 this.request_lsp(buffer.clone(), server, request, cx)
2713 })?
2714 .await?;
2715 return Ok(actions);
2716 }
2717
2718 pub async fn execute_code_actions_on_server(
2719 lsp_store: &WeakEntity<LspStore>,
2720 language_server: &Arc<LanguageServer>,
2721 lsp_adapter: &Arc<CachedLspAdapter>,
2722 actions: Vec<CodeAction>,
2723 push_to_history: bool,
2724 project_transaction: &mut ProjectTransaction,
2725 cx: &mut AsyncApp,
2726 ) -> anyhow::Result<()> {
2727 for mut action in actions {
2728 Self::try_resolve_code_action(language_server, &mut action)
2729 .await
2730 .context("resolving a formatting code action")?;
2731
2732 if let Some(edit) = action.lsp_action.edit() {
2733 if edit.changes.is_none() && edit.document_changes.is_none() {
2734 continue;
2735 }
2736
2737 let new = Self::deserialize_workspace_edit(
2738 lsp_store.upgrade().context("project dropped")?,
2739 edit.clone(),
2740 push_to_history,
2741 lsp_adapter.clone(),
2742 language_server.clone(),
2743 cx,
2744 )
2745 .await?;
2746 project_transaction.0.extend(new.0);
2747 }
2748
2749 if let Some(command) = action.lsp_action.command() {
2750 let server_capabilities = language_server.capabilities();
2751 let available_commands = server_capabilities
2752 .execute_command_provider
2753 .as_ref()
2754 .map(|options| options.commands.as_slice())
2755 .unwrap_or_default();
2756 if available_commands.contains(&command.command) {
2757 lsp_store.update(cx, |lsp_store, _| {
2758 if let LspStoreMode::Local(mode) = &mut lsp_store.mode {
2759 mode.last_workspace_edits_by_language_server
2760 .remove(&language_server.server_id());
2761 }
2762 })?;
2763
2764 language_server
2765 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
2766 command: command.command.clone(),
2767 arguments: command.arguments.clone().unwrap_or_default(),
2768 ..Default::default()
2769 })
2770 .await
2771 .into_response()
2772 .context("execute command")?;
2773
2774 lsp_store.update(cx, |this, _| {
2775 if let LspStoreMode::Local(mode) = &mut this.mode {
2776 project_transaction.0.extend(
2777 mode.last_workspace_edits_by_language_server
2778 .remove(&language_server.server_id())
2779 .unwrap_or_default()
2780 .0,
2781 )
2782 }
2783 })?;
2784 } else {
2785 log::warn!(
2786 "Cannot execute a command {} not listed in the language server capabilities",
2787 command.command
2788 )
2789 }
2790 }
2791 }
2792 return Ok(());
2793 }
2794
2795 pub async fn deserialize_text_edits(
2796 this: Entity<LspStore>,
2797 buffer_to_edit: Entity<Buffer>,
2798 edits: Vec<lsp::TextEdit>,
2799 push_to_history: bool,
2800 _: Arc<CachedLspAdapter>,
2801 language_server: Arc<LanguageServer>,
2802 cx: &mut AsyncApp,
2803 ) -> Result<Option<Transaction>> {
2804 let edits = this
2805 .update(cx, |this, cx| {
2806 this.as_local_mut().unwrap().edits_from_lsp(
2807 &buffer_to_edit,
2808 edits,
2809 language_server.server_id(),
2810 None,
2811 cx,
2812 )
2813 })?
2814 .await?;
2815
2816 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2817 buffer.finalize_last_transaction();
2818 buffer.start_transaction();
2819 for (range, text) in edits {
2820 buffer.edit([(range, text)], None, cx);
2821 }
2822
2823 if buffer.end_transaction(cx).is_some() {
2824 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2825 if !push_to_history {
2826 buffer.forget_transaction(transaction.id);
2827 }
2828 Some(transaction)
2829 } else {
2830 None
2831 }
2832 })?;
2833
2834 Ok(transaction)
2835 }
2836
2837 #[allow(clippy::type_complexity)]
2838 pub(crate) fn edits_from_lsp(
2839 &mut self,
2840 buffer: &Entity<Buffer>,
2841 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
2842 server_id: LanguageServerId,
2843 version: Option<i32>,
2844 cx: &mut Context<LspStore>,
2845 ) -> Task<Result<Vec<(Range<Anchor>, Arc<str>)>>> {
2846 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
2847 cx.background_spawn(async move {
2848 let snapshot = snapshot?;
2849 let mut lsp_edits = lsp_edits
2850 .into_iter()
2851 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
2852 .collect::<Vec<_>>();
2853
2854 lsp_edits.sort_by_key(|(range, _)| (range.start, range.end));
2855
2856 let mut lsp_edits = lsp_edits.into_iter().peekable();
2857 let mut edits = Vec::new();
2858 while let Some((range, mut new_text)) = lsp_edits.next() {
2859 // Clip invalid ranges provided by the language server.
2860 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
2861 ..snapshot.clip_point_utf16(range.end, Bias::Left);
2862
2863 // Combine any LSP edits that are adjacent.
2864 //
2865 // Also, combine LSP edits that are separated from each other by only
2866 // a newline. This is important because for some code actions,
2867 // Rust-analyzer rewrites the entire buffer via a series of edits that
2868 // are separated by unchanged newline characters.
2869 //
2870 // In order for the diffing logic below to work properly, any edits that
2871 // cancel each other out must be combined into one.
2872 while let Some((next_range, next_text)) = lsp_edits.peek() {
2873 if next_range.start.0 > range.end {
2874 if next_range.start.0.row > range.end.row + 1
2875 || next_range.start.0.column > 0
2876 || snapshot.clip_point_utf16(
2877 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
2878 Bias::Left,
2879 ) > range.end
2880 {
2881 break;
2882 }
2883 new_text.push('\n');
2884 }
2885 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
2886 new_text.push_str(next_text);
2887 lsp_edits.next();
2888 }
2889
2890 // For multiline edits, perform a diff of the old and new text so that
2891 // we can identify the changes more precisely, preserving the locations
2892 // of any anchors positioned in the unchanged regions.
2893 if range.end.row > range.start.row {
2894 let offset = range.start.to_offset(&snapshot);
2895 let old_text = snapshot.text_for_range(range).collect::<String>();
2896 let range_edits = language::text_diff(old_text.as_str(), &new_text);
2897 edits.extend(range_edits.into_iter().map(|(range, replacement)| {
2898 (
2899 snapshot.anchor_after(offset + range.start)
2900 ..snapshot.anchor_before(offset + range.end),
2901 replacement,
2902 )
2903 }));
2904 } else if range.end == range.start {
2905 let anchor = snapshot.anchor_after(range.start);
2906 edits.push((anchor..anchor, new_text.into()));
2907 } else {
2908 let edit_start = snapshot.anchor_after(range.start);
2909 let edit_end = snapshot.anchor_before(range.end);
2910 edits.push((edit_start..edit_end, new_text.into()));
2911 }
2912 }
2913
2914 Ok(edits)
2915 })
2916 }
2917
2918 pub(crate) async fn deserialize_workspace_edit(
2919 this: Entity<LspStore>,
2920 edit: lsp::WorkspaceEdit,
2921 push_to_history: bool,
2922 lsp_adapter: Arc<CachedLspAdapter>,
2923 language_server: Arc<LanguageServer>,
2924 cx: &mut AsyncApp,
2925 ) -> Result<ProjectTransaction> {
2926 let fs = this.read_with(cx, |this, _| this.as_local().unwrap().fs.clone())?;
2927
2928 let mut operations = Vec::new();
2929 if let Some(document_changes) = edit.document_changes {
2930 match document_changes {
2931 lsp::DocumentChanges::Edits(edits) => {
2932 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2933 }
2934 lsp::DocumentChanges::Operations(ops) => operations = ops,
2935 }
2936 } else if let Some(changes) = edit.changes {
2937 operations.extend(changes.into_iter().map(|(uri, edits)| {
2938 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2939 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2940 uri,
2941 version: None,
2942 },
2943 edits: edits.into_iter().map(Edit::Plain).collect(),
2944 })
2945 }));
2946 }
2947
2948 let mut project_transaction = ProjectTransaction::default();
2949 for operation in operations {
2950 match operation {
2951 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2952 let abs_path = op
2953 .uri
2954 .to_file_path()
2955 .map_err(|()| anyhow!("can't convert URI to path"))?;
2956
2957 if let Some(parent_path) = abs_path.parent() {
2958 fs.create_dir(parent_path).await?;
2959 }
2960 if abs_path.ends_with("/") {
2961 fs.create_dir(&abs_path).await?;
2962 } else {
2963 fs.create_file(
2964 &abs_path,
2965 op.options
2966 .map(|options| fs::CreateOptions {
2967 overwrite: options.overwrite.unwrap_or(false),
2968 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2969 })
2970 .unwrap_or_default(),
2971 )
2972 .await?;
2973 }
2974 }
2975
2976 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2977 let source_abs_path = op
2978 .old_uri
2979 .to_file_path()
2980 .map_err(|()| anyhow!("can't convert URI to path"))?;
2981 let target_abs_path = op
2982 .new_uri
2983 .to_file_path()
2984 .map_err(|()| anyhow!("can't convert URI to path"))?;
2985 fs.rename(
2986 &source_abs_path,
2987 &target_abs_path,
2988 op.options
2989 .map(|options| fs::RenameOptions {
2990 overwrite: options.overwrite.unwrap_or(false),
2991 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2992 })
2993 .unwrap_or_default(),
2994 )
2995 .await?;
2996 }
2997
2998 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2999 let abs_path = op
3000 .uri
3001 .to_file_path()
3002 .map_err(|()| anyhow!("can't convert URI to path"))?;
3003 let options = op
3004 .options
3005 .map(|options| fs::RemoveOptions {
3006 recursive: options.recursive.unwrap_or(false),
3007 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
3008 })
3009 .unwrap_or_default();
3010 if abs_path.ends_with("/") {
3011 fs.remove_dir(&abs_path, options).await?;
3012 } else {
3013 fs.remove_file(&abs_path, options).await?;
3014 }
3015 }
3016
3017 lsp::DocumentChangeOperation::Edit(op) => {
3018 let buffer_to_edit = this
3019 .update(cx, |this, cx| {
3020 this.open_local_buffer_via_lsp(
3021 op.text_document.uri.clone(),
3022 language_server.server_id(),
3023 lsp_adapter.name.clone(),
3024 cx,
3025 )
3026 })?
3027 .await?;
3028
3029 let edits = this
3030 .update(cx, |this, cx| {
3031 let path = buffer_to_edit.read(cx).project_path(cx);
3032 let active_entry = this.active_entry;
3033 let is_active_entry = path.clone().map_or(false, |project_path| {
3034 this.worktree_store
3035 .read(cx)
3036 .entry_for_path(&project_path, cx)
3037 .map_or(false, |entry| Some(entry.id) == active_entry)
3038 });
3039 let local = this.as_local_mut().unwrap();
3040
3041 let (mut edits, mut snippet_edits) = (vec![], vec![]);
3042 for edit in op.edits {
3043 match edit {
3044 Edit::Plain(edit) => {
3045 if !edits.contains(&edit) {
3046 edits.push(edit)
3047 }
3048 }
3049 Edit::Annotated(edit) => {
3050 if !edits.contains(&edit.text_edit) {
3051 edits.push(edit.text_edit)
3052 }
3053 }
3054 Edit::Snippet(edit) => {
3055 let Ok(snippet) = Snippet::parse(&edit.snippet.value)
3056 else {
3057 continue;
3058 };
3059
3060 if is_active_entry {
3061 snippet_edits.push((edit.range, snippet));
3062 } else {
3063 // Since this buffer is not focused, apply a normal edit.
3064 let new_edit = TextEdit {
3065 range: edit.range,
3066 new_text: snippet.text,
3067 };
3068 if !edits.contains(&new_edit) {
3069 edits.push(new_edit);
3070 }
3071 }
3072 }
3073 }
3074 }
3075 if !snippet_edits.is_empty() {
3076 let buffer_id = buffer_to_edit.read(cx).remote_id();
3077 let version = if let Some(buffer_version) = op.text_document.version
3078 {
3079 local
3080 .buffer_snapshot_for_lsp_version(
3081 &buffer_to_edit,
3082 language_server.server_id(),
3083 Some(buffer_version),
3084 cx,
3085 )
3086 .ok()
3087 .map(|snapshot| snapshot.version)
3088 } else {
3089 Some(buffer_to_edit.read(cx).saved_version().clone())
3090 };
3091
3092 let most_recent_edit = version.and_then(|version| {
3093 version.iter().max_by_key(|timestamp| timestamp.value)
3094 });
3095 // Check if the edit that triggered that edit has been made by this participant.
3096
3097 if let Some(most_recent_edit) = most_recent_edit {
3098 cx.emit(LspStoreEvent::SnippetEdit {
3099 buffer_id,
3100 edits: snippet_edits,
3101 most_recent_edit,
3102 });
3103 }
3104 }
3105
3106 local.edits_from_lsp(
3107 &buffer_to_edit,
3108 edits,
3109 language_server.server_id(),
3110 op.text_document.version,
3111 cx,
3112 )
3113 })?
3114 .await?;
3115
3116 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3117 buffer.finalize_last_transaction();
3118 buffer.start_transaction();
3119 for (range, text) in edits {
3120 buffer.edit([(range, text)], None, cx);
3121 }
3122
3123 let transaction = buffer.end_transaction(cx).and_then(|transaction_id| {
3124 if push_to_history {
3125 buffer.finalize_last_transaction();
3126 buffer.get_transaction(transaction_id).cloned()
3127 } else {
3128 buffer.forget_transaction(transaction_id)
3129 }
3130 });
3131
3132 transaction
3133 })?;
3134 if let Some(transaction) = transaction {
3135 project_transaction.0.insert(buffer_to_edit, transaction);
3136 }
3137 }
3138 }
3139 }
3140
3141 Ok(project_transaction)
3142 }
3143
3144 async fn on_lsp_workspace_edit(
3145 this: WeakEntity<LspStore>,
3146 params: lsp::ApplyWorkspaceEditParams,
3147 server_id: LanguageServerId,
3148 adapter: Arc<CachedLspAdapter>,
3149 cx: &mut AsyncApp,
3150 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3151 let this = this.upgrade().context("project project closed")?;
3152 let language_server = this
3153 .read_with(cx, |this, _| this.language_server_for_id(server_id))?
3154 .context("language server not found")?;
3155 let transaction = Self::deserialize_workspace_edit(
3156 this.clone(),
3157 params.edit,
3158 true,
3159 adapter.clone(),
3160 language_server.clone(),
3161 cx,
3162 )
3163 .await
3164 .log_err();
3165 this.update(cx, |this, _| {
3166 if let Some(transaction) = transaction {
3167 this.as_local_mut()
3168 .unwrap()
3169 .last_workspace_edits_by_language_server
3170 .insert(server_id, transaction);
3171 }
3172 })?;
3173 Ok(lsp::ApplyWorkspaceEditResponse {
3174 applied: true,
3175 failed_change: None,
3176 failure_reason: None,
3177 })
3178 }
3179
3180 fn remove_worktree(
3181 &mut self,
3182 id_to_remove: WorktreeId,
3183 cx: &mut Context<LspStore>,
3184 ) -> Vec<LanguageServerId> {
3185 self.diagnostics.remove(&id_to_remove);
3186 self.prettier_store.update(cx, |prettier_store, cx| {
3187 prettier_store.remove_worktree(id_to_remove, cx);
3188 });
3189
3190 let mut servers_to_remove = BTreeMap::default();
3191 let mut servers_to_preserve = HashSet::default();
3192 for ((path, server_name), ref server_ids) in &self.language_server_ids {
3193 if *path == id_to_remove {
3194 servers_to_remove.extend(server_ids.iter().map(|id| (*id, server_name.clone())));
3195 } else {
3196 servers_to_preserve.extend(server_ids.iter().cloned());
3197 }
3198 }
3199 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
3200
3201 for (server_id_to_remove, _) in &servers_to_remove {
3202 self.language_server_ids
3203 .values_mut()
3204 .for_each(|server_ids| {
3205 server_ids.remove(server_id_to_remove);
3206 });
3207 self.language_server_watched_paths
3208 .remove(server_id_to_remove);
3209 self.language_server_paths_watched_for_rename
3210 .remove(server_id_to_remove);
3211 self.last_workspace_edits_by_language_server
3212 .remove(server_id_to_remove);
3213 self.language_servers.remove(server_id_to_remove);
3214 self.buffer_pull_diagnostics_result_ids
3215 .remove(server_id_to_remove);
3216 for buffer_servers in self.buffers_opened_in_servers.values_mut() {
3217 buffer_servers.remove(server_id_to_remove);
3218 }
3219 cx.emit(LspStoreEvent::LanguageServerRemoved(*server_id_to_remove));
3220 }
3221 servers_to_remove.into_keys().collect()
3222 }
3223
3224 fn rebuild_watched_paths_inner<'a>(
3225 &'a self,
3226 language_server_id: LanguageServerId,
3227 watchers: impl Iterator<Item = &'a FileSystemWatcher>,
3228 cx: &mut Context<LspStore>,
3229 ) -> LanguageServerWatchedPathsBuilder {
3230 let worktrees = self
3231 .worktree_store
3232 .read(cx)
3233 .worktrees()
3234 .filter_map(|worktree| {
3235 self.language_servers_for_worktree(worktree.read(cx).id())
3236 .find(|server| server.server_id() == language_server_id)
3237 .map(|_| worktree)
3238 })
3239 .collect::<Vec<_>>();
3240
3241 let mut worktree_globs = HashMap::default();
3242 let mut abs_globs = HashMap::default();
3243 log::trace!(
3244 "Processing new watcher paths for language server with id {}",
3245 language_server_id
3246 );
3247
3248 for watcher in watchers {
3249 if let Some((worktree, literal_prefix, pattern)) =
3250 self.worktree_and_path_for_file_watcher(&worktrees, &watcher, cx)
3251 {
3252 worktree.update(cx, |worktree, _| {
3253 if let Some((tree, glob)) =
3254 worktree.as_local_mut().zip(Glob::new(&pattern).log_err())
3255 {
3256 tree.add_path_prefix_to_scan(literal_prefix.into());
3257 worktree_globs
3258 .entry(tree.id())
3259 .or_insert_with(GlobSetBuilder::new)
3260 .add(glob);
3261 }
3262 });
3263 } else {
3264 let (path, pattern) = match &watcher.glob_pattern {
3265 lsp::GlobPattern::String(s) => {
3266 let watcher_path = SanitizedPath::from(s);
3267 let path = glob_literal_prefix(watcher_path.as_path());
3268 let pattern = watcher_path
3269 .as_path()
3270 .strip_prefix(&path)
3271 .map(|p| p.to_string_lossy().to_string())
3272 .unwrap_or_else(|e| {
3273 debug_panic!(
3274 "Failed to strip prefix for string pattern: {}, with prefix: {}, with error: {}",
3275 s,
3276 path.display(),
3277 e
3278 );
3279 watcher_path.as_path().to_string_lossy().to_string()
3280 });
3281 (path, pattern)
3282 }
3283 lsp::GlobPattern::Relative(rp) => {
3284 let Ok(mut base_uri) = match &rp.base_uri {
3285 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3286 lsp::OneOf::Right(base_uri) => base_uri,
3287 }
3288 .to_file_path() else {
3289 continue;
3290 };
3291
3292 let path = glob_literal_prefix(Path::new(&rp.pattern));
3293 let pattern = Path::new(&rp.pattern)
3294 .strip_prefix(&path)
3295 .map(|p| p.to_string_lossy().to_string())
3296 .unwrap_or_else(|e| {
3297 debug_panic!(
3298 "Failed to strip prefix for relative pattern: {}, with prefix: {}, with error: {}",
3299 rp.pattern,
3300 path.display(),
3301 e
3302 );
3303 rp.pattern.clone()
3304 });
3305 base_uri.push(path);
3306 (base_uri, pattern)
3307 }
3308 };
3309
3310 if let Some(glob) = Glob::new(&pattern).log_err() {
3311 if !path
3312 .components()
3313 .any(|c| matches!(c, path::Component::Normal(_)))
3314 {
3315 // For an unrooted glob like `**/Cargo.toml`, watch it within each worktree,
3316 // rather than adding a new watcher for `/`.
3317 for worktree in &worktrees {
3318 worktree_globs
3319 .entry(worktree.read(cx).id())
3320 .or_insert_with(GlobSetBuilder::new)
3321 .add(glob.clone());
3322 }
3323 } else {
3324 abs_globs
3325 .entry(path.into())
3326 .or_insert_with(GlobSetBuilder::new)
3327 .add(glob);
3328 }
3329 }
3330 }
3331 }
3332
3333 let mut watch_builder = LanguageServerWatchedPathsBuilder::default();
3334 for (worktree_id, builder) in worktree_globs {
3335 if let Ok(globset) = builder.build() {
3336 watch_builder.watch_worktree(worktree_id, globset);
3337 }
3338 }
3339 for (abs_path, builder) in abs_globs {
3340 if let Ok(globset) = builder.build() {
3341 watch_builder.watch_abs_path(abs_path, globset);
3342 }
3343 }
3344 watch_builder
3345 }
3346
3347 fn worktree_and_path_for_file_watcher(
3348 &self,
3349 worktrees: &[Entity<Worktree>],
3350 watcher: &FileSystemWatcher,
3351 cx: &App,
3352 ) -> Option<(Entity<Worktree>, PathBuf, String)> {
3353 worktrees.iter().find_map(|worktree| {
3354 let tree = worktree.read(cx);
3355 let worktree_root_path = tree.abs_path();
3356 match &watcher.glob_pattern {
3357 lsp::GlobPattern::String(s) => {
3358 let watcher_path = SanitizedPath::from(s);
3359 let relative = watcher_path
3360 .as_path()
3361 .strip_prefix(&worktree_root_path)
3362 .ok()?;
3363 let literal_prefix = glob_literal_prefix(relative);
3364 Some((
3365 worktree.clone(),
3366 literal_prefix,
3367 relative.to_string_lossy().to_string(),
3368 ))
3369 }
3370 lsp::GlobPattern::Relative(rp) => {
3371 let base_uri = match &rp.base_uri {
3372 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3373 lsp::OneOf::Right(base_uri) => base_uri,
3374 }
3375 .to_file_path()
3376 .ok()?;
3377 let relative = base_uri.strip_prefix(&worktree_root_path).ok()?;
3378 let mut literal_prefix = relative.to_owned();
3379 literal_prefix.push(glob_literal_prefix(Path::new(&rp.pattern)));
3380 Some((worktree.clone(), literal_prefix, rp.pattern.clone()))
3381 }
3382 }
3383 })
3384 }
3385
3386 fn rebuild_watched_paths(
3387 &mut self,
3388 language_server_id: LanguageServerId,
3389 cx: &mut Context<LspStore>,
3390 ) {
3391 let Some(watchers) = self
3392 .language_server_watcher_registrations
3393 .get(&language_server_id)
3394 else {
3395 return;
3396 };
3397
3398 let watch_builder =
3399 self.rebuild_watched_paths_inner(language_server_id, watchers.values().flatten(), cx);
3400 let watcher = watch_builder.build(self.fs.clone(), language_server_id, cx);
3401 self.language_server_watched_paths
3402 .insert(language_server_id, watcher);
3403
3404 cx.notify();
3405 }
3406
3407 fn on_lsp_did_change_watched_files(
3408 &mut self,
3409 language_server_id: LanguageServerId,
3410 registration_id: &str,
3411 params: DidChangeWatchedFilesRegistrationOptions,
3412 cx: &mut Context<LspStore>,
3413 ) {
3414 let registrations = self
3415 .language_server_watcher_registrations
3416 .entry(language_server_id)
3417 .or_default();
3418
3419 registrations.insert(registration_id.to_string(), params.watchers);
3420
3421 self.rebuild_watched_paths(language_server_id, cx);
3422 }
3423
3424 fn on_lsp_unregister_did_change_watched_files(
3425 &mut self,
3426 language_server_id: LanguageServerId,
3427 registration_id: &str,
3428 cx: &mut Context<LspStore>,
3429 ) {
3430 let registrations = self
3431 .language_server_watcher_registrations
3432 .entry(language_server_id)
3433 .or_default();
3434
3435 if registrations.remove(registration_id).is_some() {
3436 log::info!(
3437 "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
3438 language_server_id,
3439 registration_id
3440 );
3441 } else {
3442 log::warn!(
3443 "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
3444 language_server_id,
3445 registration_id
3446 );
3447 }
3448
3449 self.rebuild_watched_paths(language_server_id, cx);
3450 }
3451
3452 async fn initialization_options_for_adapter(
3453 adapter: Arc<dyn LspAdapter>,
3454 fs: &dyn Fs,
3455 delegate: &Arc<dyn LspAdapterDelegate>,
3456 ) -> Result<Option<serde_json::Value>> {
3457 let Some(mut initialization_config) =
3458 adapter.clone().initialization_options(fs, delegate).await?
3459 else {
3460 return Ok(None);
3461 };
3462
3463 for other_adapter in delegate.registered_lsp_adapters() {
3464 if other_adapter.name() == adapter.name() {
3465 continue;
3466 }
3467 if let Ok(Some(target_config)) = other_adapter
3468 .clone()
3469 .additional_initialization_options(adapter.name(), fs, delegate)
3470 .await
3471 {
3472 merge_json_value_into(target_config.clone(), &mut initialization_config);
3473 }
3474 }
3475
3476 Ok(Some(initialization_config))
3477 }
3478
3479 async fn workspace_configuration_for_adapter(
3480 adapter: Arc<dyn LspAdapter>,
3481 fs: &dyn Fs,
3482 delegate: &Arc<dyn LspAdapterDelegate>,
3483 toolchains: Arc<dyn LanguageToolchainStore>,
3484 cx: &mut AsyncApp,
3485 ) -> Result<serde_json::Value> {
3486 let mut workspace_config = adapter
3487 .clone()
3488 .workspace_configuration(fs, delegate, toolchains.clone(), cx)
3489 .await?;
3490
3491 for other_adapter in delegate.registered_lsp_adapters() {
3492 if other_adapter.name() == adapter.name() {
3493 continue;
3494 }
3495 if let Ok(Some(target_config)) = other_adapter
3496 .clone()
3497 .additional_workspace_configuration(
3498 adapter.name(),
3499 fs,
3500 delegate,
3501 toolchains.clone(),
3502 cx,
3503 )
3504 .await
3505 {
3506 merge_json_value_into(target_config.clone(), &mut workspace_config);
3507 }
3508 }
3509
3510 Ok(workspace_config)
3511 }
3512}
3513
3514#[derive(Debug)]
3515pub struct FormattableBuffer {
3516 handle: Entity<Buffer>,
3517 abs_path: Option<PathBuf>,
3518 env: Option<HashMap<String, String>>,
3519 ranges: Option<Vec<Range<Anchor>>>,
3520}
3521
3522pub struct RemoteLspStore {
3523 upstream_client: Option<AnyProtoClient>,
3524 upstream_project_id: u64,
3525}
3526
3527pub(crate) enum LspStoreMode {
3528 Local(LocalLspStore), // ssh host and collab host
3529 Remote(RemoteLspStore), // collab guest
3530}
3531
3532impl LspStoreMode {
3533 fn is_local(&self) -> bool {
3534 matches!(self, LspStoreMode::Local(_))
3535 }
3536}
3537
3538pub struct LspStore {
3539 mode: LspStoreMode,
3540 last_formatting_failure: Option<String>,
3541 downstream_client: Option<(AnyProtoClient, u64)>,
3542 nonce: u128,
3543 buffer_store: Entity<BufferStore>,
3544 worktree_store: Entity<WorktreeStore>,
3545 toolchain_store: Option<Entity<ToolchainStore>>,
3546 pub languages: Arc<LanguageRegistry>,
3547 language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3548 active_entry: Option<ProjectEntryId>,
3549 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3550 _maintain_buffer_languages: Task<()>,
3551 diagnostic_summaries:
3552 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3553 lsp_data: HashMap<BufferId, DocumentColorData>,
3554}
3555
3556#[derive(Debug, Default, Clone)]
3557pub struct DocumentColors {
3558 pub colors: HashSet<DocumentColor>,
3559 pub cache_version: Option<usize>,
3560}
3561
3562type DocumentColorTask = Shared<Task<std::result::Result<DocumentColors, Arc<anyhow::Error>>>>;
3563
3564#[derive(Debug, Default)]
3565struct DocumentColorData {
3566 colors_for_version: Global,
3567 colors: HashMap<LanguageServerId, HashSet<DocumentColor>>,
3568 cache_version: usize,
3569 colors_update: Option<(Global, DocumentColorTask)>,
3570}
3571
3572#[derive(Debug, PartialEq, Eq, Clone, Copy)]
3573pub enum ColorFetchStrategy {
3574 IgnoreCache,
3575 UseCache { known_cache_version: Option<usize> },
3576}
3577
3578#[derive(Debug)]
3579pub enum LspStoreEvent {
3580 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3581 LanguageServerRemoved(LanguageServerId),
3582 LanguageServerUpdate {
3583 language_server_id: LanguageServerId,
3584 name: Option<LanguageServerName>,
3585 message: proto::update_language_server::Variant,
3586 },
3587 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3588 LanguageServerPrompt(LanguageServerPromptRequest),
3589 LanguageDetected {
3590 buffer: Entity<Buffer>,
3591 new_language: Option<Arc<Language>>,
3592 },
3593 Notification(String),
3594 RefreshInlayHints,
3595 RefreshCodeLens,
3596 DiagnosticsUpdated {
3597 language_server_id: LanguageServerId,
3598 path: ProjectPath,
3599 },
3600 DiskBasedDiagnosticsStarted {
3601 language_server_id: LanguageServerId,
3602 },
3603 DiskBasedDiagnosticsFinished {
3604 language_server_id: LanguageServerId,
3605 },
3606 SnippetEdit {
3607 buffer_id: BufferId,
3608 edits: Vec<(lsp::Range, Snippet)>,
3609 most_recent_edit: clock::Lamport,
3610 },
3611}
3612
3613#[derive(Clone, Debug, Serialize)]
3614pub struct LanguageServerStatus {
3615 pub name: String,
3616 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3617 pub has_pending_diagnostic_updates: bool,
3618 progress_tokens: HashSet<String>,
3619}
3620
3621#[derive(Clone, Debug)]
3622struct CoreSymbol {
3623 pub language_server_name: LanguageServerName,
3624 pub source_worktree_id: WorktreeId,
3625 pub source_language_server_id: LanguageServerId,
3626 pub path: ProjectPath,
3627 pub name: String,
3628 pub kind: lsp::SymbolKind,
3629 pub range: Range<Unclipped<PointUtf16>>,
3630 pub signature: [u8; 32],
3631}
3632
3633impl LspStore {
3634 pub fn init(client: &AnyProtoClient) {
3635 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3636 client.add_entity_request_handler(Self::handle_restart_language_servers);
3637 client.add_entity_request_handler(Self::handle_stop_language_servers);
3638 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3639 client.add_entity_message_handler(Self::handle_start_language_server);
3640 client.add_entity_message_handler(Self::handle_update_language_server);
3641 client.add_entity_message_handler(Self::handle_language_server_log);
3642 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3643 client.add_entity_request_handler(Self::handle_format_buffers);
3644 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3645 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3646 client.add_entity_request_handler(Self::handle_apply_code_action);
3647 client.add_entity_request_handler(Self::handle_inlay_hints);
3648 client.add_entity_request_handler(Self::handle_get_project_symbols);
3649 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3650 client.add_entity_request_handler(Self::handle_get_color_presentation);
3651 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3652 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3653 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3654 client.add_entity_request_handler(Self::handle_on_type_formatting);
3655 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3656 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3657 client.add_entity_request_handler(Self::handle_rename_project_entry);
3658 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3659 client.add_entity_request_handler(Self::handle_pull_workspace_diagnostics);
3660 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3661 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3662 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3663 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3664 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3665 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3666 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3667 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3668 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3669 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3670 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3671 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3672
3673 client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
3674 client.add_entity_request_handler(Self::handle_lsp_ext_run_flycheck);
3675 client.add_entity_request_handler(Self::handle_lsp_ext_clear_flycheck);
3676 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3677 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3678 client.add_entity_request_handler(
3679 Self::handle_lsp_command::<lsp_ext_command::GoToParentModule>,
3680 );
3681 client.add_entity_request_handler(
3682 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3683 );
3684 client.add_entity_request_handler(
3685 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3686 );
3687 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentDiagnostics>);
3688 }
3689
3690 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3691 match &self.mode {
3692 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3693 _ => None,
3694 }
3695 }
3696
3697 pub fn as_local(&self) -> Option<&LocalLspStore> {
3698 match &self.mode {
3699 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3700 _ => None,
3701 }
3702 }
3703
3704 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3705 match &mut self.mode {
3706 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3707 _ => None,
3708 }
3709 }
3710
3711 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3712 match &self.mode {
3713 LspStoreMode::Remote(RemoteLspStore {
3714 upstream_client: Some(upstream_client),
3715 upstream_project_id,
3716 ..
3717 }) => Some((upstream_client.clone(), *upstream_project_id)),
3718
3719 LspStoreMode::Remote(RemoteLspStore {
3720 upstream_client: None,
3721 ..
3722 }) => None,
3723 LspStoreMode::Local(_) => None,
3724 }
3725 }
3726
3727 pub fn new_local(
3728 buffer_store: Entity<BufferStore>,
3729 worktree_store: Entity<WorktreeStore>,
3730 prettier_store: Entity<PrettierStore>,
3731 toolchain_store: Entity<ToolchainStore>,
3732 environment: Entity<ProjectEnvironment>,
3733 manifest_tree: Entity<ManifestTree>,
3734 languages: Arc<LanguageRegistry>,
3735 http_client: Arc<dyn HttpClient>,
3736 fs: Arc<dyn Fs>,
3737 cx: &mut Context<Self>,
3738 ) -> Self {
3739 let yarn = YarnPathStore::new(fs.clone(), cx);
3740 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3741 .detach();
3742 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3743 .detach();
3744 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3745 .detach();
3746 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3747 .detach();
3748 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3749 cx.subscribe(
3750 extension_events,
3751 Self::reload_zed_json_schemas_on_extensions_changed,
3752 )
3753 .detach();
3754 } else {
3755 log::debug!("No extension events global found. Skipping JSON schema auto-reload setup");
3756 }
3757 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3758 .detach();
3759 subscribe_to_binary_statuses(&languages, cx).detach();
3760
3761 let _maintain_workspace_config = {
3762 let (sender, receiver) = watch::channel();
3763 (
3764 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3765 sender,
3766 )
3767 };
3768
3769 Self {
3770 mode: LspStoreMode::Local(LocalLspStore {
3771 weak: cx.weak_entity(),
3772 worktree_store: worktree_store.clone(),
3773 toolchain_store: toolchain_store.clone(),
3774 supplementary_language_servers: Default::default(),
3775 languages: languages.clone(),
3776 language_server_ids: Default::default(),
3777 language_servers: Default::default(),
3778 last_workspace_edits_by_language_server: Default::default(),
3779 language_server_watched_paths: Default::default(),
3780 language_server_paths_watched_for_rename: Default::default(),
3781 language_server_watcher_registrations: Default::default(),
3782 buffers_being_formatted: Default::default(),
3783 buffer_snapshots: Default::default(),
3784 prettier_store,
3785 environment,
3786 http_client,
3787 fs,
3788 yarn,
3789 next_diagnostic_group_id: Default::default(),
3790 diagnostics: Default::default(),
3791 _subscription: cx.on_app_quit(|this, cx| {
3792 this.as_local_mut()
3793 .unwrap()
3794 .shutdown_language_servers_on_quit(cx)
3795 }),
3796 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3797 registered_buffers: HashMap::default(),
3798 buffers_opened_in_servers: HashMap::default(),
3799 buffer_pull_diagnostics_result_ids: HashMap::default(),
3800 }),
3801 last_formatting_failure: None,
3802 downstream_client: None,
3803 buffer_store,
3804 worktree_store,
3805 toolchain_store: Some(toolchain_store),
3806 languages: languages.clone(),
3807 language_server_statuses: Default::default(),
3808 nonce: StdRng::from_entropy().r#gen(),
3809 diagnostic_summaries: HashMap::default(),
3810 lsp_data: HashMap::default(),
3811 active_entry: None,
3812 _maintain_workspace_config,
3813 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3814 }
3815 }
3816
3817 fn send_lsp_proto_request<R: LspCommand>(
3818 &self,
3819 buffer: Entity<Buffer>,
3820 client: AnyProtoClient,
3821 upstream_project_id: u64,
3822 request: R,
3823 cx: &mut Context<LspStore>,
3824 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3825 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3826 cx.spawn(async move |this, cx| {
3827 let response = client.request(message).await?;
3828 let this = this.upgrade().context("project dropped")?;
3829 request
3830 .response_from_proto(response, this, buffer, cx.clone())
3831 .await
3832 })
3833 }
3834
3835 pub(super) fn new_remote(
3836 buffer_store: Entity<BufferStore>,
3837 worktree_store: Entity<WorktreeStore>,
3838 toolchain_store: Option<Entity<ToolchainStore>>,
3839 languages: Arc<LanguageRegistry>,
3840 upstream_client: AnyProtoClient,
3841 project_id: u64,
3842 fs: Arc<dyn Fs>,
3843 cx: &mut Context<Self>,
3844 ) -> Self {
3845 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3846 .detach();
3847 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3848 .detach();
3849 subscribe_to_binary_statuses(&languages, cx).detach();
3850 let _maintain_workspace_config = {
3851 let (sender, receiver) = watch::channel();
3852 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3853 };
3854 Self {
3855 mode: LspStoreMode::Remote(RemoteLspStore {
3856 upstream_client: Some(upstream_client),
3857 upstream_project_id: project_id,
3858 }),
3859 downstream_client: None,
3860 last_formatting_failure: None,
3861 buffer_store,
3862 worktree_store,
3863 languages: languages.clone(),
3864 language_server_statuses: Default::default(),
3865 nonce: StdRng::from_entropy().r#gen(),
3866 diagnostic_summaries: HashMap::default(),
3867 lsp_data: HashMap::default(),
3868 active_entry: None,
3869 toolchain_store,
3870 _maintain_workspace_config,
3871 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3872 }
3873 }
3874
3875 fn on_buffer_store_event(
3876 &mut self,
3877 _: Entity<BufferStore>,
3878 event: &BufferStoreEvent,
3879 cx: &mut Context<Self>,
3880 ) {
3881 match event {
3882 BufferStoreEvent::BufferAdded(buffer) => {
3883 self.on_buffer_added(buffer, cx).log_err();
3884 }
3885 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3886 let buffer_id = buffer.read(cx).remote_id();
3887 if let Some(local) = self.as_local_mut() {
3888 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3889 local.reset_buffer(buffer, old_file, cx);
3890
3891 if local.registered_buffers.contains_key(&buffer_id) {
3892 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3893 }
3894 }
3895 }
3896
3897 self.detect_language_for_buffer(buffer, cx);
3898 if let Some(local) = self.as_local_mut() {
3899 local.initialize_buffer(buffer, cx);
3900 if local.registered_buffers.contains_key(&buffer_id) {
3901 local.register_buffer_with_language_servers(buffer, HashSet::default(), cx);
3902 }
3903 }
3904 }
3905 _ => {}
3906 }
3907 }
3908
3909 fn on_worktree_store_event(
3910 &mut self,
3911 _: Entity<WorktreeStore>,
3912 event: &WorktreeStoreEvent,
3913 cx: &mut Context<Self>,
3914 ) {
3915 match event {
3916 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3917 if !worktree.read(cx).is_local() {
3918 return;
3919 }
3920 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3921 worktree::Event::UpdatedEntries(changes) => {
3922 this.update_local_worktree_language_servers(&worktree, changes, cx);
3923 }
3924 worktree::Event::UpdatedGitRepositories(_)
3925 | worktree::Event::DeletedEntry(_) => {}
3926 })
3927 .detach()
3928 }
3929 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3930 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3931 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3932 }
3933 WorktreeStoreEvent::WorktreeReleased(..)
3934 | WorktreeStoreEvent::WorktreeOrderChanged
3935 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3936 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3937 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3938 }
3939 }
3940
3941 fn on_prettier_store_event(
3942 &mut self,
3943 _: Entity<PrettierStore>,
3944 event: &PrettierStoreEvent,
3945 cx: &mut Context<Self>,
3946 ) {
3947 match event {
3948 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3949 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3950 }
3951 PrettierStoreEvent::LanguageServerAdded {
3952 new_server_id,
3953 name,
3954 prettier_server,
3955 } => {
3956 self.register_supplementary_language_server(
3957 *new_server_id,
3958 name.clone(),
3959 prettier_server.clone(),
3960 cx,
3961 );
3962 }
3963 }
3964 }
3965
3966 fn on_toolchain_store_event(
3967 &mut self,
3968 _: Entity<ToolchainStore>,
3969 event: &ToolchainStoreEvent,
3970 _: &mut Context<Self>,
3971 ) {
3972 match event {
3973 ToolchainStoreEvent::ToolchainActivated { .. } => {
3974 self.request_workspace_config_refresh()
3975 }
3976 }
3977 }
3978
3979 fn request_workspace_config_refresh(&mut self) {
3980 *self._maintain_workspace_config.1.borrow_mut() = ();
3981 }
3982
3983 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3984 self.as_local().map(|local| local.prettier_store.clone())
3985 }
3986
3987 fn on_buffer_event(
3988 &mut self,
3989 buffer: Entity<Buffer>,
3990 event: &language::BufferEvent,
3991 cx: &mut Context<Self>,
3992 ) {
3993 match event {
3994 language::BufferEvent::Edited => {
3995 self.on_buffer_edited(buffer, cx);
3996 }
3997
3998 language::BufferEvent::Saved => {
3999 self.on_buffer_saved(buffer, cx);
4000 }
4001
4002 _ => {}
4003 }
4004 }
4005
4006 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
4007 buffer
4008 .read(cx)
4009 .set_language_registry(self.languages.clone());
4010
4011 cx.subscribe(buffer, |this, buffer, event, cx| {
4012 this.on_buffer_event(buffer, event, cx);
4013 })
4014 .detach();
4015
4016 self.detect_language_for_buffer(buffer, cx);
4017 if let Some(local) = self.as_local_mut() {
4018 local.initialize_buffer(buffer, cx);
4019 }
4020
4021 Ok(())
4022 }
4023
4024 pub fn reload_zed_json_schemas_on_extensions_changed(
4025 &mut self,
4026 _: Entity<extension::ExtensionEvents>,
4027 evt: &extension::Event,
4028 cx: &mut Context<Self>,
4029 ) {
4030 match evt {
4031 extension::Event::ExtensionInstalled(_)
4032 | extension::Event::ExtensionUninstalled(_)
4033 | extension::Event::ConfigureExtensionRequested(_) => return,
4034 extension::Event::ExtensionsInstalledChanged => {}
4035 }
4036 if self.as_local().is_none() {
4037 return;
4038 }
4039 cx.spawn(async move |this, cx| {
4040 let weak_ref = this.clone();
4041
4042 let servers = this
4043 .update(cx, |this, cx| {
4044 let local = this.as_local()?;
4045
4046 let mut servers = Vec::new();
4047 for ((worktree_id, _), server_ids) in &local.language_server_ids {
4048 for server_id in server_ids {
4049 let Some(states) = local.language_servers.get(server_id) else {
4050 continue;
4051 };
4052 let (json_adapter, json_server) = match states {
4053 LanguageServerState::Running {
4054 adapter, server, ..
4055 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
4056 (adapter.adapter.clone(), server.clone())
4057 }
4058 _ => continue,
4059 };
4060
4061 let Some(worktree) = this
4062 .worktree_store
4063 .read(cx)
4064 .worktree_for_id(*worktree_id, cx)
4065 else {
4066 continue;
4067 };
4068 let json_delegate: Arc<dyn LspAdapterDelegate> =
4069 LocalLspAdapterDelegate::new(
4070 local.languages.clone(),
4071 &local.environment,
4072 weak_ref.clone(),
4073 &worktree,
4074 local.http_client.clone(),
4075 local.fs.clone(),
4076 cx,
4077 );
4078
4079 servers.push((json_adapter, json_server, json_delegate));
4080 }
4081 }
4082 return Some(servers);
4083 })
4084 .ok()
4085 .flatten();
4086
4087 let Some(servers) = servers else {
4088 return;
4089 };
4090
4091 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
4092 let local = this.as_local()?;
4093 let toolchain_store = this.toolchain_store(cx);
4094 return Some((local.fs.clone(), toolchain_store));
4095 }) else {
4096 return;
4097 };
4098 for (adapter, server, delegate) in servers {
4099 adapter.clear_zed_json_schema_cache().await;
4100
4101 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
4102 adapter,
4103 fs.as_ref(),
4104 &delegate,
4105 toolchain_store.clone(),
4106 cx,
4107 )
4108 .await
4109 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
4110 .ok()
4111 else {
4112 continue;
4113 };
4114 server
4115 .notify::<lsp::notification::DidChangeConfiguration>(
4116 &lsp::DidChangeConfigurationParams {
4117 settings: json_workspace_config,
4118 },
4119 )
4120 .ok();
4121 }
4122 })
4123 .detach();
4124 }
4125
4126 pub(crate) fn register_buffer_with_language_servers(
4127 &mut self,
4128 buffer: &Entity<Buffer>,
4129 only_register_servers: HashSet<LanguageServerSelector>,
4130 ignore_refcounts: bool,
4131 cx: &mut Context<Self>,
4132 ) -> OpenLspBufferHandle {
4133 let buffer_id = buffer.read(cx).remote_id();
4134 let handle = cx.new(|_| buffer.clone());
4135 if let Some(local) = self.as_local_mut() {
4136 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
4137 if !ignore_refcounts {
4138 *refcount += 1;
4139 }
4140
4141 // We run early exits on non-existing buffers AFTER we mark the buffer as registered in order to handle buffer saving.
4142 // When a new unnamed buffer is created and saved, we will start loading it's language. Once the language is loaded, we go over all "language-less" buffers and try to fit that new language
4143 // with them. However, we do that only for the buffers that we think are open in at least one editor; thus, we need to keep tab of unnamed buffers as well, even though they're not actually registered with any language
4144 // servers in practice (we don't support non-file URI schemes in our LSP impl).
4145 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
4146 return handle;
4147 };
4148 if !file.is_local() {
4149 return handle;
4150 }
4151
4152 if ignore_refcounts || *refcount == 1 {
4153 local.register_buffer_with_language_servers(buffer, only_register_servers, cx);
4154 }
4155 if !ignore_refcounts {
4156 cx.observe_release(&handle, move |lsp_store, buffer, cx| {
4157 let refcount = {
4158 let local = lsp_store.as_local_mut().unwrap();
4159 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
4160 debug_panic!("bad refcounting");
4161 return;
4162 };
4163
4164 *refcount -= 1;
4165 *refcount
4166 };
4167 if refcount == 0 {
4168 lsp_store.lsp_data.remove(&buffer_id);
4169 let local = lsp_store.as_local_mut().unwrap();
4170 local.registered_buffers.remove(&buffer_id);
4171 local.buffers_opened_in_servers.remove(&buffer_id);
4172 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
4173 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
4174 }
4175 }
4176 })
4177 .detach();
4178 }
4179 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4180 let buffer_id = buffer.read(cx).remote_id().to_proto();
4181 cx.background_spawn(async move {
4182 upstream_client
4183 .request(proto::RegisterBufferWithLanguageServers {
4184 project_id: upstream_project_id,
4185 buffer_id,
4186 only_servers: only_register_servers
4187 .into_iter()
4188 .map(|selector| {
4189 let selector = match selector {
4190 LanguageServerSelector::Id(language_server_id) => {
4191 proto::language_server_selector::Selector::ServerId(
4192 language_server_id.to_proto(),
4193 )
4194 }
4195 LanguageServerSelector::Name(language_server_name) => {
4196 proto::language_server_selector::Selector::Name(
4197 language_server_name.to_string(),
4198 )
4199 }
4200 };
4201 proto::LanguageServerSelector {
4202 selector: Some(selector),
4203 }
4204 })
4205 .collect(),
4206 })
4207 .await
4208 })
4209 .detach();
4210 } else {
4211 panic!("oops!");
4212 }
4213 handle
4214 }
4215
4216 fn maintain_buffer_languages(
4217 languages: Arc<LanguageRegistry>,
4218 cx: &mut Context<Self>,
4219 ) -> Task<()> {
4220 let mut subscription = languages.subscribe();
4221 let mut prev_reload_count = languages.reload_count();
4222 cx.spawn(async move |this, cx| {
4223 while let Some(()) = subscription.next().await {
4224 if let Some(this) = this.upgrade() {
4225 // If the language registry has been reloaded, then remove and
4226 // re-assign the languages on all open buffers.
4227 let reload_count = languages.reload_count();
4228 if reload_count > prev_reload_count {
4229 prev_reload_count = reload_count;
4230 this.update(cx, |this, cx| {
4231 this.buffer_store.clone().update(cx, |buffer_store, cx| {
4232 for buffer in buffer_store.buffers() {
4233 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
4234 {
4235 buffer
4236 .update(cx, |buffer, cx| buffer.set_language(None, cx));
4237 if let Some(local) = this.as_local_mut() {
4238 local.reset_buffer(&buffer, &f, cx);
4239
4240 if local
4241 .registered_buffers
4242 .contains_key(&buffer.read(cx).remote_id())
4243 {
4244 if let Some(file_url) =
4245 file_path_to_lsp_url(&f.abs_path(cx)).log_err()
4246 {
4247 local.unregister_buffer_from_language_servers(
4248 &buffer, &file_url, cx,
4249 );
4250 }
4251 }
4252 }
4253 }
4254 }
4255 });
4256 })
4257 .ok();
4258 }
4259
4260 this.update(cx, |this, cx| {
4261 let mut plain_text_buffers = Vec::new();
4262 let mut buffers_with_unknown_injections = Vec::new();
4263 for handle in this.buffer_store.read(cx).buffers() {
4264 let buffer = handle.read(cx);
4265 if buffer.language().is_none()
4266 || buffer.language() == Some(&*language::PLAIN_TEXT)
4267 {
4268 plain_text_buffers.push(handle);
4269 } else if buffer.contains_unknown_injections() {
4270 buffers_with_unknown_injections.push(handle);
4271 }
4272 }
4273
4274 // Deprioritize the invisible worktrees so main worktrees' language servers can be started first,
4275 // and reused later in the invisible worktrees.
4276 plain_text_buffers.sort_by_key(|buffer| {
4277 Reverse(
4278 File::from_dyn(buffer.read(cx).file())
4279 .map(|file| file.worktree.read(cx).is_visible()),
4280 )
4281 });
4282
4283 for buffer in plain_text_buffers {
4284 this.detect_language_for_buffer(&buffer, cx);
4285 if let Some(local) = this.as_local_mut() {
4286 local.initialize_buffer(&buffer, cx);
4287 if local
4288 .registered_buffers
4289 .contains_key(&buffer.read(cx).remote_id())
4290 {
4291 local.register_buffer_with_language_servers(
4292 &buffer,
4293 HashSet::default(),
4294 cx,
4295 );
4296 }
4297 }
4298 }
4299
4300 for buffer in buffers_with_unknown_injections {
4301 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4302 }
4303 })
4304 .ok();
4305 }
4306 }
4307 })
4308 }
4309
4310 fn detect_language_for_buffer(
4311 &mut self,
4312 buffer_handle: &Entity<Buffer>,
4313 cx: &mut Context<Self>,
4314 ) -> Option<language::AvailableLanguage> {
4315 // If the buffer has a language, set it and start the language server if we haven't already.
4316 let buffer = buffer_handle.read(cx);
4317 let file = buffer.file()?;
4318
4319 let content = buffer.as_rope();
4320 let available_language = self.languages.language_for_file(file, Some(content), cx);
4321 if let Some(available_language) = &available_language {
4322 if let Some(Ok(Ok(new_language))) = self
4323 .languages
4324 .load_language(available_language)
4325 .now_or_never()
4326 {
4327 self.set_language_for_buffer(buffer_handle, new_language, cx);
4328 }
4329 } else {
4330 cx.emit(LspStoreEvent::LanguageDetected {
4331 buffer: buffer_handle.clone(),
4332 new_language: None,
4333 });
4334 }
4335
4336 available_language
4337 }
4338
4339 pub(crate) fn set_language_for_buffer(
4340 &mut self,
4341 buffer_entity: &Entity<Buffer>,
4342 new_language: Arc<Language>,
4343 cx: &mut Context<Self>,
4344 ) {
4345 let buffer = buffer_entity.read(cx);
4346 let buffer_file = buffer.file().cloned();
4347 let buffer_id = buffer.remote_id();
4348 if let Some(local_store) = self.as_local_mut() {
4349 if local_store.registered_buffers.contains_key(&buffer_id) {
4350 if let Some(abs_path) =
4351 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4352 {
4353 if let Some(file_url) = file_path_to_lsp_url(&abs_path).log_err() {
4354 local_store.unregister_buffer_from_language_servers(
4355 buffer_entity,
4356 &file_url,
4357 cx,
4358 );
4359 }
4360 }
4361 }
4362 }
4363 buffer_entity.update(cx, |buffer, cx| {
4364 if buffer.language().map_or(true, |old_language| {
4365 !Arc::ptr_eq(old_language, &new_language)
4366 }) {
4367 buffer.set_language(Some(new_language.clone()), cx);
4368 }
4369 });
4370
4371 let settings =
4372 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4373 let buffer_file = File::from_dyn(buffer_file.as_ref());
4374
4375 let worktree_id = if let Some(file) = buffer_file {
4376 let worktree = file.worktree.clone();
4377
4378 if let Some(local) = self.as_local_mut() {
4379 if local.registered_buffers.contains_key(&buffer_id) {
4380 local.register_buffer_with_language_servers(
4381 buffer_entity,
4382 HashSet::default(),
4383 cx,
4384 );
4385 }
4386 }
4387 Some(worktree.read(cx).id())
4388 } else {
4389 None
4390 };
4391
4392 if settings.prettier.allowed {
4393 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4394 {
4395 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4396 if let Some(prettier_store) = prettier_store {
4397 prettier_store.update(cx, |prettier_store, cx| {
4398 prettier_store.install_default_prettier(
4399 worktree_id,
4400 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4401 cx,
4402 )
4403 })
4404 }
4405 }
4406 }
4407
4408 cx.emit(LspStoreEvent::LanguageDetected {
4409 buffer: buffer_entity.clone(),
4410 new_language: Some(new_language),
4411 })
4412 }
4413
4414 pub fn buffer_store(&self) -> Entity<BufferStore> {
4415 self.buffer_store.clone()
4416 }
4417
4418 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4419 self.active_entry = active_entry;
4420 }
4421
4422 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4423 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4424 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4425 for (path, summaries) in summaries {
4426 for (&server_id, summary) in summaries {
4427 client
4428 .send(proto::UpdateDiagnosticSummary {
4429 project_id: downstream_project_id,
4430 worktree_id: worktree.id().to_proto(),
4431 summary: Some(summary.to_proto(server_id, path)),
4432 })
4433 .log_err();
4434 }
4435 }
4436 }
4437 }
4438 }
4439
4440 pub fn request_lsp<R: LspCommand>(
4441 &mut self,
4442 buffer_handle: Entity<Buffer>,
4443 server: LanguageServerToQuery,
4444 request: R,
4445 cx: &mut Context<Self>,
4446 ) -> Task<Result<R::Response>>
4447 where
4448 <R::LspRequest as lsp::request::Request>::Result: Send,
4449 <R::LspRequest as lsp::request::Request>::Params: Send,
4450 {
4451 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4452 return self.send_lsp_proto_request(
4453 buffer_handle,
4454 upstream_client,
4455 upstream_project_id,
4456 request,
4457 cx,
4458 );
4459 }
4460
4461 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4462 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4463 local
4464 .language_servers_for_buffer(buffer, cx)
4465 .find(|(_, server)| {
4466 request.check_capabilities(server.adapter_server_capabilities())
4467 })
4468 .map(|(_, server)| server.clone())
4469 }),
4470 LanguageServerToQuery::Other(id) => self
4471 .language_server_for_local_buffer(buffer, id, cx)
4472 .and_then(|(_, server)| {
4473 request
4474 .check_capabilities(server.adapter_server_capabilities())
4475 .then(|| Arc::clone(server))
4476 }),
4477 }) else {
4478 return Task::ready(Ok(Default::default()));
4479 };
4480
4481 let buffer = buffer_handle.read(cx);
4482 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4483
4484 let Some(file) = file else {
4485 return Task::ready(Ok(Default::default()));
4486 };
4487
4488 let lsp_params = match request.to_lsp_params_or_response(
4489 &file.abs_path(cx),
4490 buffer,
4491 &language_server,
4492 cx,
4493 ) {
4494 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4495 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4496
4497 Err(err) => {
4498 let message = format!(
4499 "{} via {} failed: {}",
4500 request.display_name(),
4501 language_server.name(),
4502 err
4503 );
4504 log::warn!("{message}");
4505 return Task::ready(Err(anyhow!(message)));
4506 }
4507 };
4508
4509 let status = request.status();
4510 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4511 return Task::ready(Ok(Default::default()));
4512 }
4513 return cx.spawn(async move |this, cx| {
4514 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4515
4516 let id = lsp_request.id();
4517 let _cleanup = if status.is_some() {
4518 cx.update(|cx| {
4519 this.update(cx, |this, cx| {
4520 this.on_lsp_work_start(
4521 language_server.server_id(),
4522 id.to_string(),
4523 LanguageServerProgress {
4524 is_disk_based_diagnostics_progress: false,
4525 is_cancellable: false,
4526 title: None,
4527 message: status.clone(),
4528 percentage: None,
4529 last_update_at: cx.background_executor().now(),
4530 },
4531 cx,
4532 );
4533 })
4534 })
4535 .log_err();
4536
4537 Some(defer(|| {
4538 cx.update(|cx| {
4539 this.update(cx, |this, cx| {
4540 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4541 })
4542 })
4543 .log_err();
4544 }))
4545 } else {
4546 None
4547 };
4548
4549 let result = lsp_request.await.into_response();
4550
4551 let response = result.map_err(|err| {
4552 let message = format!(
4553 "{} via {} failed: {}",
4554 request.display_name(),
4555 language_server.name(),
4556 err
4557 );
4558 log::warn!("{message}");
4559 anyhow::anyhow!(message)
4560 })?;
4561
4562 let response = request
4563 .response_from_lsp(
4564 response,
4565 this.upgrade().context("no app context")?,
4566 buffer_handle,
4567 language_server.server_id(),
4568 cx.clone(),
4569 )
4570 .await;
4571 response
4572 });
4573 }
4574
4575 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4576 let mut language_formatters_to_check = Vec::new();
4577 for buffer in self.buffer_store.read(cx).buffers() {
4578 let buffer = buffer.read(cx);
4579 let buffer_file = File::from_dyn(buffer.file());
4580 let buffer_language = buffer.language();
4581 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4582 if buffer_language.is_some() {
4583 language_formatters_to_check.push((
4584 buffer_file.map(|f| f.worktree_id(cx)),
4585 settings.into_owned(),
4586 ));
4587 }
4588 }
4589
4590 self.refresh_server_tree(cx);
4591
4592 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4593 prettier_store.update(cx, |prettier_store, cx| {
4594 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4595 })
4596 }
4597
4598 cx.notify();
4599 }
4600
4601 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4602 let buffer_store = self.buffer_store.clone();
4603 if let Some(local) = self.as_local_mut() {
4604 let mut adapters = BTreeMap::default();
4605 let get_adapter = {
4606 let languages = local.languages.clone();
4607 let environment = local.environment.clone();
4608 let weak = local.weak.clone();
4609 let worktree_store = local.worktree_store.clone();
4610 let http_client = local.http_client.clone();
4611 let fs = local.fs.clone();
4612 move |worktree_id, cx: &mut App| {
4613 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4614 Some(LocalLspAdapterDelegate::new(
4615 languages.clone(),
4616 &environment,
4617 weak.clone(),
4618 &worktree,
4619 http_client.clone(),
4620 fs.clone(),
4621 cx,
4622 ))
4623 }
4624 };
4625
4626 let mut messages_to_report = Vec::new();
4627 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4628 let mut rebase = lsp_tree.rebase();
4629 for buffer_handle in buffer_store.read(cx).buffers().sorted_by_key(|buffer| {
4630 Reverse(
4631 File::from_dyn(buffer.read(cx).file())
4632 .map(|file| file.worktree.read(cx).is_visible()),
4633 )
4634 }) {
4635 let buffer = buffer_handle.read(cx);
4636 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4637 continue;
4638 }
4639 if let Some((file, language)) = File::from_dyn(buffer.file())
4640 .cloned()
4641 .zip(buffer.language().map(|l| l.name()))
4642 {
4643 let worktree_id = file.worktree_id(cx);
4644 let Some(worktree) = local
4645 .worktree_store
4646 .read(cx)
4647 .worktree_for_id(worktree_id, cx)
4648 else {
4649 continue;
4650 };
4651
4652 let Some((reused, delegate, nodes)) = local
4653 .reuse_existing_language_server(
4654 rebase.server_tree(),
4655 &worktree,
4656 &language,
4657 cx,
4658 )
4659 .map(|(delegate, servers)| (true, delegate, servers))
4660 .or_else(|| {
4661 let lsp_delegate = adapters
4662 .entry(worktree_id)
4663 .or_insert_with(|| get_adapter(worktree_id, cx))
4664 .clone()?;
4665 let delegate = Arc::new(ManifestQueryDelegate::new(
4666 worktree.read(cx).snapshot(),
4667 ));
4668 let path = file
4669 .path()
4670 .parent()
4671 .map(Arc::from)
4672 .unwrap_or_else(|| file.path().clone());
4673 let worktree_path = ProjectPath { worktree_id, path };
4674
4675 let nodes = rebase.get(
4676 worktree_path,
4677 AdapterQuery::Language(&language),
4678 delegate.clone(),
4679 cx,
4680 );
4681
4682 Some((false, lsp_delegate, nodes.collect()))
4683 })
4684 else {
4685 continue;
4686 };
4687
4688 let abs_path = file.abs_path(cx);
4689 for node in nodes {
4690 if !reused {
4691 let server_id = node.server_id_or_init(
4692 |LaunchDisposition {
4693 server_name,
4694 attach,
4695 path,
4696 settings,
4697 }| match attach {
4698 language::Attach::InstancePerRoot => {
4699 // todo: handle instance per root proper.
4700 if let Some(server_ids) = local
4701 .language_server_ids
4702 .get(&(worktree_id, server_name.clone()))
4703 {
4704 server_ids.iter().cloned().next().unwrap()
4705 } else {
4706 let adapter = local
4707 .languages
4708 .lsp_adapters(&language)
4709 .into_iter()
4710 .find(|adapter| &adapter.name() == server_name)
4711 .expect("To find LSP adapter");
4712 let server_id = local.start_language_server(
4713 &worktree,
4714 delegate.clone(),
4715 adapter,
4716 settings,
4717 cx,
4718 );
4719 server_id
4720 }
4721 }
4722 language::Attach::Shared => {
4723 let uri = Url::from_file_path(
4724 worktree.read(cx).abs_path().join(&path.path),
4725 );
4726 let key = (worktree_id, server_name.clone());
4727 local.language_server_ids.remove(&key);
4728
4729 let adapter = local
4730 .languages
4731 .lsp_adapters(&language)
4732 .into_iter()
4733 .find(|adapter| &adapter.name() == server_name)
4734 .expect("To find LSP adapter");
4735 let server_id = local.start_language_server(
4736 &worktree,
4737 delegate.clone(),
4738 adapter,
4739 settings,
4740 cx,
4741 );
4742 if let Some(state) =
4743 local.language_servers.get(&server_id)
4744 {
4745 if let Ok(uri) = uri {
4746 state.add_workspace_folder(uri);
4747 };
4748 }
4749 server_id
4750 }
4751 },
4752 );
4753
4754 if let Some(language_server_id) = server_id {
4755 messages_to_report.push(LspStoreEvent::LanguageServerUpdate {
4756 language_server_id,
4757 name: node.name(),
4758 message:
4759 proto::update_language_server::Variant::RegisteredForBuffer(
4760 proto::RegisteredForBuffer {
4761 buffer_abs_path: abs_path.to_string_lossy().to_string(),
4762 },
4763 ),
4764 });
4765 }
4766 }
4767 }
4768 }
4769 }
4770 rebase.finish()
4771 });
4772 for message in messages_to_report {
4773 cx.emit(message);
4774 }
4775 for (id, _) in to_stop {
4776 self.stop_local_language_server(id, cx).detach();
4777 }
4778 }
4779 }
4780
4781 pub fn apply_code_action(
4782 &self,
4783 buffer_handle: Entity<Buffer>,
4784 mut action: CodeAction,
4785 push_to_history: bool,
4786 cx: &mut Context<Self>,
4787 ) -> Task<Result<ProjectTransaction>> {
4788 if let Some((upstream_client, project_id)) = self.upstream_client() {
4789 let request = proto::ApplyCodeAction {
4790 project_id,
4791 buffer_id: buffer_handle.read(cx).remote_id().into(),
4792 action: Some(Self::serialize_code_action(&action)),
4793 };
4794 let buffer_store = self.buffer_store();
4795 cx.spawn(async move |_, cx| {
4796 let response = upstream_client
4797 .request(request)
4798 .await?
4799 .transaction
4800 .context("missing transaction")?;
4801
4802 buffer_store
4803 .update(cx, |buffer_store, cx| {
4804 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4805 })?
4806 .await
4807 })
4808 } else if self.mode.is_local() {
4809 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4810 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4811 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4812 }) else {
4813 return Task::ready(Ok(ProjectTransaction::default()));
4814 };
4815 cx.spawn(async move |this, cx| {
4816 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4817 .await
4818 .context("resolving a code action")?;
4819 if let Some(edit) = action.lsp_action.edit() {
4820 if edit.changes.is_some() || edit.document_changes.is_some() {
4821 return LocalLspStore::deserialize_workspace_edit(
4822 this.upgrade().context("no app present")?,
4823 edit.clone(),
4824 push_to_history,
4825 lsp_adapter.clone(),
4826 lang_server.clone(),
4827 cx,
4828 )
4829 .await;
4830 }
4831 }
4832
4833 if let Some(command) = action.lsp_action.command() {
4834 let server_capabilities = lang_server.capabilities();
4835 let available_commands = server_capabilities
4836 .execute_command_provider
4837 .as_ref()
4838 .map(|options| options.commands.as_slice())
4839 .unwrap_or_default();
4840 if available_commands.contains(&command.command) {
4841 this.update(cx, |this, _| {
4842 this.as_local_mut()
4843 .unwrap()
4844 .last_workspace_edits_by_language_server
4845 .remove(&lang_server.server_id());
4846 })?;
4847
4848 let _result = lang_server
4849 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4850 command: command.command.clone(),
4851 arguments: command.arguments.clone().unwrap_or_default(),
4852 ..lsp::ExecuteCommandParams::default()
4853 })
4854 .await.into_response()
4855 .context("execute command")?;
4856
4857 return this.update(cx, |this, _| {
4858 this.as_local_mut()
4859 .unwrap()
4860 .last_workspace_edits_by_language_server
4861 .remove(&lang_server.server_id())
4862 .unwrap_or_default()
4863 });
4864 } else {
4865 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4866 }
4867 }
4868
4869 Ok(ProjectTransaction::default())
4870 })
4871 } else {
4872 Task::ready(Err(anyhow!("no upstream client and not local")))
4873 }
4874 }
4875
4876 pub fn apply_code_action_kind(
4877 &mut self,
4878 buffers: HashSet<Entity<Buffer>>,
4879 kind: CodeActionKind,
4880 push_to_history: bool,
4881 cx: &mut Context<Self>,
4882 ) -> Task<anyhow::Result<ProjectTransaction>> {
4883 if let Some(_) = self.as_local() {
4884 cx.spawn(async move |lsp_store, cx| {
4885 let buffers = buffers.into_iter().collect::<Vec<_>>();
4886 let result = LocalLspStore::execute_code_action_kind_locally(
4887 lsp_store.clone(),
4888 buffers,
4889 kind,
4890 push_to_history,
4891 cx,
4892 )
4893 .await;
4894 lsp_store.update(cx, |lsp_store, _| {
4895 lsp_store.update_last_formatting_failure(&result);
4896 })?;
4897 result
4898 })
4899 } else if let Some((client, project_id)) = self.upstream_client() {
4900 let buffer_store = self.buffer_store();
4901 cx.spawn(async move |lsp_store, cx| {
4902 let result = client
4903 .request(proto::ApplyCodeActionKind {
4904 project_id,
4905 kind: kind.as_str().to_owned(),
4906 buffer_ids: buffers
4907 .iter()
4908 .map(|buffer| {
4909 buffer.read_with(cx, |buffer, _| buffer.remote_id().into())
4910 })
4911 .collect::<Result<_>>()?,
4912 })
4913 .await
4914 .and_then(|result| result.transaction.context("missing transaction"));
4915 lsp_store.update(cx, |lsp_store, _| {
4916 lsp_store.update_last_formatting_failure(&result);
4917 })?;
4918
4919 let transaction_response = result?;
4920 buffer_store
4921 .update(cx, |buffer_store, cx| {
4922 buffer_store.deserialize_project_transaction(
4923 transaction_response,
4924 push_to_history,
4925 cx,
4926 )
4927 })?
4928 .await
4929 })
4930 } else {
4931 Task::ready(Ok(ProjectTransaction::default()))
4932 }
4933 }
4934
4935 pub fn resolve_inlay_hint(
4936 &self,
4937 hint: InlayHint,
4938 buffer_handle: Entity<Buffer>,
4939 server_id: LanguageServerId,
4940 cx: &mut Context<Self>,
4941 ) -> Task<anyhow::Result<InlayHint>> {
4942 if let Some((upstream_client, project_id)) = self.upstream_client() {
4943 let request = proto::ResolveInlayHint {
4944 project_id,
4945 buffer_id: buffer_handle.read(cx).remote_id().into(),
4946 language_server_id: server_id.0 as u64,
4947 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4948 };
4949 cx.spawn(async move |_, _| {
4950 let response = upstream_client
4951 .request(request)
4952 .await
4953 .context("inlay hints proto request")?;
4954 match response.hint {
4955 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4956 .context("inlay hints proto resolve response conversion"),
4957 None => Ok(hint),
4958 }
4959 })
4960 } else {
4961 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4962 self.language_server_for_local_buffer(buffer, server_id, cx)
4963 .map(|(_, server)| server.clone())
4964 }) else {
4965 return Task::ready(Ok(hint));
4966 };
4967 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4968 return Task::ready(Ok(hint));
4969 }
4970 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4971 cx.spawn(async move |_, cx| {
4972 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4973 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4974 );
4975 let resolved_hint = resolve_task
4976 .await
4977 .into_response()
4978 .context("inlay hint resolve LSP request")?;
4979 let resolved_hint = InlayHints::lsp_to_project_hint(
4980 resolved_hint,
4981 &buffer_handle,
4982 server_id,
4983 ResolveState::Resolved,
4984 false,
4985 cx,
4986 )
4987 .await?;
4988 Ok(resolved_hint)
4989 })
4990 }
4991 }
4992
4993 pub fn resolve_color_presentation(
4994 &mut self,
4995 mut color: DocumentColor,
4996 buffer: Entity<Buffer>,
4997 server_id: LanguageServerId,
4998 cx: &mut Context<Self>,
4999 ) -> Task<Result<DocumentColor>> {
5000 if color.resolved {
5001 return Task::ready(Ok(color));
5002 }
5003
5004 if let Some((upstream_client, project_id)) = self.upstream_client() {
5005 let start = color.lsp_range.start;
5006 let end = color.lsp_range.end;
5007 let request = proto::GetColorPresentation {
5008 project_id,
5009 server_id: server_id.to_proto(),
5010 buffer_id: buffer.read(cx).remote_id().into(),
5011 color: Some(proto::ColorInformation {
5012 red: color.color.red,
5013 green: color.color.green,
5014 blue: color.color.blue,
5015 alpha: color.color.alpha,
5016 lsp_range_start: Some(proto::PointUtf16 {
5017 row: start.line,
5018 column: start.character,
5019 }),
5020 lsp_range_end: Some(proto::PointUtf16 {
5021 row: end.line,
5022 column: end.character,
5023 }),
5024 }),
5025 };
5026 cx.background_spawn(async move {
5027 let response = upstream_client
5028 .request(request)
5029 .await
5030 .context("color presentation proto request")?;
5031 color.resolved = true;
5032 color.color_presentations = response
5033 .presentations
5034 .into_iter()
5035 .map(|presentation| ColorPresentation {
5036 label: SharedString::from(presentation.label),
5037 text_edit: presentation.text_edit.and_then(deserialize_lsp_edit),
5038 additional_text_edits: presentation
5039 .additional_text_edits
5040 .into_iter()
5041 .filter_map(deserialize_lsp_edit)
5042 .collect(),
5043 })
5044 .collect();
5045 Ok(color)
5046 })
5047 } else {
5048 let path = match buffer
5049 .update(cx, |buffer, cx| {
5050 Some(File::from_dyn(buffer.file())?.abs_path(cx))
5051 })
5052 .context("buffer with the missing path")
5053 {
5054 Ok(path) => path,
5055 Err(e) => return Task::ready(Err(e)),
5056 };
5057 let Some(lang_server) = buffer.update(cx, |buffer, cx| {
5058 self.language_server_for_local_buffer(buffer, server_id, cx)
5059 .map(|(_, server)| server.clone())
5060 }) else {
5061 return Task::ready(Ok(color));
5062 };
5063 cx.background_spawn(async move {
5064 let resolve_task = lang_server.request::<lsp::request::ColorPresentationRequest>(
5065 lsp::ColorPresentationParams {
5066 text_document: make_text_document_identifier(&path)?,
5067 color: color.color,
5068 range: color.lsp_range,
5069 work_done_progress_params: Default::default(),
5070 partial_result_params: Default::default(),
5071 },
5072 );
5073 color.color_presentations = resolve_task
5074 .await
5075 .into_response()
5076 .context("color presentation resolve LSP request")?
5077 .into_iter()
5078 .map(|presentation| ColorPresentation {
5079 label: SharedString::from(presentation.label),
5080 text_edit: presentation.text_edit,
5081 additional_text_edits: presentation
5082 .additional_text_edits
5083 .unwrap_or_default(),
5084 })
5085 .collect();
5086 color.resolved = true;
5087 Ok(color)
5088 })
5089 }
5090 }
5091
5092 pub(crate) fn linked_edit(
5093 &mut self,
5094 buffer: &Entity<Buffer>,
5095 position: Anchor,
5096 cx: &mut Context<Self>,
5097 ) -> Task<Result<Vec<Range<Anchor>>>> {
5098 let snapshot = buffer.read(cx).snapshot();
5099 let scope = snapshot.language_scope_at(position);
5100 let Some(server_id) = self
5101 .as_local()
5102 .and_then(|local| {
5103 buffer.update(cx, |buffer, cx| {
5104 local
5105 .language_servers_for_buffer(buffer, cx)
5106 .filter(|(_, server)| {
5107 server
5108 .capabilities()
5109 .linked_editing_range_provider
5110 .is_some()
5111 })
5112 .filter(|(adapter, _)| {
5113 scope
5114 .as_ref()
5115 .map(|scope| scope.language_allowed(&adapter.name))
5116 .unwrap_or(true)
5117 })
5118 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
5119 .next()
5120 })
5121 })
5122 .or_else(|| {
5123 self.upstream_client()
5124 .is_some()
5125 .then_some(LanguageServerToQuery::FirstCapable)
5126 })
5127 .filter(|_| {
5128 maybe!({
5129 let language = buffer.read(cx).language_at(position)?;
5130 Some(
5131 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
5132 .linked_edits,
5133 )
5134 }) == Some(true)
5135 })
5136 else {
5137 return Task::ready(Ok(vec![]));
5138 };
5139
5140 self.request_lsp(
5141 buffer.clone(),
5142 server_id,
5143 LinkedEditingRange { position },
5144 cx,
5145 )
5146 }
5147
5148 fn apply_on_type_formatting(
5149 &mut self,
5150 buffer: Entity<Buffer>,
5151 position: Anchor,
5152 trigger: String,
5153 cx: &mut Context<Self>,
5154 ) -> Task<Result<Option<Transaction>>> {
5155 if let Some((client, project_id)) = self.upstream_client() {
5156 let request = proto::OnTypeFormatting {
5157 project_id,
5158 buffer_id: buffer.read(cx).remote_id().into(),
5159 position: Some(serialize_anchor(&position)),
5160 trigger,
5161 version: serialize_version(&buffer.read(cx).version()),
5162 };
5163 cx.spawn(async move |_, _| {
5164 client
5165 .request(request)
5166 .await?
5167 .transaction
5168 .map(language::proto::deserialize_transaction)
5169 .transpose()
5170 })
5171 } else if let Some(local) = self.as_local_mut() {
5172 let buffer_id = buffer.read(cx).remote_id();
5173 local.buffers_being_formatted.insert(buffer_id);
5174 cx.spawn(async move |this, cx| {
5175 let _cleanup = defer({
5176 let this = this.clone();
5177 let mut cx = cx.clone();
5178 move || {
5179 this.update(&mut cx, |this, _| {
5180 if let Some(local) = this.as_local_mut() {
5181 local.buffers_being_formatted.remove(&buffer_id);
5182 }
5183 })
5184 .ok();
5185 }
5186 });
5187
5188 buffer
5189 .update(cx, |buffer, _| {
5190 buffer.wait_for_edits(Some(position.timestamp))
5191 })?
5192 .await?;
5193 this.update(cx, |this, cx| {
5194 let position = position.to_point_utf16(buffer.read(cx));
5195 this.on_type_format(buffer, position, trigger, false, cx)
5196 })?
5197 .await
5198 })
5199 } else {
5200 Task::ready(Err(anyhow!("No upstream client or local language server")))
5201 }
5202 }
5203
5204 pub fn on_type_format<T: ToPointUtf16>(
5205 &mut self,
5206 buffer: Entity<Buffer>,
5207 position: T,
5208 trigger: String,
5209 push_to_history: bool,
5210 cx: &mut Context<Self>,
5211 ) -> Task<Result<Option<Transaction>>> {
5212 let position = position.to_point_utf16(buffer.read(cx));
5213 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5214 }
5215
5216 fn on_type_format_impl(
5217 &mut self,
5218 buffer: Entity<Buffer>,
5219 position: PointUtf16,
5220 trigger: String,
5221 push_to_history: bool,
5222 cx: &mut Context<Self>,
5223 ) -> Task<Result<Option<Transaction>>> {
5224 let options = buffer.update(cx, |buffer, cx| {
5225 lsp_command::lsp_formatting_options(
5226 language_settings(
5227 buffer.language_at(position).map(|l| l.name()),
5228 buffer.file(),
5229 cx,
5230 )
5231 .as_ref(),
5232 )
5233 });
5234
5235 cx.spawn(async move |this, cx| {
5236 if let Some(waiter) =
5237 buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())?
5238 {
5239 waiter.await?;
5240 }
5241 cx.update(|cx| {
5242 this.update(cx, |this, cx| {
5243 this.request_lsp(
5244 buffer.clone(),
5245 LanguageServerToQuery::FirstCapable,
5246 OnTypeFormatting {
5247 position,
5248 trigger,
5249 options,
5250 push_to_history,
5251 },
5252 cx,
5253 )
5254 })
5255 })??
5256 .await
5257 })
5258 }
5259
5260 pub fn code_actions(
5261 &mut self,
5262 buffer_handle: &Entity<Buffer>,
5263 range: Range<Anchor>,
5264 kinds: Option<Vec<CodeActionKind>>,
5265 cx: &mut Context<Self>,
5266 ) -> Task<Result<Vec<CodeAction>>> {
5267 if let Some((upstream_client, project_id)) = self.upstream_client() {
5268 let request_task = upstream_client.request(proto::MultiLspQuery {
5269 buffer_id: buffer_handle.read(cx).remote_id().into(),
5270 version: serialize_version(&buffer_handle.read(cx).version()),
5271 project_id,
5272 strategy: Some(proto::multi_lsp_query::Strategy::All(
5273 proto::AllLanguageServers {},
5274 )),
5275 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
5276 GetCodeActions {
5277 range: range.clone(),
5278 kinds: kinds.clone(),
5279 }
5280 .to_proto(project_id, buffer_handle.read(cx)),
5281 )),
5282 });
5283 let buffer = buffer_handle.clone();
5284 cx.spawn(async move |weak_project, cx| {
5285 let Some(project) = weak_project.upgrade() else {
5286 return Ok(Vec::new());
5287 };
5288 let responses = request_task.await?.responses;
5289 let actions = join_all(
5290 responses
5291 .into_iter()
5292 .filter_map(|lsp_response| match lsp_response.response? {
5293 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
5294 Some(response)
5295 }
5296 unexpected => {
5297 debug_panic!("Unexpected response: {unexpected:?}");
5298 None
5299 }
5300 })
5301 .map(|code_actions_response| {
5302 GetCodeActions {
5303 range: range.clone(),
5304 kinds: kinds.clone(),
5305 }
5306 .response_from_proto(
5307 code_actions_response,
5308 project.clone(),
5309 buffer.clone(),
5310 cx.clone(),
5311 )
5312 }),
5313 )
5314 .await;
5315
5316 Ok(actions
5317 .into_iter()
5318 .collect::<Result<Vec<Vec<_>>>>()?
5319 .into_iter()
5320 .flatten()
5321 .collect())
5322 })
5323 } else {
5324 let all_actions_task = self.request_multiple_lsp_locally(
5325 buffer_handle,
5326 Some(range.start),
5327 GetCodeActions {
5328 range: range.clone(),
5329 kinds: kinds.clone(),
5330 },
5331 cx,
5332 );
5333 cx.spawn(async move |_, _| {
5334 Ok(all_actions_task
5335 .await
5336 .into_iter()
5337 .flat_map(|(_, actions)| actions)
5338 .collect())
5339 })
5340 }
5341 }
5342
5343 pub fn code_lens(
5344 &mut self,
5345 buffer_handle: &Entity<Buffer>,
5346 cx: &mut Context<Self>,
5347 ) -> Task<Result<Vec<CodeAction>>> {
5348 if let Some((upstream_client, project_id)) = self.upstream_client() {
5349 let request_task = upstream_client.request(proto::MultiLspQuery {
5350 buffer_id: buffer_handle.read(cx).remote_id().into(),
5351 version: serialize_version(&buffer_handle.read(cx).version()),
5352 project_id,
5353 strategy: Some(proto::multi_lsp_query::Strategy::All(
5354 proto::AllLanguageServers {},
5355 )),
5356 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
5357 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
5358 )),
5359 });
5360 let buffer = buffer_handle.clone();
5361 cx.spawn(async move |weak_project, cx| {
5362 let Some(project) = weak_project.upgrade() else {
5363 return Ok(Vec::new());
5364 };
5365 let responses = request_task.await?.responses;
5366 let code_lens = join_all(
5367 responses
5368 .into_iter()
5369 .filter_map(|lsp_response| match lsp_response.response? {
5370 proto::lsp_response::Response::GetCodeLensResponse(response) => {
5371 Some(response)
5372 }
5373 unexpected => {
5374 debug_panic!("Unexpected response: {unexpected:?}");
5375 None
5376 }
5377 })
5378 .map(|code_lens_response| {
5379 GetCodeLens.response_from_proto(
5380 code_lens_response,
5381 project.clone(),
5382 buffer.clone(),
5383 cx.clone(),
5384 )
5385 }),
5386 )
5387 .await;
5388
5389 Ok(code_lens
5390 .into_iter()
5391 .collect::<Result<Vec<Vec<_>>>>()?
5392 .into_iter()
5393 .flatten()
5394 .collect())
5395 })
5396 } else {
5397 let code_lens_task =
5398 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
5399 cx.spawn(async move |_, _| {
5400 Ok(code_lens_task
5401 .await
5402 .into_iter()
5403 .flat_map(|(_, code_lens)| code_lens)
5404 .collect())
5405 })
5406 }
5407 }
5408
5409 #[inline(never)]
5410 pub fn completions(
5411 &self,
5412 buffer: &Entity<Buffer>,
5413 position: PointUtf16,
5414 context: CompletionContext,
5415 cx: &mut Context<Self>,
5416 ) -> Task<Result<Vec<CompletionResponse>>> {
5417 let language_registry = self.languages.clone();
5418
5419 if let Some((upstream_client, project_id)) = self.upstream_client() {
5420 let task = self.send_lsp_proto_request(
5421 buffer.clone(),
5422 upstream_client,
5423 project_id,
5424 GetCompletions { position, context },
5425 cx,
5426 );
5427 let language = buffer.read(cx).language().cloned();
5428
5429 // In the future, we should provide project guests with the names of LSP adapters,
5430 // so that they can use the correct LSP adapter when computing labels. For now,
5431 // guests just use the first LSP adapter associated with the buffer's language.
5432 let lsp_adapter = language.as_ref().and_then(|language| {
5433 language_registry
5434 .lsp_adapters(&language.name())
5435 .first()
5436 .cloned()
5437 });
5438
5439 cx.foreground_executor().spawn(async move {
5440 let completion_response = task.await?;
5441 let completions = populate_labels_for_completions(
5442 completion_response.completions,
5443 language,
5444 lsp_adapter,
5445 )
5446 .await;
5447 Ok(vec![CompletionResponse {
5448 completions,
5449 is_incomplete: completion_response.is_incomplete,
5450 }])
5451 })
5452 } else if let Some(local) = self.as_local() {
5453 let snapshot = buffer.read(cx).snapshot();
5454 let offset = position.to_offset(&snapshot);
5455 let scope = snapshot.language_scope_at(offset);
5456 let language = snapshot.language().cloned();
5457 let completion_settings = language_settings(
5458 language.as_ref().map(|language| language.name()),
5459 buffer.read(cx).file(),
5460 cx,
5461 )
5462 .completions;
5463 if !completion_settings.lsp {
5464 return Task::ready(Ok(Vec::new()));
5465 }
5466
5467 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5468 local
5469 .language_servers_for_buffer(buffer, cx)
5470 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5471 .filter(|(adapter, _)| {
5472 scope
5473 .as_ref()
5474 .map(|scope| scope.language_allowed(&adapter.name))
5475 .unwrap_or(true)
5476 })
5477 .map(|(_, server)| server.server_id())
5478 .collect()
5479 });
5480
5481 let buffer = buffer.clone();
5482 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5483 let lsp_timeout = if lsp_timeout > 0 {
5484 Some(Duration::from_millis(lsp_timeout))
5485 } else {
5486 None
5487 };
5488 cx.spawn(async move |this, cx| {
5489 let mut tasks = Vec::with_capacity(server_ids.len());
5490 this.update(cx, |lsp_store, cx| {
5491 for server_id in server_ids {
5492 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5493 let lsp_timeout = lsp_timeout
5494 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5495 let mut timeout = cx.background_spawn(async move {
5496 match lsp_timeout {
5497 Some(lsp_timeout) => {
5498 lsp_timeout.await;
5499 true
5500 },
5501 None => false,
5502 }
5503 }).fuse();
5504 let mut lsp_request = lsp_store.request_lsp(
5505 buffer.clone(),
5506 LanguageServerToQuery::Other(server_id),
5507 GetCompletions {
5508 position,
5509 context: context.clone(),
5510 },
5511 cx,
5512 ).fuse();
5513 let new_task = cx.background_spawn(async move {
5514 select_biased! {
5515 response = lsp_request => anyhow::Ok(Some(response?)),
5516 timeout_happened = timeout => {
5517 if timeout_happened {
5518 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5519 Ok(None)
5520 } else {
5521 let completions = lsp_request.await?;
5522 Ok(Some(completions))
5523 }
5524 },
5525 }
5526 });
5527 tasks.push((lsp_adapter, new_task));
5528 }
5529 })?;
5530
5531 let futures = tasks.into_iter().map(async |(lsp_adapter, task)| {
5532 let completion_response = task.await.ok()??;
5533 let completions = populate_labels_for_completions(
5534 completion_response.completions,
5535 language.clone(),
5536 lsp_adapter,
5537 )
5538 .await;
5539 Some(CompletionResponse {
5540 completions,
5541 is_incomplete: completion_response.is_incomplete,
5542 })
5543 });
5544
5545 let responses: Vec<Option<CompletionResponse>> = join_all(futures).await;
5546
5547 Ok(responses.into_iter().flatten().collect())
5548 })
5549 } else {
5550 Task::ready(Err(anyhow!("No upstream client or local language server")))
5551 }
5552 }
5553
5554 pub fn resolve_completions(
5555 &self,
5556 buffer: Entity<Buffer>,
5557 completion_indices: Vec<usize>,
5558 completions: Rc<RefCell<Box<[Completion]>>>,
5559 cx: &mut Context<Self>,
5560 ) -> Task<Result<bool>> {
5561 let client = self.upstream_client();
5562
5563 let buffer_id = buffer.read(cx).remote_id();
5564 let buffer_snapshot = buffer.read(cx).snapshot();
5565
5566 cx.spawn(async move |this, cx| {
5567 let mut did_resolve = false;
5568 if let Some((client, project_id)) = client {
5569 for completion_index in completion_indices {
5570 let server_id = {
5571 let completion = &completions.borrow()[completion_index];
5572 completion.source.server_id()
5573 };
5574 if let Some(server_id) = server_id {
5575 if Self::resolve_completion_remote(
5576 project_id,
5577 server_id,
5578 buffer_id,
5579 completions.clone(),
5580 completion_index,
5581 client.clone(),
5582 )
5583 .await
5584 .log_err()
5585 .is_some()
5586 {
5587 did_resolve = true;
5588 }
5589 } else {
5590 resolve_word_completion(
5591 &buffer_snapshot,
5592 &mut completions.borrow_mut()[completion_index],
5593 );
5594 }
5595 }
5596 } else {
5597 for completion_index in completion_indices {
5598 let server_id = {
5599 let completion = &completions.borrow()[completion_index];
5600 completion.source.server_id()
5601 };
5602 if let Some(server_id) = server_id {
5603 let server_and_adapter = this
5604 .read_with(cx, |lsp_store, _| {
5605 let server = lsp_store.language_server_for_id(server_id)?;
5606 let adapter =
5607 lsp_store.language_server_adapter_for_id(server.server_id())?;
5608 Some((server, adapter))
5609 })
5610 .ok()
5611 .flatten();
5612 let Some((server, adapter)) = server_and_adapter else {
5613 continue;
5614 };
5615
5616 let resolved = Self::resolve_completion_local(
5617 server,
5618 &buffer_snapshot,
5619 completions.clone(),
5620 completion_index,
5621 )
5622 .await
5623 .log_err()
5624 .is_some();
5625 if resolved {
5626 Self::regenerate_completion_labels(
5627 adapter,
5628 &buffer_snapshot,
5629 completions.clone(),
5630 completion_index,
5631 )
5632 .await
5633 .log_err();
5634 did_resolve = true;
5635 }
5636 } else {
5637 resolve_word_completion(
5638 &buffer_snapshot,
5639 &mut completions.borrow_mut()[completion_index],
5640 );
5641 }
5642 }
5643 }
5644
5645 Ok(did_resolve)
5646 })
5647 }
5648
5649 async fn resolve_completion_local(
5650 server: Arc<lsp::LanguageServer>,
5651 snapshot: &BufferSnapshot,
5652 completions: Rc<RefCell<Box<[Completion]>>>,
5653 completion_index: usize,
5654 ) -> Result<()> {
5655 let server_id = server.server_id();
5656 let can_resolve = server
5657 .capabilities()
5658 .completion_provider
5659 .as_ref()
5660 .and_then(|options| options.resolve_provider)
5661 .unwrap_or(false);
5662 if !can_resolve {
5663 return Ok(());
5664 }
5665
5666 let request = {
5667 let completion = &completions.borrow()[completion_index];
5668 match &completion.source {
5669 CompletionSource::Lsp {
5670 lsp_completion,
5671 resolved,
5672 server_id: completion_server_id,
5673 ..
5674 } => {
5675 if *resolved {
5676 return Ok(());
5677 }
5678 anyhow::ensure!(
5679 server_id == *completion_server_id,
5680 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5681 );
5682 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5683 }
5684 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5685 return Ok(());
5686 }
5687 }
5688 };
5689 let resolved_completion = request
5690 .await
5691 .into_response()
5692 .context("resolve completion")?;
5693
5694 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5695 // Technically we don't have to parse the whole `text_edit`, since the only
5696 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5697 // is `typescript-language-server` and they only update `text_edit.new_text`.
5698 // But we should not rely on that.
5699 let edit = parse_completion_text_edit(text_edit, snapshot);
5700
5701 if let Some(mut parsed_edit) = edit {
5702 LineEnding::normalize(&mut parsed_edit.new_text);
5703
5704 let mut completions = completions.borrow_mut();
5705 let completion = &mut completions[completion_index];
5706
5707 completion.new_text = parsed_edit.new_text;
5708 completion.replace_range = parsed_edit.replace_range;
5709 if let CompletionSource::Lsp { insert_range, .. } = &mut completion.source {
5710 *insert_range = parsed_edit.insert_range;
5711 }
5712 }
5713 }
5714
5715 let mut completions = completions.borrow_mut();
5716 let completion = &mut completions[completion_index];
5717 if let CompletionSource::Lsp {
5718 lsp_completion,
5719 resolved,
5720 server_id: completion_server_id,
5721 ..
5722 } = &mut completion.source
5723 {
5724 if *resolved {
5725 return Ok(());
5726 }
5727 anyhow::ensure!(
5728 server_id == *completion_server_id,
5729 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5730 );
5731 *lsp_completion = Box::new(resolved_completion);
5732 *resolved = true;
5733 }
5734 Ok(())
5735 }
5736
5737 async fn regenerate_completion_labels(
5738 adapter: Arc<CachedLspAdapter>,
5739 snapshot: &BufferSnapshot,
5740 completions: Rc<RefCell<Box<[Completion]>>>,
5741 completion_index: usize,
5742 ) -> Result<()> {
5743 let completion_item = completions.borrow()[completion_index]
5744 .source
5745 .lsp_completion(true)
5746 .map(Cow::into_owned);
5747 if let Some(lsp_documentation) = completion_item
5748 .as_ref()
5749 .and_then(|completion_item| completion_item.documentation.clone())
5750 {
5751 let mut completions = completions.borrow_mut();
5752 let completion = &mut completions[completion_index];
5753 completion.documentation = Some(lsp_documentation.into());
5754 } else {
5755 let mut completions = completions.borrow_mut();
5756 let completion = &mut completions[completion_index];
5757 completion.documentation = Some(CompletionDocumentation::Undocumented);
5758 }
5759
5760 let mut new_label = match completion_item {
5761 Some(completion_item) => {
5762 // NB: Zed does not have `details` inside the completion resolve capabilities, but certain language servers violate the spec and do not return `details` immediately, e.g. https://github.com/yioneko/vtsls/issues/213
5763 // So we have to update the label here anyway...
5764 let language = snapshot.language();
5765 match language {
5766 Some(language) => {
5767 adapter
5768 .labels_for_completions(
5769 std::slice::from_ref(&completion_item),
5770 language,
5771 )
5772 .await?
5773 }
5774 None => Vec::new(),
5775 }
5776 .pop()
5777 .flatten()
5778 .unwrap_or_else(|| {
5779 CodeLabel::fallback_for_completion(
5780 &completion_item,
5781 language.map(|language| language.as_ref()),
5782 )
5783 })
5784 }
5785 None => CodeLabel::plain(
5786 completions.borrow()[completion_index].new_text.clone(),
5787 None,
5788 ),
5789 };
5790 ensure_uniform_list_compatible_label(&mut new_label);
5791
5792 let mut completions = completions.borrow_mut();
5793 let completion = &mut completions[completion_index];
5794 if completion.label.filter_text() == new_label.filter_text() {
5795 completion.label = new_label;
5796 } else {
5797 log::error!(
5798 "Resolved completion changed display label from {} to {}. \
5799 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5800 completion.label.text(),
5801 new_label.text(),
5802 completion.label.filter_text(),
5803 new_label.filter_text()
5804 );
5805 }
5806
5807 Ok(())
5808 }
5809
5810 async fn resolve_completion_remote(
5811 project_id: u64,
5812 server_id: LanguageServerId,
5813 buffer_id: BufferId,
5814 completions: Rc<RefCell<Box<[Completion]>>>,
5815 completion_index: usize,
5816 client: AnyProtoClient,
5817 ) -> Result<()> {
5818 let lsp_completion = {
5819 let completion = &completions.borrow()[completion_index];
5820 match &completion.source {
5821 CompletionSource::Lsp {
5822 lsp_completion,
5823 resolved,
5824 server_id: completion_server_id,
5825 ..
5826 } => {
5827 anyhow::ensure!(
5828 server_id == *completion_server_id,
5829 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5830 );
5831 if *resolved {
5832 return Ok(());
5833 }
5834 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5835 }
5836 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5837 return Ok(());
5838 }
5839 }
5840 };
5841 let request = proto::ResolveCompletionDocumentation {
5842 project_id,
5843 language_server_id: server_id.0 as u64,
5844 lsp_completion,
5845 buffer_id: buffer_id.into(),
5846 };
5847
5848 let response = client
5849 .request(request)
5850 .await
5851 .context("completion documentation resolve proto request")?;
5852 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5853
5854 let documentation = if response.documentation.is_empty() {
5855 CompletionDocumentation::Undocumented
5856 } else if response.documentation_is_markdown {
5857 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5858 } else if response.documentation.lines().count() <= 1 {
5859 CompletionDocumentation::SingleLine(response.documentation.into())
5860 } else {
5861 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5862 };
5863
5864 let mut completions = completions.borrow_mut();
5865 let completion = &mut completions[completion_index];
5866 completion.documentation = Some(documentation);
5867 if let CompletionSource::Lsp {
5868 insert_range,
5869 lsp_completion,
5870 resolved,
5871 server_id: completion_server_id,
5872 lsp_defaults: _,
5873 } = &mut completion.source
5874 {
5875 let completion_insert_range = response
5876 .old_insert_start
5877 .and_then(deserialize_anchor)
5878 .zip(response.old_insert_end.and_then(deserialize_anchor));
5879 *insert_range = completion_insert_range.map(|(start, end)| start..end);
5880
5881 if *resolved {
5882 return Ok(());
5883 }
5884 anyhow::ensure!(
5885 server_id == *completion_server_id,
5886 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5887 );
5888 *lsp_completion = Box::new(resolved_lsp_completion);
5889 *resolved = true;
5890 }
5891
5892 let replace_range = response
5893 .old_replace_start
5894 .and_then(deserialize_anchor)
5895 .zip(response.old_replace_end.and_then(deserialize_anchor));
5896 if let Some((old_replace_start, old_replace_end)) = replace_range {
5897 if !response.new_text.is_empty() {
5898 completion.new_text = response.new_text;
5899 completion.replace_range = old_replace_start..old_replace_end;
5900 }
5901 }
5902
5903 Ok(())
5904 }
5905
5906 pub fn apply_additional_edits_for_completion(
5907 &self,
5908 buffer_handle: Entity<Buffer>,
5909 completions: Rc<RefCell<Box<[Completion]>>>,
5910 completion_index: usize,
5911 push_to_history: bool,
5912 cx: &mut Context<Self>,
5913 ) -> Task<Result<Option<Transaction>>> {
5914 if let Some((client, project_id)) = self.upstream_client() {
5915 let buffer = buffer_handle.read(cx);
5916 let buffer_id = buffer.remote_id();
5917 cx.spawn(async move |_, cx| {
5918 let request = {
5919 let completion = completions.borrow()[completion_index].clone();
5920 proto::ApplyCompletionAdditionalEdits {
5921 project_id,
5922 buffer_id: buffer_id.into(),
5923 completion: Some(Self::serialize_completion(&CoreCompletion {
5924 replace_range: completion.replace_range,
5925 new_text: completion.new_text,
5926 source: completion.source,
5927 })),
5928 }
5929 };
5930
5931 if let Some(transaction) = client.request(request).await?.transaction {
5932 let transaction = language::proto::deserialize_transaction(transaction)?;
5933 buffer_handle
5934 .update(cx, |buffer, _| {
5935 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5936 })?
5937 .await?;
5938 if push_to_history {
5939 buffer_handle.update(cx, |buffer, _| {
5940 buffer.push_transaction(transaction.clone(), Instant::now());
5941 buffer.finalize_last_transaction();
5942 })?;
5943 }
5944 Ok(Some(transaction))
5945 } else {
5946 Ok(None)
5947 }
5948 })
5949 } else {
5950 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5951 let completion = &completions.borrow()[completion_index];
5952 let server_id = completion.source.server_id()?;
5953 Some(
5954 self.language_server_for_local_buffer(buffer, server_id, cx)?
5955 .1
5956 .clone(),
5957 )
5958 }) else {
5959 return Task::ready(Ok(None));
5960 };
5961 let snapshot = buffer_handle.read(&cx).snapshot();
5962
5963 cx.spawn(async move |this, cx| {
5964 Self::resolve_completion_local(
5965 server.clone(),
5966 &snapshot,
5967 completions.clone(),
5968 completion_index,
5969 )
5970 .await
5971 .context("resolving completion")?;
5972 let completion = completions.borrow()[completion_index].clone();
5973 let additional_text_edits = completion
5974 .source
5975 .lsp_completion(true)
5976 .as_ref()
5977 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5978 if let Some(edits) = additional_text_edits {
5979 let edits = this
5980 .update(cx, |this, cx| {
5981 this.as_local_mut().unwrap().edits_from_lsp(
5982 &buffer_handle,
5983 edits,
5984 server.server_id(),
5985 None,
5986 cx,
5987 )
5988 })?
5989 .await?;
5990
5991 buffer_handle.update(cx, |buffer, cx| {
5992 buffer.finalize_last_transaction();
5993 buffer.start_transaction();
5994
5995 for (range, text) in edits {
5996 let primary = &completion.replace_range;
5997 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5998 && primary.end.cmp(&range.start, buffer).is_ge();
5999 let end_within = range.start.cmp(&primary.end, buffer).is_le()
6000 && range.end.cmp(&primary.end, buffer).is_ge();
6001
6002 //Skip additional edits which overlap with the primary completion edit
6003 //https://github.com/zed-industries/zed/pull/1871
6004 if !start_within && !end_within {
6005 buffer.edit([(range, text)], None, cx);
6006 }
6007 }
6008
6009 let transaction = if buffer.end_transaction(cx).is_some() {
6010 let transaction = buffer.finalize_last_transaction().unwrap().clone();
6011 if !push_to_history {
6012 buffer.forget_transaction(transaction.id);
6013 }
6014 Some(transaction)
6015 } else {
6016 None
6017 };
6018 Ok(transaction)
6019 })?
6020 } else {
6021 Ok(None)
6022 }
6023 })
6024 }
6025 }
6026
6027 pub fn pull_diagnostics(
6028 &mut self,
6029 buffer_handle: Entity<Buffer>,
6030 cx: &mut Context<Self>,
6031 ) -> Task<Result<Vec<LspPullDiagnostics>>> {
6032 let buffer = buffer_handle.read(cx);
6033 let buffer_id = buffer.remote_id();
6034
6035 if let Some((client, upstream_project_id)) = self.upstream_client() {
6036 let request_task = client.request(proto::MultiLspQuery {
6037 buffer_id: buffer_id.to_proto(),
6038 version: serialize_version(&buffer_handle.read(cx).version()),
6039 project_id: upstream_project_id,
6040 strategy: Some(proto::multi_lsp_query::Strategy::All(
6041 proto::AllLanguageServers {},
6042 )),
6043 request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
6044 proto::GetDocumentDiagnostics {
6045 project_id: upstream_project_id,
6046 buffer_id: buffer_id.to_proto(),
6047 version: serialize_version(&buffer_handle.read(cx).version()),
6048 },
6049 )),
6050 });
6051 cx.background_spawn(async move {
6052 Ok(request_task
6053 .await?
6054 .responses
6055 .into_iter()
6056 .filter_map(|lsp_response| match lsp_response.response? {
6057 proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
6058 Some(response)
6059 }
6060 unexpected => {
6061 debug_panic!("Unexpected response: {unexpected:?}");
6062 None
6063 }
6064 })
6065 .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
6066 .collect())
6067 })
6068 } else {
6069 let server_ids = buffer_handle.update(cx, |buffer, cx| {
6070 self.language_servers_for_local_buffer(buffer, cx)
6071 .map(|(_, server)| server.server_id())
6072 .collect::<Vec<_>>()
6073 });
6074 let pull_diagnostics = server_ids
6075 .into_iter()
6076 .map(|server_id| {
6077 let result_id = self.result_id(server_id, buffer_id, cx);
6078 self.request_lsp(
6079 buffer_handle.clone(),
6080 LanguageServerToQuery::Other(server_id),
6081 GetDocumentDiagnostics {
6082 previous_result_id: result_id,
6083 },
6084 cx,
6085 )
6086 })
6087 .collect::<Vec<_>>();
6088
6089 cx.background_spawn(async move {
6090 let mut responses = Vec::new();
6091 for diagnostics in join_all(pull_diagnostics).await {
6092 responses.extend(diagnostics?);
6093 }
6094 Ok(responses)
6095 })
6096 }
6097 }
6098
6099 pub fn inlay_hints(
6100 &mut self,
6101 buffer_handle: Entity<Buffer>,
6102 range: Range<Anchor>,
6103 cx: &mut Context<Self>,
6104 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6105 let buffer = buffer_handle.read(cx);
6106 let range_start = range.start;
6107 let range_end = range.end;
6108 let buffer_id = buffer.remote_id().into();
6109 let lsp_request = InlayHints { range };
6110
6111 if let Some((client, project_id)) = self.upstream_client() {
6112 let request = proto::InlayHints {
6113 project_id,
6114 buffer_id,
6115 start: Some(serialize_anchor(&range_start)),
6116 end: Some(serialize_anchor(&range_end)),
6117 version: serialize_version(&buffer_handle.read(cx).version()),
6118 };
6119 cx.spawn(async move |project, cx| {
6120 let response = client
6121 .request(request)
6122 .await
6123 .context("inlay hints proto request")?;
6124 LspCommand::response_from_proto(
6125 lsp_request,
6126 response,
6127 project.upgrade().context("No project")?,
6128 buffer_handle.clone(),
6129 cx.clone(),
6130 )
6131 .await
6132 .context("inlay hints proto response conversion")
6133 })
6134 } else {
6135 let lsp_request_task = self.request_lsp(
6136 buffer_handle.clone(),
6137 LanguageServerToQuery::FirstCapable,
6138 lsp_request,
6139 cx,
6140 );
6141 cx.spawn(async move |_, cx| {
6142 buffer_handle
6143 .update(cx, |buffer, _| {
6144 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6145 })?
6146 .await
6147 .context("waiting for inlay hint request range edits")?;
6148 lsp_request_task.await.context("inlay hints LSP request")
6149 })
6150 }
6151 }
6152
6153 pub fn pull_diagnostics_for_buffer(
6154 &mut self,
6155 buffer: Entity<Buffer>,
6156 cx: &mut Context<Self>,
6157 ) -> Task<anyhow::Result<()>> {
6158 let buffer_id = buffer.read(cx).remote_id();
6159 let diagnostics = self.pull_diagnostics(buffer, cx);
6160 cx.spawn(async move |lsp_store, cx| {
6161 let diagnostics = diagnostics.await.context("pulling diagnostics")?;
6162 lsp_store.update(cx, |lsp_store, cx| {
6163 if lsp_store.as_local().is_none() {
6164 return;
6165 }
6166
6167 for diagnostics_set in diagnostics {
6168 let LspPullDiagnostics::Response {
6169 server_id,
6170 uri,
6171 diagnostics,
6172 } = diagnostics_set
6173 else {
6174 continue;
6175 };
6176
6177 let adapter = lsp_store.language_server_adapter_for_id(server_id);
6178 let disk_based_sources = adapter
6179 .as_ref()
6180 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
6181 .unwrap_or(&[]);
6182 match diagnostics {
6183 PulledDiagnostics::Unchanged { result_id } => {
6184 lsp_store
6185 .merge_diagnostics(
6186 server_id,
6187 lsp::PublishDiagnosticsParams {
6188 uri: uri.clone(),
6189 diagnostics: Vec::new(),
6190 version: None,
6191 },
6192 Some(result_id),
6193 DiagnosticSourceKind::Pulled,
6194 disk_based_sources,
6195 |_, _, _| true,
6196 cx,
6197 )
6198 .log_err();
6199 }
6200 PulledDiagnostics::Changed {
6201 diagnostics,
6202 result_id,
6203 } => {
6204 lsp_store
6205 .merge_diagnostics(
6206 server_id,
6207 lsp::PublishDiagnosticsParams {
6208 uri: uri.clone(),
6209 diagnostics,
6210 version: None,
6211 },
6212 result_id,
6213 DiagnosticSourceKind::Pulled,
6214 disk_based_sources,
6215 |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
6216 DiagnosticSourceKind::Pulled => {
6217 buffer.remote_id() != buffer_id
6218 }
6219 DiagnosticSourceKind::Other
6220 | DiagnosticSourceKind::Pushed => true,
6221 },
6222 cx,
6223 )
6224 .log_err();
6225 }
6226 }
6227 }
6228 })
6229 })
6230 }
6231
6232 pub fn document_colors(
6233 &mut self,
6234 fetch_strategy: ColorFetchStrategy,
6235 buffer: Entity<Buffer>,
6236 cx: &mut Context<Self>,
6237 ) -> Option<DocumentColorTask> {
6238 let version_queried_for = buffer.read(cx).version();
6239 let buffer_id = buffer.read(cx).remote_id();
6240
6241 match fetch_strategy {
6242 ColorFetchStrategy::IgnoreCache => {}
6243 ColorFetchStrategy::UseCache {
6244 known_cache_version,
6245 } => {
6246 if let Some(cached_data) = self.lsp_data.get(&buffer_id) {
6247 if !version_queried_for.changed_since(&cached_data.colors_for_version) {
6248 let has_different_servers = self.as_local().is_some_and(|local| {
6249 local
6250 .buffers_opened_in_servers
6251 .get(&buffer_id)
6252 .cloned()
6253 .unwrap_or_default()
6254 != cached_data.colors.keys().copied().collect()
6255 });
6256 if !has_different_servers {
6257 if Some(cached_data.cache_version) == known_cache_version {
6258 return None;
6259 } else {
6260 return Some(
6261 Task::ready(Ok(DocumentColors {
6262 colors: cached_data
6263 .colors
6264 .values()
6265 .flatten()
6266 .cloned()
6267 .collect(),
6268 cache_version: Some(cached_data.cache_version),
6269 }))
6270 .shared(),
6271 );
6272 }
6273 }
6274 }
6275 }
6276 }
6277 }
6278
6279 let lsp_data = self.lsp_data.entry(buffer_id).or_default();
6280 if let Some((updating_for, running_update)) = &lsp_data.colors_update {
6281 if !version_queried_for.changed_since(&updating_for) {
6282 return Some(running_update.clone());
6283 }
6284 }
6285 let query_version_queried_for = version_queried_for.clone();
6286 let new_task = cx
6287 .spawn(async move |lsp_store, cx| {
6288 cx.background_executor()
6289 .timer(Duration::from_millis(30))
6290 .await;
6291 let fetched_colors = lsp_store
6292 .update(cx, |lsp_store, cx| {
6293 lsp_store.fetch_document_colors_for_buffer(buffer.clone(), cx)
6294 })?
6295 .await
6296 .context("fetching document colors")
6297 .map_err(Arc::new);
6298 let fetched_colors = match fetched_colors {
6299 Ok(fetched_colors) => {
6300 if fetch_strategy != ColorFetchStrategy::IgnoreCache
6301 && Some(true)
6302 == buffer
6303 .update(cx, |buffer, _| {
6304 buffer.version() != query_version_queried_for
6305 })
6306 .ok()
6307 {
6308 return Ok(DocumentColors::default());
6309 }
6310 fetched_colors
6311 }
6312 Err(e) => {
6313 lsp_store
6314 .update(cx, |lsp_store, _| {
6315 lsp_store
6316 .lsp_data
6317 .entry(buffer_id)
6318 .or_default()
6319 .colors_update = None;
6320 })
6321 .ok();
6322 return Err(e);
6323 }
6324 };
6325
6326 lsp_store
6327 .update(cx, |lsp_store, _| {
6328 let lsp_data = lsp_store.lsp_data.entry(buffer_id).or_default();
6329
6330 if lsp_data.colors_for_version == query_version_queried_for {
6331 lsp_data.colors.extend(fetched_colors.clone());
6332 lsp_data.cache_version += 1;
6333 } else if !lsp_data
6334 .colors_for_version
6335 .changed_since(&query_version_queried_for)
6336 {
6337 lsp_data.colors_for_version = query_version_queried_for;
6338 lsp_data.colors = fetched_colors.clone();
6339 lsp_data.cache_version += 1;
6340 }
6341 lsp_data.colors_update = None;
6342 let colors = lsp_data
6343 .colors
6344 .values()
6345 .flatten()
6346 .cloned()
6347 .collect::<HashSet<_>>();
6348 DocumentColors {
6349 colors,
6350 cache_version: Some(lsp_data.cache_version),
6351 }
6352 })
6353 .map_err(Arc::new)
6354 })
6355 .shared();
6356 lsp_data.colors_update = Some((version_queried_for, new_task.clone()));
6357 Some(new_task)
6358 }
6359
6360 fn fetch_document_colors_for_buffer(
6361 &mut self,
6362 buffer: Entity<Buffer>,
6363 cx: &mut Context<Self>,
6364 ) -> Task<anyhow::Result<HashMap<LanguageServerId, HashSet<DocumentColor>>>> {
6365 if let Some((client, project_id)) = self.upstream_client() {
6366 let request_task = client.request(proto::MultiLspQuery {
6367 project_id,
6368 buffer_id: buffer.read(cx).remote_id().to_proto(),
6369 version: serialize_version(&buffer.read(cx).version()),
6370 strategy: Some(proto::multi_lsp_query::Strategy::All(
6371 proto::AllLanguageServers {},
6372 )),
6373 request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
6374 GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
6375 )),
6376 });
6377 cx.spawn(async move |project, cx| {
6378 let Some(project) = project.upgrade() else {
6379 return Ok(HashMap::default());
6380 };
6381 let colors = join_all(
6382 request_task
6383 .await
6384 .log_err()
6385 .map(|response| response.responses)
6386 .unwrap_or_default()
6387 .into_iter()
6388 .filter_map(|lsp_response| match lsp_response.response? {
6389 proto::lsp_response::Response::GetDocumentColorResponse(response) => {
6390 Some((
6391 LanguageServerId::from_proto(lsp_response.server_id),
6392 response,
6393 ))
6394 }
6395 unexpected => {
6396 debug_panic!("Unexpected response: {unexpected:?}");
6397 None
6398 }
6399 })
6400 .map(|(server_id, color_response)| {
6401 let response = GetDocumentColor {}.response_from_proto(
6402 color_response,
6403 project.clone(),
6404 buffer.clone(),
6405 cx.clone(),
6406 );
6407 async move { (server_id, response.await.log_err().unwrap_or_default()) }
6408 }),
6409 )
6410 .await
6411 .into_iter()
6412 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6413 acc.entry(server_id)
6414 .or_insert_with(HashSet::default)
6415 .extend(colors);
6416 acc
6417 });
6418 Ok(colors)
6419 })
6420 } else {
6421 let document_colors_task =
6422 self.request_multiple_lsp_locally(&buffer, None::<usize>, GetDocumentColor, cx);
6423 cx.spawn(async move |_, _| {
6424 Ok(document_colors_task
6425 .await
6426 .into_iter()
6427 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6428 acc.entry(server_id)
6429 .or_insert_with(HashSet::default)
6430 .extend(colors);
6431 acc
6432 })
6433 .into_iter()
6434 .collect())
6435 })
6436 }
6437 }
6438
6439 pub fn signature_help<T: ToPointUtf16>(
6440 &mut self,
6441 buffer: &Entity<Buffer>,
6442 position: T,
6443 cx: &mut Context<Self>,
6444 ) -> Task<Vec<SignatureHelp>> {
6445 let position = position.to_point_utf16(buffer.read(cx));
6446
6447 if let Some((client, upstream_project_id)) = self.upstream_client() {
6448 let request_task = client.request(proto::MultiLspQuery {
6449 buffer_id: buffer.read(cx).remote_id().into(),
6450 version: serialize_version(&buffer.read(cx).version()),
6451 project_id: upstream_project_id,
6452 strategy: Some(proto::multi_lsp_query::Strategy::All(
6453 proto::AllLanguageServers {},
6454 )),
6455 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
6456 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
6457 )),
6458 });
6459 let buffer = buffer.clone();
6460 cx.spawn(async move |weak_project, cx| {
6461 let Some(project) = weak_project.upgrade() else {
6462 return Vec::new();
6463 };
6464 join_all(
6465 request_task
6466 .await
6467 .log_err()
6468 .map(|response| response.responses)
6469 .unwrap_or_default()
6470 .into_iter()
6471 .filter_map(|lsp_response| match lsp_response.response? {
6472 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
6473 Some(response)
6474 }
6475 unexpected => {
6476 debug_panic!("Unexpected response: {unexpected:?}");
6477 None
6478 }
6479 })
6480 .map(|signature_response| {
6481 let response = GetSignatureHelp { position }.response_from_proto(
6482 signature_response,
6483 project.clone(),
6484 buffer.clone(),
6485 cx.clone(),
6486 );
6487 async move { response.await.log_err().flatten() }
6488 }),
6489 )
6490 .await
6491 .into_iter()
6492 .flatten()
6493 .collect()
6494 })
6495 } else {
6496 let all_actions_task = self.request_multiple_lsp_locally(
6497 buffer,
6498 Some(position),
6499 GetSignatureHelp { position },
6500 cx,
6501 );
6502 cx.spawn(async move |_, _| {
6503 all_actions_task
6504 .await
6505 .into_iter()
6506 .flat_map(|(_, actions)| actions)
6507 .collect::<Vec<_>>()
6508 })
6509 }
6510 }
6511
6512 pub fn hover(
6513 &mut self,
6514 buffer: &Entity<Buffer>,
6515 position: PointUtf16,
6516 cx: &mut Context<Self>,
6517 ) -> Task<Vec<Hover>> {
6518 if let Some((client, upstream_project_id)) = self.upstream_client() {
6519 let request_task = client.request(proto::MultiLspQuery {
6520 buffer_id: buffer.read(cx).remote_id().into(),
6521 version: serialize_version(&buffer.read(cx).version()),
6522 project_id: upstream_project_id,
6523 strategy: Some(proto::multi_lsp_query::Strategy::All(
6524 proto::AllLanguageServers {},
6525 )),
6526 request: Some(proto::multi_lsp_query::Request::GetHover(
6527 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
6528 )),
6529 });
6530 let buffer = buffer.clone();
6531 cx.spawn(async move |weak_project, cx| {
6532 let Some(project) = weak_project.upgrade() else {
6533 return Vec::new();
6534 };
6535 join_all(
6536 request_task
6537 .await
6538 .log_err()
6539 .map(|response| response.responses)
6540 .unwrap_or_default()
6541 .into_iter()
6542 .filter_map(|lsp_response| match lsp_response.response? {
6543 proto::lsp_response::Response::GetHoverResponse(response) => {
6544 Some(response)
6545 }
6546 unexpected => {
6547 debug_panic!("Unexpected response: {unexpected:?}");
6548 None
6549 }
6550 })
6551 .map(|hover_response| {
6552 let response = GetHover { position }.response_from_proto(
6553 hover_response,
6554 project.clone(),
6555 buffer.clone(),
6556 cx.clone(),
6557 );
6558 async move {
6559 response
6560 .await
6561 .log_err()
6562 .flatten()
6563 .and_then(remove_empty_hover_blocks)
6564 }
6565 }),
6566 )
6567 .await
6568 .into_iter()
6569 .flatten()
6570 .collect()
6571 })
6572 } else {
6573 let all_actions_task = self.request_multiple_lsp_locally(
6574 buffer,
6575 Some(position),
6576 GetHover { position },
6577 cx,
6578 );
6579 cx.spawn(async move |_, _| {
6580 all_actions_task
6581 .await
6582 .into_iter()
6583 .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
6584 .collect::<Vec<Hover>>()
6585 })
6586 }
6587 }
6588
6589 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
6590 let language_registry = self.languages.clone();
6591
6592 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
6593 let request = upstream_client.request(proto::GetProjectSymbols {
6594 project_id: *project_id,
6595 query: query.to_string(),
6596 });
6597 cx.foreground_executor().spawn(async move {
6598 let response = request.await?;
6599 let mut symbols = Vec::new();
6600 let core_symbols = response
6601 .symbols
6602 .into_iter()
6603 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
6604 .collect::<Vec<_>>();
6605 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
6606 .await;
6607 Ok(symbols)
6608 })
6609 } else if let Some(local) = self.as_local() {
6610 struct WorkspaceSymbolsResult {
6611 server_id: LanguageServerId,
6612 lsp_adapter: Arc<CachedLspAdapter>,
6613 worktree: WeakEntity<Worktree>,
6614 worktree_abs_path: Arc<Path>,
6615 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
6616 }
6617
6618 let mut requests = Vec::new();
6619 let mut requested_servers = BTreeSet::new();
6620 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
6621 let Some(worktree_handle) = self
6622 .worktree_store
6623 .read(cx)
6624 .worktree_for_id(*worktree_id, cx)
6625 else {
6626 continue;
6627 };
6628 let worktree = worktree_handle.read(cx);
6629 if !worktree.is_visible() {
6630 continue;
6631 }
6632
6633 let mut servers_to_query = server_ids
6634 .difference(&requested_servers)
6635 .cloned()
6636 .collect::<BTreeSet<_>>();
6637 for server_id in &servers_to_query {
6638 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
6639 Some(LanguageServerState::Running {
6640 adapter, server, ..
6641 }) => (adapter.clone(), server),
6642
6643 _ => continue 'next_server,
6644 };
6645 let supports_workspace_symbol_request =
6646 match server.capabilities().workspace_symbol_provider {
6647 Some(OneOf::Left(supported)) => supported,
6648 Some(OneOf::Right(_)) => true,
6649 None => false,
6650 };
6651 if !supports_workspace_symbol_request {
6652 continue 'next_server;
6653 }
6654 let worktree_abs_path = worktree.abs_path().clone();
6655 let worktree_handle = worktree_handle.clone();
6656 let server_id = server.server_id();
6657 requests.push(
6658 server
6659 .request::<lsp::request::WorkspaceSymbolRequest>(
6660 lsp::WorkspaceSymbolParams {
6661 query: query.to_string(),
6662 ..Default::default()
6663 },
6664 )
6665 .map(move |response| {
6666 let lsp_symbols = response.into_response()
6667 .context("workspace symbols request")
6668 .log_err()
6669 .flatten()
6670 .map(|symbol_response| match symbol_response {
6671 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
6672 flat_responses.into_iter().map(|lsp_symbol| {
6673 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
6674 }).collect::<Vec<_>>()
6675 }
6676 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
6677 nested_responses.into_iter().filter_map(|lsp_symbol| {
6678 let location = match lsp_symbol.location {
6679 OneOf::Left(location) => location,
6680 OneOf::Right(_) => {
6681 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
6682 return None
6683 }
6684 };
6685 Some((lsp_symbol.name, lsp_symbol.kind, location))
6686 }).collect::<Vec<_>>()
6687 }
6688 }).unwrap_or_default();
6689
6690 WorkspaceSymbolsResult {
6691 server_id,
6692 lsp_adapter,
6693 worktree: worktree_handle.downgrade(),
6694 worktree_abs_path,
6695 lsp_symbols,
6696 }
6697 }),
6698 );
6699 }
6700 requested_servers.append(&mut servers_to_query);
6701 }
6702
6703 cx.spawn(async move |this, cx| {
6704 let responses = futures::future::join_all(requests).await;
6705 let this = match this.upgrade() {
6706 Some(this) => this,
6707 None => return Ok(Vec::new()),
6708 };
6709
6710 let mut symbols = Vec::new();
6711 for result in responses {
6712 let core_symbols = this.update(cx, |this, cx| {
6713 result
6714 .lsp_symbols
6715 .into_iter()
6716 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
6717 let abs_path = symbol_location.uri.to_file_path().ok()?;
6718 let source_worktree = result.worktree.upgrade()?;
6719 let source_worktree_id = source_worktree.read(cx).id();
6720
6721 let path;
6722 let worktree;
6723 if let Some((tree, rel_path)) =
6724 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
6725 {
6726 worktree = tree;
6727 path = rel_path;
6728 } else {
6729 worktree = source_worktree.clone();
6730 path = relativize_path(&result.worktree_abs_path, &abs_path);
6731 }
6732
6733 let worktree_id = worktree.read(cx).id();
6734 let project_path = ProjectPath {
6735 worktree_id,
6736 path: path.into(),
6737 };
6738 let signature = this.symbol_signature(&project_path);
6739 Some(CoreSymbol {
6740 source_language_server_id: result.server_id,
6741 language_server_name: result.lsp_adapter.name.clone(),
6742 source_worktree_id,
6743 path: project_path,
6744 kind: symbol_kind,
6745 name: symbol_name,
6746 range: range_from_lsp(symbol_location.range),
6747 signature,
6748 })
6749 })
6750 .collect()
6751 })?;
6752
6753 populate_labels_for_symbols(
6754 core_symbols,
6755 &language_registry,
6756 Some(result.lsp_adapter),
6757 &mut symbols,
6758 )
6759 .await;
6760 }
6761
6762 Ok(symbols)
6763 })
6764 } else {
6765 Task::ready(Err(anyhow!("No upstream client or local language server")))
6766 }
6767 }
6768
6769 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
6770 let mut summary = DiagnosticSummary::default();
6771 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
6772 summary.error_count += path_summary.error_count;
6773 summary.warning_count += path_summary.warning_count;
6774 }
6775 summary
6776 }
6777
6778 pub fn diagnostic_summaries<'a>(
6779 &'a self,
6780 include_ignored: bool,
6781 cx: &'a App,
6782 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6783 self.worktree_store
6784 .read(cx)
6785 .visible_worktrees(cx)
6786 .filter_map(|worktree| {
6787 let worktree = worktree.read(cx);
6788 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
6789 })
6790 .flat_map(move |(worktree, summaries)| {
6791 let worktree_id = worktree.id();
6792 summaries
6793 .iter()
6794 .filter(move |(path, _)| {
6795 include_ignored
6796 || worktree
6797 .entry_for_path(path.as_ref())
6798 .map_or(false, |entry| !entry.is_ignored)
6799 })
6800 .flat_map(move |(path, summaries)| {
6801 summaries.iter().map(move |(server_id, summary)| {
6802 (
6803 ProjectPath {
6804 worktree_id,
6805 path: path.clone(),
6806 },
6807 *server_id,
6808 *summary,
6809 )
6810 })
6811 })
6812 })
6813 }
6814
6815 pub fn on_buffer_edited(
6816 &mut self,
6817 buffer: Entity<Buffer>,
6818 cx: &mut Context<Self>,
6819 ) -> Option<()> {
6820 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
6821 Some(
6822 self.as_local()?
6823 .language_servers_for_buffer(buffer, cx)
6824 .map(|i| i.1.clone())
6825 .collect(),
6826 )
6827 })?;
6828
6829 let buffer = buffer.read(cx);
6830 let file = File::from_dyn(buffer.file())?;
6831 let abs_path = file.as_local()?.abs_path(cx);
6832 let uri = lsp::Url::from_file_path(abs_path).unwrap();
6833 let next_snapshot = buffer.text_snapshot();
6834 for language_server in language_servers {
6835 let language_server = language_server.clone();
6836
6837 let buffer_snapshots = self
6838 .as_local_mut()
6839 .unwrap()
6840 .buffer_snapshots
6841 .get_mut(&buffer.remote_id())
6842 .and_then(|m| m.get_mut(&language_server.server_id()))?;
6843 let previous_snapshot = buffer_snapshots.last()?;
6844
6845 let build_incremental_change = || {
6846 buffer
6847 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6848 .map(|edit| {
6849 let edit_start = edit.new.start.0;
6850 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6851 let new_text = next_snapshot
6852 .text_for_range(edit.new.start.1..edit.new.end.1)
6853 .collect();
6854 lsp::TextDocumentContentChangeEvent {
6855 range: Some(lsp::Range::new(
6856 point_to_lsp(edit_start),
6857 point_to_lsp(edit_end),
6858 )),
6859 range_length: None,
6860 text: new_text,
6861 }
6862 })
6863 .collect()
6864 };
6865
6866 let document_sync_kind = language_server
6867 .capabilities()
6868 .text_document_sync
6869 .as_ref()
6870 .and_then(|sync| match sync {
6871 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6872 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6873 });
6874
6875 let content_changes: Vec<_> = match document_sync_kind {
6876 Some(lsp::TextDocumentSyncKind::FULL) => {
6877 vec![lsp::TextDocumentContentChangeEvent {
6878 range: None,
6879 range_length: None,
6880 text: next_snapshot.text(),
6881 }]
6882 }
6883 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6884 _ => {
6885 #[cfg(any(test, feature = "test-support"))]
6886 {
6887 build_incremental_change()
6888 }
6889
6890 #[cfg(not(any(test, feature = "test-support")))]
6891 {
6892 continue;
6893 }
6894 }
6895 };
6896
6897 let next_version = previous_snapshot.version + 1;
6898 buffer_snapshots.push(LspBufferSnapshot {
6899 version: next_version,
6900 snapshot: next_snapshot.clone(),
6901 });
6902
6903 language_server
6904 .notify::<lsp::notification::DidChangeTextDocument>(
6905 &lsp::DidChangeTextDocumentParams {
6906 text_document: lsp::VersionedTextDocumentIdentifier::new(
6907 uri.clone(),
6908 next_version,
6909 ),
6910 content_changes,
6911 },
6912 )
6913 .ok();
6914 self.pull_workspace_diagnostics(language_server.server_id());
6915 }
6916
6917 None
6918 }
6919
6920 pub fn on_buffer_saved(
6921 &mut self,
6922 buffer: Entity<Buffer>,
6923 cx: &mut Context<Self>,
6924 ) -> Option<()> {
6925 let file = File::from_dyn(buffer.read(cx).file())?;
6926 let worktree_id = file.worktree_id(cx);
6927 let abs_path = file.as_local()?.abs_path(cx);
6928 let text_document = lsp::TextDocumentIdentifier {
6929 uri: file_path_to_lsp_url(&abs_path).log_err()?,
6930 };
6931 let local = self.as_local()?;
6932
6933 for server in local.language_servers_for_worktree(worktree_id) {
6934 if let Some(include_text) = include_text(server.as_ref()) {
6935 let text = if include_text {
6936 Some(buffer.read(cx).text())
6937 } else {
6938 None
6939 };
6940 server
6941 .notify::<lsp::notification::DidSaveTextDocument>(
6942 &lsp::DidSaveTextDocumentParams {
6943 text_document: text_document.clone(),
6944 text,
6945 },
6946 )
6947 .ok();
6948 }
6949 }
6950
6951 let language_servers = buffer.update(cx, |buffer, cx| {
6952 local.language_server_ids_for_buffer(buffer, cx)
6953 });
6954 for language_server_id in language_servers {
6955 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6956 }
6957
6958 None
6959 }
6960
6961 pub(crate) async fn refresh_workspace_configurations(
6962 this: &WeakEntity<Self>,
6963 fs: Arc<dyn Fs>,
6964 cx: &mut AsyncApp,
6965 ) {
6966 maybe!(async move {
6967 let servers = this
6968 .update(cx, |this, cx| {
6969 let Some(local) = this.as_local() else {
6970 return Vec::default();
6971 };
6972 local
6973 .language_server_ids
6974 .iter()
6975 .flat_map(|((worktree_id, _), server_ids)| {
6976 let worktree = this
6977 .worktree_store
6978 .read(cx)
6979 .worktree_for_id(*worktree_id, cx);
6980 let delegate = worktree.map(|worktree| {
6981 LocalLspAdapterDelegate::new(
6982 local.languages.clone(),
6983 &local.environment,
6984 cx.weak_entity(),
6985 &worktree,
6986 local.http_client.clone(),
6987 local.fs.clone(),
6988 cx,
6989 )
6990 });
6991
6992 server_ids.iter().filter_map(move |server_id| {
6993 let states = local.language_servers.get(server_id)?;
6994
6995 match states {
6996 LanguageServerState::Starting { .. } => None,
6997 LanguageServerState::Running {
6998 adapter, server, ..
6999 } => Some((
7000 adapter.adapter.clone(),
7001 server.clone(),
7002 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
7003 )),
7004 }
7005 })
7006 })
7007 .collect::<Vec<_>>()
7008 })
7009 .ok()?;
7010
7011 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
7012 for (adapter, server, delegate) in servers {
7013 let settings = LocalLspStore::workspace_configuration_for_adapter(
7014 adapter,
7015 fs.as_ref(),
7016 &delegate,
7017 toolchain_store.clone(),
7018 cx,
7019 )
7020 .await
7021 .ok()?;
7022
7023 server
7024 .notify::<lsp::notification::DidChangeConfiguration>(
7025 &lsp::DidChangeConfigurationParams { settings },
7026 )
7027 .ok();
7028 }
7029 Some(())
7030 })
7031 .await;
7032 }
7033
7034 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
7035 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
7036 toolchain_store.read(cx).as_language_toolchain_store()
7037 } else {
7038 Arc::new(EmptyToolchainStore)
7039 }
7040 }
7041 fn maintain_workspace_config(
7042 fs: Arc<dyn Fs>,
7043 external_refresh_requests: watch::Receiver<()>,
7044 cx: &mut Context<Self>,
7045 ) -> Task<Result<()>> {
7046 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
7047 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
7048
7049 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
7050 *settings_changed_tx.borrow_mut() = ();
7051 });
7052
7053 let mut joint_future =
7054 futures::stream::select(settings_changed_rx, external_refresh_requests);
7055 cx.spawn(async move |this, cx| {
7056 while let Some(()) = joint_future.next().await {
7057 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
7058 }
7059
7060 drop(settings_observation);
7061 anyhow::Ok(())
7062 })
7063 }
7064
7065 pub fn language_servers_for_local_buffer<'a>(
7066 &'a self,
7067 buffer: &Buffer,
7068 cx: &mut App,
7069 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7070 let local = self.as_local();
7071 let language_server_ids = local
7072 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
7073 .unwrap_or_default();
7074
7075 language_server_ids
7076 .into_iter()
7077 .filter_map(
7078 move |server_id| match local?.language_servers.get(&server_id)? {
7079 LanguageServerState::Running {
7080 adapter, server, ..
7081 } => Some((adapter, server)),
7082 _ => None,
7083 },
7084 )
7085 }
7086
7087 pub fn language_server_for_local_buffer<'a>(
7088 &'a self,
7089 buffer: &'a Buffer,
7090 server_id: LanguageServerId,
7091 cx: &'a mut App,
7092 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7093 self.as_local()?
7094 .language_servers_for_buffer(buffer, cx)
7095 .find(|(_, s)| s.server_id() == server_id)
7096 }
7097
7098 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
7099 self.diagnostic_summaries.remove(&id_to_remove);
7100 if let Some(local) = self.as_local_mut() {
7101 let to_remove = local.remove_worktree(id_to_remove, cx);
7102 for server in to_remove {
7103 self.language_server_statuses.remove(&server);
7104 }
7105 }
7106 }
7107
7108 pub fn shared(
7109 &mut self,
7110 project_id: u64,
7111 downstream_client: AnyProtoClient,
7112 _: &mut Context<Self>,
7113 ) {
7114 self.downstream_client = Some((downstream_client.clone(), project_id));
7115
7116 for (server_id, status) in &self.language_server_statuses {
7117 downstream_client
7118 .send(proto::StartLanguageServer {
7119 project_id,
7120 server: Some(proto::LanguageServer {
7121 id: server_id.0 as u64,
7122 name: status.name.clone(),
7123 worktree_id: None,
7124 }),
7125 })
7126 .log_err();
7127 }
7128 }
7129
7130 pub fn disconnected_from_host(&mut self) {
7131 self.downstream_client.take();
7132 }
7133
7134 pub fn disconnected_from_ssh_remote(&mut self) {
7135 if let LspStoreMode::Remote(RemoteLspStore {
7136 upstream_client, ..
7137 }) = &mut self.mode
7138 {
7139 upstream_client.take();
7140 }
7141 }
7142
7143 pub(crate) fn set_language_server_statuses_from_proto(
7144 &mut self,
7145 language_servers: Vec<proto::LanguageServer>,
7146 ) {
7147 self.language_server_statuses = language_servers
7148 .into_iter()
7149 .map(|server| {
7150 (
7151 LanguageServerId(server.id as usize),
7152 LanguageServerStatus {
7153 name: server.name,
7154 pending_work: Default::default(),
7155 has_pending_diagnostic_updates: false,
7156 progress_tokens: Default::default(),
7157 },
7158 )
7159 })
7160 .collect();
7161 }
7162
7163 fn register_local_language_server(
7164 &mut self,
7165 worktree: Entity<Worktree>,
7166 language_server_name: LanguageServerName,
7167 language_server_id: LanguageServerId,
7168 cx: &mut App,
7169 ) {
7170 let Some(local) = self.as_local_mut() else {
7171 return;
7172 };
7173
7174 let worktree_id = worktree.read(cx).id();
7175 if worktree.read(cx).is_visible() {
7176 let path = ProjectPath {
7177 worktree_id,
7178 path: Arc::from("".as_ref()),
7179 };
7180 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
7181 local.lsp_tree.update(cx, |language_server_tree, cx| {
7182 for node in language_server_tree.get(
7183 path,
7184 AdapterQuery::Adapter(&language_server_name),
7185 delegate,
7186 cx,
7187 ) {
7188 node.server_id_or_init(|disposition| {
7189 assert_eq!(disposition.server_name, &language_server_name);
7190
7191 language_server_id
7192 });
7193 }
7194 });
7195 }
7196
7197 local
7198 .language_server_ids
7199 .entry((worktree_id, language_server_name))
7200 .or_default()
7201 .insert(language_server_id);
7202 }
7203
7204 #[cfg(test)]
7205 pub fn update_diagnostic_entries(
7206 &mut self,
7207 server_id: LanguageServerId,
7208 abs_path: PathBuf,
7209 result_id: Option<String>,
7210 version: Option<i32>,
7211 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7212 cx: &mut Context<Self>,
7213 ) -> anyhow::Result<()> {
7214 self.merge_diagnostic_entries(
7215 server_id,
7216 abs_path,
7217 result_id,
7218 version,
7219 diagnostics,
7220 |_, _, _| false,
7221 cx,
7222 )
7223 }
7224
7225 pub fn merge_diagnostic_entries(
7226 &mut self,
7227 server_id: LanguageServerId,
7228 abs_path: PathBuf,
7229 result_id: Option<String>,
7230 version: Option<i32>,
7231 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7232 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
7233 cx: &mut Context<Self>,
7234 ) -> anyhow::Result<()> {
7235 let Some((worktree, relative_path)) =
7236 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
7237 else {
7238 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
7239 return Ok(());
7240 };
7241
7242 let project_path = ProjectPath {
7243 worktree_id: worktree.read(cx).id(),
7244 path: relative_path.into(),
7245 };
7246
7247 if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path) {
7248 let snapshot = buffer_handle.read(cx).snapshot();
7249 let buffer = buffer_handle.read(cx);
7250 let reused_diagnostics = buffer
7251 .get_diagnostics(server_id)
7252 .into_iter()
7253 .flat_map(|diag| {
7254 diag.iter()
7255 .filter(|v| filter(buffer, &v.diagnostic, cx))
7256 .map(|v| {
7257 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
7258 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
7259 DiagnosticEntry {
7260 range: start..end,
7261 diagnostic: v.diagnostic.clone(),
7262 }
7263 })
7264 })
7265 .collect::<Vec<_>>();
7266
7267 self.as_local_mut()
7268 .context("cannot merge diagnostics on a remote LspStore")?
7269 .update_buffer_diagnostics(
7270 &buffer_handle,
7271 server_id,
7272 result_id,
7273 version,
7274 diagnostics.clone(),
7275 reused_diagnostics.clone(),
7276 cx,
7277 )?;
7278
7279 diagnostics.extend(reused_diagnostics);
7280 }
7281
7282 let updated = worktree.update(cx, |worktree, cx| {
7283 self.update_worktree_diagnostics(
7284 worktree.id(),
7285 server_id,
7286 project_path.path.clone(),
7287 diagnostics,
7288 cx,
7289 )
7290 })?;
7291 if updated {
7292 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7293 language_server_id: server_id,
7294 path: project_path,
7295 })
7296 }
7297 Ok(())
7298 }
7299
7300 fn update_worktree_diagnostics(
7301 &mut self,
7302 worktree_id: WorktreeId,
7303 server_id: LanguageServerId,
7304 worktree_path: Arc<Path>,
7305 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7306 _: &mut Context<Worktree>,
7307 ) -> Result<bool> {
7308 let local = match &mut self.mode {
7309 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
7310 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
7311 };
7312
7313 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
7314 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
7315 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
7316
7317 let old_summary = summaries_by_server_id
7318 .remove(&server_id)
7319 .unwrap_or_default();
7320
7321 let new_summary = DiagnosticSummary::new(&diagnostics);
7322 if new_summary.is_empty() {
7323 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
7324 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7325 diagnostics_by_server_id.remove(ix);
7326 }
7327 if diagnostics_by_server_id.is_empty() {
7328 diagnostics_for_tree.remove(&worktree_path);
7329 }
7330 }
7331 } else {
7332 summaries_by_server_id.insert(server_id, new_summary);
7333 let diagnostics_by_server_id = diagnostics_for_tree
7334 .entry(worktree_path.clone())
7335 .or_default();
7336 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7337 Ok(ix) => {
7338 diagnostics_by_server_id[ix] = (server_id, diagnostics);
7339 }
7340 Err(ix) => {
7341 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
7342 }
7343 }
7344 }
7345
7346 if !old_summary.is_empty() || !new_summary.is_empty() {
7347 if let Some((downstream_client, project_id)) = &self.downstream_client {
7348 downstream_client
7349 .send(proto::UpdateDiagnosticSummary {
7350 project_id: *project_id,
7351 worktree_id: worktree_id.to_proto(),
7352 summary: Some(proto::DiagnosticSummary {
7353 path: worktree_path.to_proto(),
7354 language_server_id: server_id.0 as u64,
7355 error_count: new_summary.error_count as u32,
7356 warning_count: new_summary.warning_count as u32,
7357 }),
7358 })
7359 .log_err();
7360 }
7361 }
7362
7363 Ok(!old_summary.is_empty() || !new_summary.is_empty())
7364 }
7365
7366 pub fn open_buffer_for_symbol(
7367 &mut self,
7368 symbol: &Symbol,
7369 cx: &mut Context<Self>,
7370 ) -> Task<Result<Entity<Buffer>>> {
7371 if let Some((client, project_id)) = self.upstream_client() {
7372 let request = client.request(proto::OpenBufferForSymbol {
7373 project_id,
7374 symbol: Some(Self::serialize_symbol(symbol)),
7375 });
7376 cx.spawn(async move |this, cx| {
7377 let response = request.await?;
7378 let buffer_id = BufferId::new(response.buffer_id)?;
7379 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
7380 .await
7381 })
7382 } else if let Some(local) = self.as_local() {
7383 let Some(language_server_id) = local
7384 .language_server_ids
7385 .get(&(
7386 symbol.source_worktree_id,
7387 symbol.language_server_name.clone(),
7388 ))
7389 .and_then(|ids| {
7390 ids.contains(&symbol.source_language_server_id)
7391 .then_some(symbol.source_language_server_id)
7392 })
7393 else {
7394 return Task::ready(Err(anyhow!(
7395 "language server for worktree and language not found"
7396 )));
7397 };
7398
7399 let worktree_abs_path = if let Some(worktree_abs_path) = self
7400 .worktree_store
7401 .read(cx)
7402 .worktree_for_id(symbol.path.worktree_id, cx)
7403 .map(|worktree| worktree.read(cx).abs_path())
7404 {
7405 worktree_abs_path
7406 } else {
7407 return Task::ready(Err(anyhow!("worktree not found for symbol")));
7408 };
7409
7410 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
7411 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
7412 uri
7413 } else {
7414 return Task::ready(Err(anyhow!("invalid symbol path")));
7415 };
7416
7417 self.open_local_buffer_via_lsp(
7418 symbol_uri,
7419 language_server_id,
7420 symbol.language_server_name.clone(),
7421 cx,
7422 )
7423 } else {
7424 Task::ready(Err(anyhow!("no upstream client or local store")))
7425 }
7426 }
7427
7428 pub fn open_local_buffer_via_lsp(
7429 &mut self,
7430 mut abs_path: lsp::Url,
7431 language_server_id: LanguageServerId,
7432 language_server_name: LanguageServerName,
7433 cx: &mut Context<Self>,
7434 ) -> Task<Result<Entity<Buffer>>> {
7435 cx.spawn(async move |lsp_store, cx| {
7436 // Escape percent-encoded string.
7437 let current_scheme = abs_path.scheme().to_owned();
7438 let _ = abs_path.set_scheme("file");
7439
7440 let abs_path = abs_path
7441 .to_file_path()
7442 .map_err(|()| anyhow!("can't convert URI to path"))?;
7443 let p = abs_path.clone();
7444 let yarn_worktree = lsp_store
7445 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
7446 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
7447 cx.spawn(async move |this, cx| {
7448 let t = this
7449 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
7450 .ok()?;
7451 t.await
7452 })
7453 }),
7454 None => Task::ready(None),
7455 })?
7456 .await;
7457 let (worktree_root_target, known_relative_path) =
7458 if let Some((zip_root, relative_path)) = yarn_worktree {
7459 (zip_root, Some(relative_path))
7460 } else {
7461 (Arc::<Path>::from(abs_path.as_path()), None)
7462 };
7463 let (worktree, relative_path) = if let Some(result) =
7464 lsp_store.update(cx, |lsp_store, cx| {
7465 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7466 worktree_store.find_worktree(&worktree_root_target, cx)
7467 })
7468 })? {
7469 let relative_path =
7470 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
7471 (result.0, relative_path)
7472 } else {
7473 let worktree = lsp_store
7474 .update(cx, |lsp_store, cx| {
7475 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7476 worktree_store.create_worktree(&worktree_root_target, false, cx)
7477 })
7478 })?
7479 .await?;
7480 if worktree.read_with(cx, |worktree, _| worktree.is_local())? {
7481 lsp_store
7482 .update(cx, |lsp_store, cx| {
7483 lsp_store.register_local_language_server(
7484 worktree.clone(),
7485 language_server_name,
7486 language_server_id,
7487 cx,
7488 )
7489 })
7490 .ok();
7491 }
7492 let worktree_root = worktree.read_with(cx, |worktree, _| worktree.abs_path())?;
7493 let relative_path = if let Some(known_path) = known_relative_path {
7494 known_path
7495 } else {
7496 abs_path.strip_prefix(worktree_root)?.into()
7497 };
7498 (worktree, relative_path)
7499 };
7500 let project_path = ProjectPath {
7501 worktree_id: worktree.read_with(cx, |worktree, _| worktree.id())?,
7502 path: relative_path,
7503 };
7504 lsp_store
7505 .update(cx, |lsp_store, cx| {
7506 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
7507 buffer_store.open_buffer(project_path, cx)
7508 })
7509 })?
7510 .await
7511 })
7512 }
7513
7514 fn request_multiple_lsp_locally<P, R>(
7515 &mut self,
7516 buffer: &Entity<Buffer>,
7517 position: Option<P>,
7518 request: R,
7519 cx: &mut Context<Self>,
7520 ) -> Task<Vec<(LanguageServerId, R::Response)>>
7521 where
7522 P: ToOffset,
7523 R: LspCommand + Clone,
7524 <R::LspRequest as lsp::request::Request>::Result: Send,
7525 <R::LspRequest as lsp::request::Request>::Params: Send,
7526 {
7527 let Some(local) = self.as_local() else {
7528 return Task::ready(Vec::new());
7529 };
7530
7531 let snapshot = buffer.read(cx).snapshot();
7532 let scope = position.and_then(|position| snapshot.language_scope_at(position));
7533
7534 let server_ids = buffer.update(cx, |buffer, cx| {
7535 local
7536 .language_servers_for_buffer(buffer, cx)
7537 .filter(|(adapter, _)| {
7538 scope
7539 .as_ref()
7540 .map(|scope| scope.language_allowed(&adapter.name))
7541 .unwrap_or(true)
7542 })
7543 .map(|(_, server)| server.server_id())
7544 .filter(|server_id| {
7545 self.as_local().is_none_or(|local| {
7546 local
7547 .buffers_opened_in_servers
7548 .get(&snapshot.remote_id())
7549 .is_some_and(|servers| servers.contains(server_id))
7550 })
7551 })
7552 .collect::<Vec<_>>()
7553 });
7554
7555 let mut response_results = server_ids
7556 .into_iter()
7557 .map(|server_id| {
7558 let task = self.request_lsp(
7559 buffer.clone(),
7560 LanguageServerToQuery::Other(server_id),
7561 request.clone(),
7562 cx,
7563 );
7564 async move { (server_id, task.await) }
7565 })
7566 .collect::<FuturesUnordered<_>>();
7567
7568 cx.spawn(async move |_, _| {
7569 let mut responses = Vec::with_capacity(response_results.len());
7570 while let Some((server_id, response_result)) = response_results.next().await {
7571 if let Some(response) = response_result.log_err() {
7572 responses.push((server_id, response));
7573 }
7574 }
7575 responses
7576 })
7577 }
7578
7579 async fn handle_lsp_command<T: LspCommand>(
7580 this: Entity<Self>,
7581 envelope: TypedEnvelope<T::ProtoRequest>,
7582 mut cx: AsyncApp,
7583 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7584 where
7585 <T::LspRequest as lsp::request::Request>::Params: Send,
7586 <T::LspRequest as lsp::request::Request>::Result: Send,
7587 {
7588 let sender_id = envelope.original_sender_id().unwrap_or_default();
7589 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
7590 let buffer_handle = this.update(&mut cx, |this, cx| {
7591 this.buffer_store.read(cx).get_existing(buffer_id)
7592 })??;
7593 let request = T::from_proto(
7594 envelope.payload,
7595 this.clone(),
7596 buffer_handle.clone(),
7597 cx.clone(),
7598 )
7599 .await?;
7600 let response = this
7601 .update(&mut cx, |this, cx| {
7602 this.request_lsp(
7603 buffer_handle.clone(),
7604 LanguageServerToQuery::FirstCapable,
7605 request,
7606 cx,
7607 )
7608 })?
7609 .await?;
7610 this.update(&mut cx, |this, cx| {
7611 Ok(T::response_to_proto(
7612 response,
7613 this,
7614 sender_id,
7615 &buffer_handle.read(cx).version(),
7616 cx,
7617 ))
7618 })?
7619 }
7620
7621 async fn handle_multi_lsp_query(
7622 lsp_store: Entity<Self>,
7623 envelope: TypedEnvelope<proto::MultiLspQuery>,
7624 mut cx: AsyncApp,
7625 ) -> Result<proto::MultiLspQueryResponse> {
7626 let response_from_ssh = lsp_store.read_with(&mut cx, |this, _| {
7627 let (upstream_client, project_id) = this.upstream_client()?;
7628 let mut payload = envelope.payload.clone();
7629 payload.project_id = project_id;
7630
7631 Some(upstream_client.request(payload))
7632 })?;
7633 if let Some(response_from_ssh) = response_from_ssh {
7634 return response_from_ssh.await;
7635 }
7636
7637 let sender_id = envelope.original_sender_id().unwrap_or_default();
7638 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7639 let version = deserialize_version(&envelope.payload.version);
7640 let buffer = lsp_store.update(&mut cx, |this, cx| {
7641 this.buffer_store.read(cx).get_existing(buffer_id)
7642 })??;
7643 buffer
7644 .update(&mut cx, |buffer, _| {
7645 buffer.wait_for_version(version.clone())
7646 })?
7647 .await?;
7648 let buffer_version = buffer.read_with(&mut cx, |buffer, _| buffer.version())?;
7649 match envelope
7650 .payload
7651 .strategy
7652 .context("invalid request without the strategy")?
7653 {
7654 proto::multi_lsp_query::Strategy::All(_) => {
7655 // currently, there's only one multiple language servers query strategy,
7656 // so just ensure it's specified correctly
7657 }
7658 }
7659 match envelope.payload.request {
7660 Some(proto::multi_lsp_query::Request::GetHover(message)) => {
7661 buffer
7662 .update(&mut cx, |buffer, _| {
7663 buffer.wait_for_version(deserialize_version(&message.version))
7664 })?
7665 .await?;
7666 let get_hover =
7667 GetHover::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7668 .await?;
7669 let all_hovers = lsp_store
7670 .update(&mut cx, |this, cx| {
7671 this.request_multiple_lsp_locally(
7672 &buffer,
7673 Some(get_hover.position),
7674 get_hover,
7675 cx,
7676 )
7677 })?
7678 .await
7679 .into_iter()
7680 .filter_map(|(server_id, hover)| {
7681 Some((server_id, remove_empty_hover_blocks(hover?)?))
7682 });
7683 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7684 responses: all_hovers
7685 .map(|(server_id, hover)| proto::LspResponse {
7686 server_id: server_id.to_proto(),
7687 response: Some(proto::lsp_response::Response::GetHoverResponse(
7688 GetHover::response_to_proto(
7689 Some(hover),
7690 project,
7691 sender_id,
7692 &buffer_version,
7693 cx,
7694 ),
7695 )),
7696 })
7697 .collect(),
7698 })
7699 }
7700 Some(proto::multi_lsp_query::Request::GetCodeActions(message)) => {
7701 buffer
7702 .update(&mut cx, |buffer, _| {
7703 buffer.wait_for_version(deserialize_version(&message.version))
7704 })?
7705 .await?;
7706 let get_code_actions = GetCodeActions::from_proto(
7707 message,
7708 lsp_store.clone(),
7709 buffer.clone(),
7710 cx.clone(),
7711 )
7712 .await?;
7713
7714 let all_actions = lsp_store
7715 .update(&mut cx, |project, cx| {
7716 project.request_multiple_lsp_locally(
7717 &buffer,
7718 Some(get_code_actions.range.start),
7719 get_code_actions,
7720 cx,
7721 )
7722 })?
7723 .await
7724 .into_iter();
7725
7726 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7727 responses: all_actions
7728 .map(|(server_id, code_actions)| proto::LspResponse {
7729 server_id: server_id.to_proto(),
7730 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
7731 GetCodeActions::response_to_proto(
7732 code_actions,
7733 project,
7734 sender_id,
7735 &buffer_version,
7736 cx,
7737 ),
7738 )),
7739 })
7740 .collect(),
7741 })
7742 }
7743 Some(proto::multi_lsp_query::Request::GetSignatureHelp(message)) => {
7744 buffer
7745 .update(&mut cx, |buffer, _| {
7746 buffer.wait_for_version(deserialize_version(&message.version))
7747 })?
7748 .await?;
7749 let get_signature_help = GetSignatureHelp::from_proto(
7750 message,
7751 lsp_store.clone(),
7752 buffer.clone(),
7753 cx.clone(),
7754 )
7755 .await?;
7756
7757 let all_signatures = lsp_store
7758 .update(&mut cx, |project, cx| {
7759 project.request_multiple_lsp_locally(
7760 &buffer,
7761 Some(get_signature_help.position),
7762 get_signature_help,
7763 cx,
7764 )
7765 })?
7766 .await
7767 .into_iter();
7768
7769 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7770 responses: all_signatures
7771 .map(|(server_id, signature_help)| proto::LspResponse {
7772 server_id: server_id.to_proto(),
7773 response: Some(
7774 proto::lsp_response::Response::GetSignatureHelpResponse(
7775 GetSignatureHelp::response_to_proto(
7776 signature_help,
7777 project,
7778 sender_id,
7779 &buffer_version,
7780 cx,
7781 ),
7782 ),
7783 ),
7784 })
7785 .collect(),
7786 })
7787 }
7788 Some(proto::multi_lsp_query::Request::GetCodeLens(message)) => {
7789 buffer
7790 .update(&mut cx, |buffer, _| {
7791 buffer.wait_for_version(deserialize_version(&message.version))
7792 })?
7793 .await?;
7794 let get_code_lens =
7795 GetCodeLens::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7796 .await?;
7797
7798 let code_lens_actions = lsp_store
7799 .update(&mut cx, |project, cx| {
7800 project.request_multiple_lsp_locally(
7801 &buffer,
7802 None::<usize>,
7803 get_code_lens,
7804 cx,
7805 )
7806 })?
7807 .await
7808 .into_iter();
7809
7810 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7811 responses: code_lens_actions
7812 .map(|(server_id, actions)| proto::LspResponse {
7813 server_id: server_id.to_proto(),
7814 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
7815 GetCodeLens::response_to_proto(
7816 actions,
7817 project,
7818 sender_id,
7819 &buffer_version,
7820 cx,
7821 ),
7822 )),
7823 })
7824 .collect(),
7825 })
7826 }
7827 Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(message)) => {
7828 buffer
7829 .update(&mut cx, |buffer, _| {
7830 buffer.wait_for_version(deserialize_version(&message.version))
7831 })?
7832 .await?;
7833 lsp_store
7834 .update(&mut cx, |lsp_store, cx| {
7835 lsp_store.pull_diagnostics_for_buffer(buffer, cx)
7836 })?
7837 .await?;
7838 // `pull_diagnostics_for_buffer` will merge in the new diagnostics and send them to the client.
7839 // The client cannot merge anything into its non-local LspStore, so we do not need to return anything.
7840 Ok(proto::MultiLspQueryResponse {
7841 responses: Vec::new(),
7842 })
7843 }
7844 Some(proto::multi_lsp_query::Request::GetDocumentColor(message)) => {
7845 buffer
7846 .update(&mut cx, |buffer, _| {
7847 buffer.wait_for_version(deserialize_version(&message.version))
7848 })?
7849 .await?;
7850 let get_document_color = GetDocumentColor::from_proto(
7851 message,
7852 lsp_store.clone(),
7853 buffer.clone(),
7854 cx.clone(),
7855 )
7856 .await?;
7857
7858 let all_colors = lsp_store
7859 .update(&mut cx, |project, cx| {
7860 project.request_multiple_lsp_locally(
7861 &buffer,
7862 None::<usize>,
7863 get_document_color,
7864 cx,
7865 )
7866 })?
7867 .await
7868 .into_iter();
7869
7870 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7871 responses: all_colors
7872 .map(|(server_id, colors)| proto::LspResponse {
7873 server_id: server_id.to_proto(),
7874 response: Some(
7875 proto::lsp_response::Response::GetDocumentColorResponse(
7876 GetDocumentColor::response_to_proto(
7877 colors,
7878 project,
7879 sender_id,
7880 &buffer_version,
7881 cx,
7882 ),
7883 ),
7884 ),
7885 })
7886 .collect(),
7887 })
7888 }
7889 None => anyhow::bail!("empty multi lsp query request"),
7890 }
7891 }
7892
7893 async fn handle_apply_code_action(
7894 this: Entity<Self>,
7895 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7896 mut cx: AsyncApp,
7897 ) -> Result<proto::ApplyCodeActionResponse> {
7898 let sender_id = envelope.original_sender_id().unwrap_or_default();
7899 let action =
7900 Self::deserialize_code_action(envelope.payload.action.context("invalid action")?)?;
7901 let apply_code_action = this.update(&mut cx, |this, cx| {
7902 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7903 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7904 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
7905 })??;
7906
7907 let project_transaction = apply_code_action.await?;
7908 let project_transaction = this.update(&mut cx, |this, cx| {
7909 this.buffer_store.update(cx, |buffer_store, cx| {
7910 buffer_store.serialize_project_transaction_for_peer(
7911 project_transaction,
7912 sender_id,
7913 cx,
7914 )
7915 })
7916 })?;
7917 Ok(proto::ApplyCodeActionResponse {
7918 transaction: Some(project_transaction),
7919 })
7920 }
7921
7922 async fn handle_register_buffer_with_language_servers(
7923 this: Entity<Self>,
7924 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
7925 mut cx: AsyncApp,
7926 ) -> Result<proto::Ack> {
7927 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7928 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
7929 this.update(&mut cx, |this, cx| {
7930 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
7931 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
7932 project_id: upstream_project_id,
7933 buffer_id: buffer_id.to_proto(),
7934 only_servers: envelope.payload.only_servers,
7935 });
7936 }
7937
7938 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
7939 anyhow::bail!("buffer is not open");
7940 };
7941
7942 let handle = this.register_buffer_with_language_servers(
7943 &buffer,
7944 envelope
7945 .payload
7946 .only_servers
7947 .into_iter()
7948 .filter_map(|selector| {
7949 Some(match selector.selector? {
7950 proto::language_server_selector::Selector::ServerId(server_id) => {
7951 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
7952 }
7953 proto::language_server_selector::Selector::Name(name) => {
7954 LanguageServerSelector::Name(LanguageServerName(
7955 SharedString::from(name),
7956 ))
7957 }
7958 })
7959 })
7960 .collect(),
7961 false,
7962 cx,
7963 );
7964 this.buffer_store().update(cx, |buffer_store, _| {
7965 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
7966 });
7967
7968 Ok(())
7969 })??;
7970 Ok(proto::Ack {})
7971 }
7972
7973 async fn handle_language_server_id_for_name(
7974 lsp_store: Entity<Self>,
7975 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7976 mut cx: AsyncApp,
7977 ) -> Result<proto::LanguageServerIdForNameResponse> {
7978 let name = &envelope.payload.name;
7979 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7980 lsp_store
7981 .update(&mut cx, |lsp_store, cx| {
7982 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7983 let server_id = buffer.update(cx, |buffer, cx| {
7984 lsp_store
7985 .language_servers_for_local_buffer(buffer, cx)
7986 .find_map(|(adapter, server)| {
7987 if adapter.name.0.as_ref() == name {
7988 Some(server.server_id())
7989 } else {
7990 None
7991 }
7992 })
7993 });
7994 Ok(server_id)
7995 })?
7996 .map(|server_id| proto::LanguageServerIdForNameResponse {
7997 server_id: server_id.map(|id| id.to_proto()),
7998 })
7999 }
8000
8001 async fn handle_rename_project_entry(
8002 this: Entity<Self>,
8003 envelope: TypedEnvelope<proto::RenameProjectEntry>,
8004 mut cx: AsyncApp,
8005 ) -> Result<proto::ProjectEntryResponse> {
8006 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8007 let (worktree_id, worktree, old_path, is_dir) = this
8008 .update(&mut cx, |this, cx| {
8009 this.worktree_store
8010 .read(cx)
8011 .worktree_and_entry_for_id(entry_id, cx)
8012 .map(|(worktree, entry)| {
8013 (
8014 worktree.read(cx).id(),
8015 worktree,
8016 entry.path.clone(),
8017 entry.is_dir(),
8018 )
8019 })
8020 })?
8021 .context("worktree not found")?;
8022 let (old_abs_path, new_abs_path) = {
8023 let root_path = worktree.read_with(&mut cx, |this, _| this.abs_path())?;
8024 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
8025 (root_path.join(&old_path), root_path.join(&new_path))
8026 };
8027
8028 Self::will_rename_entry(
8029 this.downgrade(),
8030 worktree_id,
8031 &old_abs_path,
8032 &new_abs_path,
8033 is_dir,
8034 cx.clone(),
8035 )
8036 .await;
8037 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
8038 this.read_with(&mut cx, |this, _| {
8039 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
8040 })
8041 .ok();
8042 response
8043 }
8044
8045 async fn handle_update_diagnostic_summary(
8046 this: Entity<Self>,
8047 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
8048 mut cx: AsyncApp,
8049 ) -> Result<()> {
8050 this.update(&mut cx, |this, cx| {
8051 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8052 if let Some(message) = envelope.payload.summary {
8053 let project_path = ProjectPath {
8054 worktree_id,
8055 path: Arc::<Path>::from_proto(message.path),
8056 };
8057 let path = project_path.path.clone();
8058 let server_id = LanguageServerId(message.language_server_id as usize);
8059 let summary = DiagnosticSummary {
8060 error_count: message.error_count as usize,
8061 warning_count: message.warning_count as usize,
8062 };
8063
8064 if summary.is_empty() {
8065 if let Some(worktree_summaries) =
8066 this.diagnostic_summaries.get_mut(&worktree_id)
8067 {
8068 if let Some(summaries) = worktree_summaries.get_mut(&path) {
8069 summaries.remove(&server_id);
8070 if summaries.is_empty() {
8071 worktree_summaries.remove(&path);
8072 }
8073 }
8074 }
8075 } else {
8076 this.diagnostic_summaries
8077 .entry(worktree_id)
8078 .or_default()
8079 .entry(path)
8080 .or_default()
8081 .insert(server_id, summary);
8082 }
8083 if let Some((downstream_client, project_id)) = &this.downstream_client {
8084 downstream_client
8085 .send(proto::UpdateDiagnosticSummary {
8086 project_id: *project_id,
8087 worktree_id: worktree_id.to_proto(),
8088 summary: Some(proto::DiagnosticSummary {
8089 path: project_path.path.as_ref().to_proto(),
8090 language_server_id: server_id.0 as u64,
8091 error_count: summary.error_count as u32,
8092 warning_count: summary.warning_count as u32,
8093 }),
8094 })
8095 .log_err();
8096 }
8097 cx.emit(LspStoreEvent::DiagnosticsUpdated {
8098 language_server_id: LanguageServerId(message.language_server_id as usize),
8099 path: project_path,
8100 });
8101 }
8102 Ok(())
8103 })?
8104 }
8105
8106 async fn handle_start_language_server(
8107 this: Entity<Self>,
8108 envelope: TypedEnvelope<proto::StartLanguageServer>,
8109 mut cx: AsyncApp,
8110 ) -> Result<()> {
8111 let server = envelope.payload.server.context("invalid server")?;
8112
8113 this.update(&mut cx, |this, cx| {
8114 let server_id = LanguageServerId(server.id as usize);
8115 this.language_server_statuses.insert(
8116 server_id,
8117 LanguageServerStatus {
8118 name: server.name.clone(),
8119 pending_work: Default::default(),
8120 has_pending_diagnostic_updates: false,
8121 progress_tokens: Default::default(),
8122 },
8123 );
8124 cx.emit(LspStoreEvent::LanguageServerAdded(
8125 server_id,
8126 LanguageServerName(server.name.into()),
8127 server.worktree_id.map(WorktreeId::from_proto),
8128 ));
8129 cx.notify();
8130 })?;
8131 Ok(())
8132 }
8133
8134 async fn handle_update_language_server(
8135 lsp_store: Entity<Self>,
8136 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
8137 mut cx: AsyncApp,
8138 ) -> Result<()> {
8139 lsp_store.update(&mut cx, |lsp_store, cx| {
8140 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8141
8142 match envelope.payload.variant.context("invalid variant")? {
8143 proto::update_language_server::Variant::WorkStart(payload) => {
8144 lsp_store.on_lsp_work_start(
8145 language_server_id,
8146 payload.token,
8147 LanguageServerProgress {
8148 title: payload.title,
8149 is_disk_based_diagnostics_progress: false,
8150 is_cancellable: payload.is_cancellable.unwrap_or(false),
8151 message: payload.message,
8152 percentage: payload.percentage.map(|p| p as usize),
8153 last_update_at: cx.background_executor().now(),
8154 },
8155 cx,
8156 );
8157 }
8158 proto::update_language_server::Variant::WorkProgress(payload) => {
8159 lsp_store.on_lsp_work_progress(
8160 language_server_id,
8161 payload.token,
8162 LanguageServerProgress {
8163 title: None,
8164 is_disk_based_diagnostics_progress: false,
8165 is_cancellable: payload.is_cancellable.unwrap_or(false),
8166 message: payload.message,
8167 percentage: payload.percentage.map(|p| p as usize),
8168 last_update_at: cx.background_executor().now(),
8169 },
8170 cx,
8171 );
8172 }
8173
8174 proto::update_language_server::Variant::WorkEnd(payload) => {
8175 lsp_store.on_lsp_work_end(language_server_id, payload.token, cx);
8176 }
8177
8178 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
8179 lsp_store.disk_based_diagnostics_started(language_server_id, cx);
8180 }
8181
8182 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
8183 lsp_store.disk_based_diagnostics_finished(language_server_id, cx)
8184 }
8185
8186 non_lsp @ proto::update_language_server::Variant::StatusUpdate(_)
8187 | non_lsp @ proto::update_language_server::Variant::RegisteredForBuffer(_) => {
8188 cx.emit(LspStoreEvent::LanguageServerUpdate {
8189 language_server_id,
8190 name: envelope
8191 .payload
8192 .server_name
8193 .map(SharedString::new)
8194 .map(LanguageServerName),
8195 message: non_lsp,
8196 });
8197 }
8198 }
8199
8200 Ok(())
8201 })?
8202 }
8203
8204 async fn handle_language_server_log(
8205 this: Entity<Self>,
8206 envelope: TypedEnvelope<proto::LanguageServerLog>,
8207 mut cx: AsyncApp,
8208 ) -> Result<()> {
8209 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8210 let log_type = envelope
8211 .payload
8212 .log_type
8213 .map(LanguageServerLogType::from_proto)
8214 .context("invalid language server log type")?;
8215
8216 let message = envelope.payload.message;
8217
8218 this.update(&mut cx, |_, cx| {
8219 cx.emit(LspStoreEvent::LanguageServerLog(
8220 language_server_id,
8221 log_type,
8222 message,
8223 ));
8224 })
8225 }
8226
8227 async fn handle_lsp_ext_cancel_flycheck(
8228 lsp_store: Entity<Self>,
8229 envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
8230 mut cx: AsyncApp,
8231 ) -> Result<proto::Ack> {
8232 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8233 lsp_store.read_with(&mut cx, |lsp_store, _| {
8234 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8235 server
8236 .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
8237 .context("handling lsp ext cancel flycheck")
8238 } else {
8239 anyhow::Ok(())
8240 }
8241 })??;
8242
8243 Ok(proto::Ack {})
8244 }
8245
8246 async fn handle_lsp_ext_run_flycheck(
8247 lsp_store: Entity<Self>,
8248 envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
8249 mut cx: AsyncApp,
8250 ) -> Result<proto::Ack> {
8251 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8252 lsp_store.update(&mut cx, |lsp_store, cx| {
8253 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8254 let text_document = if envelope.payload.current_file_only {
8255 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8256 lsp_store
8257 .buffer_store()
8258 .read(cx)
8259 .get(buffer_id)
8260 .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
8261 .map(|path| make_text_document_identifier(&path))
8262 .transpose()?
8263 } else {
8264 None
8265 };
8266 server
8267 .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
8268 &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
8269 )
8270 .context("handling lsp ext run flycheck")
8271 } else {
8272 anyhow::Ok(())
8273 }
8274 })??;
8275
8276 Ok(proto::Ack {})
8277 }
8278
8279 async fn handle_lsp_ext_clear_flycheck(
8280 lsp_store: Entity<Self>,
8281 envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
8282 mut cx: AsyncApp,
8283 ) -> Result<proto::Ack> {
8284 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8285 lsp_store.read_with(&mut cx, |lsp_store, _| {
8286 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8287 server
8288 .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
8289 .context("handling lsp ext clear flycheck")
8290 } else {
8291 anyhow::Ok(())
8292 }
8293 })??;
8294
8295 Ok(proto::Ack {})
8296 }
8297
8298 pub fn disk_based_diagnostics_started(
8299 &mut self,
8300 language_server_id: LanguageServerId,
8301 cx: &mut Context<Self>,
8302 ) {
8303 if let Some(language_server_status) =
8304 self.language_server_statuses.get_mut(&language_server_id)
8305 {
8306 language_server_status.has_pending_diagnostic_updates = true;
8307 }
8308
8309 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
8310 cx.emit(LspStoreEvent::LanguageServerUpdate {
8311 language_server_id,
8312 name: self
8313 .language_server_adapter_for_id(language_server_id)
8314 .map(|adapter| adapter.name()),
8315 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
8316 Default::default(),
8317 ),
8318 })
8319 }
8320
8321 pub fn disk_based_diagnostics_finished(
8322 &mut self,
8323 language_server_id: LanguageServerId,
8324 cx: &mut Context<Self>,
8325 ) {
8326 if let Some(language_server_status) =
8327 self.language_server_statuses.get_mut(&language_server_id)
8328 {
8329 language_server_status.has_pending_diagnostic_updates = false;
8330 }
8331
8332 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
8333 cx.emit(LspStoreEvent::LanguageServerUpdate {
8334 language_server_id,
8335 name: self
8336 .language_server_adapter_for_id(language_server_id)
8337 .map(|adapter| adapter.name()),
8338 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
8339 Default::default(),
8340 ),
8341 })
8342 }
8343
8344 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
8345 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
8346 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
8347 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
8348 // the language server might take some time to publish diagnostics.
8349 fn simulate_disk_based_diagnostics_events_if_needed(
8350 &mut self,
8351 language_server_id: LanguageServerId,
8352 cx: &mut Context<Self>,
8353 ) {
8354 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
8355
8356 let Some(LanguageServerState::Running {
8357 simulate_disk_based_diagnostics_completion,
8358 adapter,
8359 ..
8360 }) = self
8361 .as_local_mut()
8362 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
8363 else {
8364 return;
8365 };
8366
8367 if adapter.disk_based_diagnostics_progress_token.is_some() {
8368 return;
8369 }
8370
8371 let prev_task =
8372 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
8373 cx.background_executor()
8374 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
8375 .await;
8376
8377 this.update(cx, |this, cx| {
8378 this.disk_based_diagnostics_finished(language_server_id, cx);
8379
8380 if let Some(LanguageServerState::Running {
8381 simulate_disk_based_diagnostics_completion,
8382 ..
8383 }) = this.as_local_mut().and_then(|local_store| {
8384 local_store.language_servers.get_mut(&language_server_id)
8385 }) {
8386 *simulate_disk_based_diagnostics_completion = None;
8387 }
8388 })
8389 .ok();
8390 }));
8391
8392 if prev_task.is_none() {
8393 self.disk_based_diagnostics_started(language_server_id, cx);
8394 }
8395 }
8396
8397 pub fn language_server_statuses(
8398 &self,
8399 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
8400 self.language_server_statuses
8401 .iter()
8402 .map(|(key, value)| (*key, value))
8403 }
8404
8405 pub(super) fn did_rename_entry(
8406 &self,
8407 worktree_id: WorktreeId,
8408 old_path: &Path,
8409 new_path: &Path,
8410 is_dir: bool,
8411 ) {
8412 maybe!({
8413 let local_store = self.as_local()?;
8414
8415 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
8416 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
8417
8418 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8419 let Some(filter) = local_store
8420 .language_server_paths_watched_for_rename
8421 .get(&language_server.server_id())
8422 else {
8423 continue;
8424 };
8425
8426 if filter.should_send_did_rename(&old_uri, is_dir) {
8427 language_server
8428 .notify::<DidRenameFiles>(&RenameFilesParams {
8429 files: vec![FileRename {
8430 old_uri: old_uri.clone(),
8431 new_uri: new_uri.clone(),
8432 }],
8433 })
8434 .ok();
8435 }
8436 }
8437 Some(())
8438 });
8439 }
8440
8441 pub(super) fn will_rename_entry(
8442 this: WeakEntity<Self>,
8443 worktree_id: WorktreeId,
8444 old_path: &Path,
8445 new_path: &Path,
8446 is_dir: bool,
8447 cx: AsyncApp,
8448 ) -> Task<()> {
8449 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
8450 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
8451 cx.spawn(async move |cx| {
8452 let mut tasks = vec![];
8453 this.update(cx, |this, cx| {
8454 let local_store = this.as_local()?;
8455 let old_uri = old_uri?;
8456 let new_uri = new_uri?;
8457 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8458 let Some(filter) = local_store
8459 .language_server_paths_watched_for_rename
8460 .get(&language_server.server_id())
8461 else {
8462 continue;
8463 };
8464 let Some(adapter) =
8465 this.language_server_adapter_for_id(language_server.server_id())
8466 else {
8467 continue;
8468 };
8469 if filter.should_send_will_rename(&old_uri, is_dir) {
8470 let apply_edit = cx.spawn({
8471 let old_uri = old_uri.clone();
8472 let new_uri = new_uri.clone();
8473 let language_server = language_server.clone();
8474 async move |this, cx| {
8475 let edit = language_server
8476 .request::<WillRenameFiles>(RenameFilesParams {
8477 files: vec![FileRename { old_uri, new_uri }],
8478 })
8479 .await
8480 .into_response()
8481 .context("will rename files")
8482 .log_err()
8483 .flatten()?;
8484
8485 LocalLspStore::deserialize_workspace_edit(
8486 this.upgrade()?,
8487 edit,
8488 false,
8489 adapter.clone(),
8490 language_server.clone(),
8491 cx,
8492 )
8493 .await
8494 .ok();
8495 Some(())
8496 }
8497 });
8498 tasks.push(apply_edit);
8499 }
8500 }
8501 Some(())
8502 })
8503 .ok()
8504 .flatten();
8505 for task in tasks {
8506 // Await on tasks sequentially so that the order of application of edits is deterministic
8507 // (at least with regards to the order of registration of language servers)
8508 task.await;
8509 }
8510 })
8511 }
8512
8513 fn lsp_notify_abs_paths_changed(
8514 &mut self,
8515 server_id: LanguageServerId,
8516 changes: Vec<PathEvent>,
8517 ) {
8518 maybe!({
8519 let server = self.language_server_for_id(server_id)?;
8520 let changes = changes
8521 .into_iter()
8522 .filter_map(|event| {
8523 let typ = match event.kind? {
8524 PathEventKind::Created => lsp::FileChangeType::CREATED,
8525 PathEventKind::Removed => lsp::FileChangeType::DELETED,
8526 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
8527 };
8528 Some(lsp::FileEvent {
8529 uri: file_path_to_lsp_url(&event.path).log_err()?,
8530 typ,
8531 })
8532 })
8533 .collect::<Vec<_>>();
8534 if !changes.is_empty() {
8535 server
8536 .notify::<lsp::notification::DidChangeWatchedFiles>(
8537 &lsp::DidChangeWatchedFilesParams { changes },
8538 )
8539 .ok();
8540 }
8541 Some(())
8542 });
8543 }
8544
8545 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8546 let local_lsp_store = self.as_local()?;
8547 if let Some(LanguageServerState::Running { server, .. }) =
8548 local_lsp_store.language_servers.get(&id)
8549 {
8550 Some(server.clone())
8551 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
8552 Some(Arc::clone(server))
8553 } else {
8554 None
8555 }
8556 }
8557
8558 fn on_lsp_progress(
8559 &mut self,
8560 progress: lsp::ProgressParams,
8561 language_server_id: LanguageServerId,
8562 disk_based_diagnostics_progress_token: Option<String>,
8563 cx: &mut Context<Self>,
8564 ) {
8565 let token = match progress.token {
8566 lsp::NumberOrString::String(token) => token,
8567 lsp::NumberOrString::Number(token) => {
8568 log::info!("skipping numeric progress token {}", token);
8569 return;
8570 }
8571 };
8572
8573 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
8574 let language_server_status =
8575 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8576 status
8577 } else {
8578 return;
8579 };
8580
8581 if !language_server_status.progress_tokens.contains(&token) {
8582 return;
8583 }
8584
8585 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
8586 .as_ref()
8587 .map_or(false, |disk_based_token| {
8588 token.starts_with(disk_based_token)
8589 });
8590
8591 match progress {
8592 lsp::WorkDoneProgress::Begin(report) => {
8593 if is_disk_based_diagnostics_progress {
8594 self.disk_based_diagnostics_started(language_server_id, cx);
8595 }
8596 self.on_lsp_work_start(
8597 language_server_id,
8598 token.clone(),
8599 LanguageServerProgress {
8600 title: Some(report.title),
8601 is_disk_based_diagnostics_progress,
8602 is_cancellable: report.cancellable.unwrap_or(false),
8603 message: report.message.clone(),
8604 percentage: report.percentage.map(|p| p as usize),
8605 last_update_at: cx.background_executor().now(),
8606 },
8607 cx,
8608 );
8609 }
8610 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
8611 language_server_id,
8612 token,
8613 LanguageServerProgress {
8614 title: None,
8615 is_disk_based_diagnostics_progress,
8616 is_cancellable: report.cancellable.unwrap_or(false),
8617 message: report.message,
8618 percentage: report.percentage.map(|p| p as usize),
8619 last_update_at: cx.background_executor().now(),
8620 },
8621 cx,
8622 ),
8623 lsp::WorkDoneProgress::End(_) => {
8624 language_server_status.progress_tokens.remove(&token);
8625 self.on_lsp_work_end(language_server_id, token.clone(), cx);
8626 if is_disk_based_diagnostics_progress {
8627 self.disk_based_diagnostics_finished(language_server_id, cx);
8628 }
8629 }
8630 }
8631 }
8632
8633 fn on_lsp_work_start(
8634 &mut self,
8635 language_server_id: LanguageServerId,
8636 token: String,
8637 progress: LanguageServerProgress,
8638 cx: &mut Context<Self>,
8639 ) {
8640 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8641 status.pending_work.insert(token.clone(), progress.clone());
8642 cx.notify();
8643 }
8644 cx.emit(LspStoreEvent::LanguageServerUpdate {
8645 language_server_id,
8646 name: self
8647 .language_server_adapter_for_id(language_server_id)
8648 .map(|adapter| adapter.name()),
8649 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
8650 token,
8651 title: progress.title,
8652 message: progress.message,
8653 percentage: progress.percentage.map(|p| p as u32),
8654 is_cancellable: Some(progress.is_cancellable),
8655 }),
8656 })
8657 }
8658
8659 fn on_lsp_work_progress(
8660 &mut self,
8661 language_server_id: LanguageServerId,
8662 token: String,
8663 progress: LanguageServerProgress,
8664 cx: &mut Context<Self>,
8665 ) {
8666 let mut did_update = false;
8667 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8668 match status.pending_work.entry(token.clone()) {
8669 btree_map::Entry::Vacant(entry) => {
8670 entry.insert(progress.clone());
8671 did_update = true;
8672 }
8673 btree_map::Entry::Occupied(mut entry) => {
8674 let entry = entry.get_mut();
8675 if (progress.last_update_at - entry.last_update_at)
8676 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
8677 {
8678 entry.last_update_at = progress.last_update_at;
8679 if progress.message.is_some() {
8680 entry.message = progress.message.clone();
8681 }
8682 if progress.percentage.is_some() {
8683 entry.percentage = progress.percentage;
8684 }
8685 if progress.is_cancellable != entry.is_cancellable {
8686 entry.is_cancellable = progress.is_cancellable;
8687 }
8688 did_update = true;
8689 }
8690 }
8691 }
8692 }
8693
8694 if did_update {
8695 cx.emit(LspStoreEvent::LanguageServerUpdate {
8696 language_server_id,
8697 name: self
8698 .language_server_adapter_for_id(language_server_id)
8699 .map(|adapter| adapter.name()),
8700 message: proto::update_language_server::Variant::WorkProgress(
8701 proto::LspWorkProgress {
8702 token,
8703 message: progress.message,
8704 percentage: progress.percentage.map(|p| p as u32),
8705 is_cancellable: Some(progress.is_cancellable),
8706 },
8707 ),
8708 })
8709 }
8710 }
8711
8712 fn on_lsp_work_end(
8713 &mut self,
8714 language_server_id: LanguageServerId,
8715 token: String,
8716 cx: &mut Context<Self>,
8717 ) {
8718 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8719 if let Some(work) = status.pending_work.remove(&token) {
8720 if !work.is_disk_based_diagnostics_progress {
8721 cx.emit(LspStoreEvent::RefreshInlayHints);
8722 }
8723 }
8724 cx.notify();
8725 }
8726
8727 cx.emit(LspStoreEvent::LanguageServerUpdate {
8728 language_server_id,
8729 name: self
8730 .language_server_adapter_for_id(language_server_id)
8731 .map(|adapter| adapter.name()),
8732 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
8733 })
8734 }
8735
8736 pub async fn handle_resolve_completion_documentation(
8737 this: Entity<Self>,
8738 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8739 mut cx: AsyncApp,
8740 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8741 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8742
8743 let completion = this
8744 .read_with(&cx, |this, cx| {
8745 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8746 let server = this
8747 .language_server_for_id(id)
8748 .with_context(|| format!("No language server {id}"))?;
8749
8750 anyhow::Ok(cx.background_spawn(async move {
8751 let can_resolve = server
8752 .capabilities()
8753 .completion_provider
8754 .as_ref()
8755 .and_then(|options| options.resolve_provider)
8756 .unwrap_or(false);
8757 if can_resolve {
8758 server
8759 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
8760 .await
8761 .into_response()
8762 .context("resolve completion item")
8763 } else {
8764 anyhow::Ok(lsp_completion)
8765 }
8766 }))
8767 })??
8768 .await?;
8769
8770 let mut documentation_is_markdown = false;
8771 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
8772 let documentation = match completion.documentation {
8773 Some(lsp::Documentation::String(text)) => text,
8774
8775 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8776 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
8777 value
8778 }
8779
8780 _ => String::new(),
8781 };
8782
8783 // If we have a new buffer_id, that means we're talking to a new client
8784 // and want to check for new text_edits in the completion too.
8785 let mut old_replace_start = None;
8786 let mut old_replace_end = None;
8787 let mut old_insert_start = None;
8788 let mut old_insert_end = None;
8789 let mut new_text = String::default();
8790 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
8791 let buffer_snapshot = this.update(&mut cx, |this, cx| {
8792 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8793 anyhow::Ok(buffer.read(cx).snapshot())
8794 })??;
8795
8796 if let Some(text_edit) = completion.text_edit.as_ref() {
8797 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
8798
8799 if let Some(mut edit) = edit {
8800 LineEnding::normalize(&mut edit.new_text);
8801
8802 new_text = edit.new_text;
8803 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
8804 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
8805 if let Some(insert_range) = edit.insert_range {
8806 old_insert_start = Some(serialize_anchor(&insert_range.start));
8807 old_insert_end = Some(serialize_anchor(&insert_range.end));
8808 }
8809 }
8810 }
8811 }
8812
8813 Ok(proto::ResolveCompletionDocumentationResponse {
8814 documentation,
8815 documentation_is_markdown,
8816 old_replace_start,
8817 old_replace_end,
8818 new_text,
8819 lsp_completion,
8820 old_insert_start,
8821 old_insert_end,
8822 })
8823 }
8824
8825 async fn handle_on_type_formatting(
8826 this: Entity<Self>,
8827 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8828 mut cx: AsyncApp,
8829 ) -> Result<proto::OnTypeFormattingResponse> {
8830 let on_type_formatting = this.update(&mut cx, |this, cx| {
8831 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8832 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8833 let position = envelope
8834 .payload
8835 .position
8836 .and_then(deserialize_anchor)
8837 .context("invalid position")?;
8838 anyhow::Ok(this.apply_on_type_formatting(
8839 buffer,
8840 position,
8841 envelope.payload.trigger.clone(),
8842 cx,
8843 ))
8844 })??;
8845
8846 let transaction = on_type_formatting
8847 .await?
8848 .as_ref()
8849 .map(language::proto::serialize_transaction);
8850 Ok(proto::OnTypeFormattingResponse { transaction })
8851 }
8852
8853 async fn handle_refresh_inlay_hints(
8854 this: Entity<Self>,
8855 _: TypedEnvelope<proto::RefreshInlayHints>,
8856 mut cx: AsyncApp,
8857 ) -> Result<proto::Ack> {
8858 this.update(&mut cx, |_, cx| {
8859 cx.emit(LspStoreEvent::RefreshInlayHints);
8860 })?;
8861 Ok(proto::Ack {})
8862 }
8863
8864 async fn handle_pull_workspace_diagnostics(
8865 lsp_store: Entity<Self>,
8866 envelope: TypedEnvelope<proto::PullWorkspaceDiagnostics>,
8867 mut cx: AsyncApp,
8868 ) -> Result<proto::Ack> {
8869 let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
8870 lsp_store.update(&mut cx, |lsp_store, _| {
8871 lsp_store.pull_workspace_diagnostics(server_id);
8872 })?;
8873 Ok(proto::Ack {})
8874 }
8875
8876 async fn handle_inlay_hints(
8877 this: Entity<Self>,
8878 envelope: TypedEnvelope<proto::InlayHints>,
8879 mut cx: AsyncApp,
8880 ) -> Result<proto::InlayHintsResponse> {
8881 let sender_id = envelope.original_sender_id().unwrap_or_default();
8882 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8883 let buffer = this.update(&mut cx, |this, cx| {
8884 this.buffer_store.read(cx).get_existing(buffer_id)
8885 })??;
8886 buffer
8887 .update(&mut cx, |buffer, _| {
8888 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8889 })?
8890 .await
8891 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8892
8893 let start = envelope
8894 .payload
8895 .start
8896 .and_then(deserialize_anchor)
8897 .context("missing range start")?;
8898 let end = envelope
8899 .payload
8900 .end
8901 .and_then(deserialize_anchor)
8902 .context("missing range end")?;
8903 let buffer_hints = this
8904 .update(&mut cx, |lsp_store, cx| {
8905 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
8906 })?
8907 .await
8908 .context("inlay hints fetch")?;
8909
8910 this.update(&mut cx, |project, cx| {
8911 InlayHints::response_to_proto(
8912 buffer_hints,
8913 project,
8914 sender_id,
8915 &buffer.read(cx).version(),
8916 cx,
8917 )
8918 })
8919 }
8920
8921 async fn handle_get_color_presentation(
8922 lsp_store: Entity<Self>,
8923 envelope: TypedEnvelope<proto::GetColorPresentation>,
8924 mut cx: AsyncApp,
8925 ) -> Result<proto::GetColorPresentationResponse> {
8926 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8927 let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
8928 lsp_store.buffer_store.read(cx).get_existing(buffer_id)
8929 })??;
8930
8931 let color = envelope
8932 .payload
8933 .color
8934 .context("invalid color resolve request")?;
8935 let start = color
8936 .lsp_range_start
8937 .context("invalid color resolve request")?;
8938 let end = color
8939 .lsp_range_end
8940 .context("invalid color resolve request")?;
8941
8942 let color = DocumentColor {
8943 lsp_range: lsp::Range {
8944 start: point_to_lsp(PointUtf16::new(start.row, start.column)),
8945 end: point_to_lsp(PointUtf16::new(end.row, end.column)),
8946 },
8947 color: lsp::Color {
8948 red: color.red,
8949 green: color.green,
8950 blue: color.blue,
8951 alpha: color.alpha,
8952 },
8953 resolved: false,
8954 color_presentations: Vec::new(),
8955 };
8956 let resolved_color = lsp_store
8957 .update(&mut cx, |lsp_store, cx| {
8958 lsp_store.resolve_color_presentation(
8959 color,
8960 buffer.clone(),
8961 LanguageServerId(envelope.payload.server_id as usize),
8962 cx,
8963 )
8964 })?
8965 .await
8966 .context("resolving color presentation")?;
8967
8968 Ok(proto::GetColorPresentationResponse {
8969 presentations: resolved_color
8970 .color_presentations
8971 .into_iter()
8972 .map(|presentation| proto::ColorPresentation {
8973 label: presentation.label.to_string(),
8974 text_edit: presentation.text_edit.map(serialize_lsp_edit),
8975 additional_text_edits: presentation
8976 .additional_text_edits
8977 .into_iter()
8978 .map(serialize_lsp_edit)
8979 .collect(),
8980 })
8981 .collect(),
8982 })
8983 }
8984
8985 async fn handle_resolve_inlay_hint(
8986 this: Entity<Self>,
8987 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8988 mut cx: AsyncApp,
8989 ) -> Result<proto::ResolveInlayHintResponse> {
8990 let proto_hint = envelope
8991 .payload
8992 .hint
8993 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8994 let hint = InlayHints::proto_to_project_hint(proto_hint)
8995 .context("resolved proto inlay hint conversion")?;
8996 let buffer = this.update(&mut cx, |this, cx| {
8997 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8998 this.buffer_store.read(cx).get_existing(buffer_id)
8999 })??;
9000 let response_hint = this
9001 .update(&mut cx, |this, cx| {
9002 this.resolve_inlay_hint(
9003 hint,
9004 buffer,
9005 LanguageServerId(envelope.payload.language_server_id as usize),
9006 cx,
9007 )
9008 })?
9009 .await
9010 .context("inlay hints fetch")?;
9011 Ok(proto::ResolveInlayHintResponse {
9012 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
9013 })
9014 }
9015
9016 async fn handle_refresh_code_lens(
9017 this: Entity<Self>,
9018 _: TypedEnvelope<proto::RefreshCodeLens>,
9019 mut cx: AsyncApp,
9020 ) -> Result<proto::Ack> {
9021 this.update(&mut cx, |_, cx| {
9022 cx.emit(LspStoreEvent::RefreshCodeLens);
9023 })?;
9024 Ok(proto::Ack {})
9025 }
9026
9027 async fn handle_open_buffer_for_symbol(
9028 this: Entity<Self>,
9029 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
9030 mut cx: AsyncApp,
9031 ) -> Result<proto::OpenBufferForSymbolResponse> {
9032 let peer_id = envelope.original_sender_id().unwrap_or_default();
9033 let symbol = envelope.payload.symbol.context("invalid symbol")?;
9034 let symbol = Self::deserialize_symbol(symbol)?;
9035 let symbol = this.read_with(&mut cx, |this, _| {
9036 let signature = this.symbol_signature(&symbol.path);
9037 anyhow::ensure!(signature == symbol.signature, "invalid symbol signature");
9038 Ok(symbol)
9039 })??;
9040 let buffer = this
9041 .update(&mut cx, |this, cx| {
9042 this.open_buffer_for_symbol(
9043 &Symbol {
9044 language_server_name: symbol.language_server_name,
9045 source_worktree_id: symbol.source_worktree_id,
9046 source_language_server_id: symbol.source_language_server_id,
9047 path: symbol.path,
9048 name: symbol.name,
9049 kind: symbol.kind,
9050 range: symbol.range,
9051 signature: symbol.signature,
9052 label: CodeLabel {
9053 text: Default::default(),
9054 runs: Default::default(),
9055 filter_range: Default::default(),
9056 },
9057 },
9058 cx,
9059 )
9060 })?
9061 .await?;
9062
9063 this.update(&mut cx, |this, cx| {
9064 let is_private = buffer
9065 .read(cx)
9066 .file()
9067 .map(|f| f.is_private())
9068 .unwrap_or_default();
9069 if is_private {
9070 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
9071 } else {
9072 this.buffer_store
9073 .update(cx, |buffer_store, cx| {
9074 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
9075 })
9076 .detach_and_log_err(cx);
9077 let buffer_id = buffer.read(cx).remote_id().to_proto();
9078 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
9079 }
9080 })?
9081 }
9082
9083 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
9084 let mut hasher = Sha256::new();
9085 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
9086 hasher.update(project_path.path.to_string_lossy().as_bytes());
9087 hasher.update(self.nonce.to_be_bytes());
9088 hasher.finalize().as_slice().try_into().unwrap()
9089 }
9090
9091 pub async fn handle_get_project_symbols(
9092 this: Entity<Self>,
9093 envelope: TypedEnvelope<proto::GetProjectSymbols>,
9094 mut cx: AsyncApp,
9095 ) -> Result<proto::GetProjectSymbolsResponse> {
9096 let symbols = this
9097 .update(&mut cx, |this, cx| {
9098 this.symbols(&envelope.payload.query, cx)
9099 })?
9100 .await?;
9101
9102 Ok(proto::GetProjectSymbolsResponse {
9103 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
9104 })
9105 }
9106
9107 pub async fn handle_restart_language_servers(
9108 this: Entity<Self>,
9109 envelope: TypedEnvelope<proto::RestartLanguageServers>,
9110 mut cx: AsyncApp,
9111 ) -> Result<proto::Ack> {
9112 this.update(&mut cx, |lsp_store, cx| {
9113 let buffers =
9114 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9115 lsp_store.restart_language_servers_for_buffers(
9116 buffers,
9117 envelope
9118 .payload
9119 .only_servers
9120 .into_iter()
9121 .filter_map(|selector| {
9122 Some(match selector.selector? {
9123 proto::language_server_selector::Selector::ServerId(server_id) => {
9124 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
9125 }
9126 proto::language_server_selector::Selector::Name(name) => {
9127 LanguageServerSelector::Name(LanguageServerName(
9128 SharedString::from(name),
9129 ))
9130 }
9131 })
9132 })
9133 .collect(),
9134 cx,
9135 );
9136 })?;
9137
9138 Ok(proto::Ack {})
9139 }
9140
9141 pub async fn handle_stop_language_servers(
9142 lsp_store: Entity<Self>,
9143 envelope: TypedEnvelope<proto::StopLanguageServers>,
9144 mut cx: AsyncApp,
9145 ) -> Result<proto::Ack> {
9146 lsp_store.update(&mut cx, |lsp_store, cx| {
9147 if envelope.payload.all
9148 && envelope.payload.also_servers.is_empty()
9149 && envelope.payload.buffer_ids.is_empty()
9150 {
9151 lsp_store.stop_all_language_servers(cx);
9152 } else {
9153 let buffers =
9154 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9155 lsp_store.stop_language_servers_for_buffers(
9156 buffers,
9157 envelope
9158 .payload
9159 .also_servers
9160 .into_iter()
9161 .filter_map(|selector| {
9162 Some(match selector.selector? {
9163 proto::language_server_selector::Selector::ServerId(server_id) => {
9164 LanguageServerSelector::Id(LanguageServerId::from_proto(
9165 server_id,
9166 ))
9167 }
9168 proto::language_server_selector::Selector::Name(name) => {
9169 LanguageServerSelector::Name(LanguageServerName(
9170 SharedString::from(name),
9171 ))
9172 }
9173 })
9174 })
9175 .collect(),
9176 cx,
9177 );
9178 }
9179 })?;
9180
9181 Ok(proto::Ack {})
9182 }
9183
9184 pub async fn handle_cancel_language_server_work(
9185 this: Entity<Self>,
9186 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
9187 mut cx: AsyncApp,
9188 ) -> Result<proto::Ack> {
9189 this.update(&mut cx, |this, cx| {
9190 if let Some(work) = envelope.payload.work {
9191 match work {
9192 proto::cancel_language_server_work::Work::Buffers(buffers) => {
9193 let buffers =
9194 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
9195 this.cancel_language_server_work_for_buffers(buffers, cx);
9196 }
9197 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
9198 let server_id = LanguageServerId::from_proto(work.language_server_id);
9199 this.cancel_language_server_work(server_id, work.token, cx);
9200 }
9201 }
9202 }
9203 })?;
9204
9205 Ok(proto::Ack {})
9206 }
9207
9208 fn buffer_ids_to_buffers(
9209 &mut self,
9210 buffer_ids: impl Iterator<Item = u64>,
9211 cx: &mut Context<Self>,
9212 ) -> Vec<Entity<Buffer>> {
9213 buffer_ids
9214 .into_iter()
9215 .flat_map(|buffer_id| {
9216 self.buffer_store
9217 .read(cx)
9218 .get(BufferId::new(buffer_id).log_err()?)
9219 })
9220 .collect::<Vec<_>>()
9221 }
9222
9223 async fn handle_apply_additional_edits_for_completion(
9224 this: Entity<Self>,
9225 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
9226 mut cx: AsyncApp,
9227 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
9228 let (buffer, completion) = this.update(&mut cx, |this, cx| {
9229 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9230 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
9231 let completion = Self::deserialize_completion(
9232 envelope.payload.completion.context("invalid completion")?,
9233 )?;
9234 anyhow::Ok((buffer, completion))
9235 })??;
9236
9237 let apply_additional_edits = this.update(&mut cx, |this, cx| {
9238 this.apply_additional_edits_for_completion(
9239 buffer,
9240 Rc::new(RefCell::new(Box::new([Completion {
9241 replace_range: completion.replace_range,
9242 new_text: completion.new_text,
9243 source: completion.source,
9244 documentation: None,
9245 label: CodeLabel {
9246 text: Default::default(),
9247 runs: Default::default(),
9248 filter_range: Default::default(),
9249 },
9250 insert_text_mode: None,
9251 icon_path: None,
9252 confirm: None,
9253 }]))),
9254 0,
9255 false,
9256 cx,
9257 )
9258 })?;
9259
9260 Ok(proto::ApplyCompletionAdditionalEditsResponse {
9261 transaction: apply_additional_edits
9262 .await?
9263 .as_ref()
9264 .map(language::proto::serialize_transaction),
9265 })
9266 }
9267
9268 pub fn last_formatting_failure(&self) -> Option<&str> {
9269 self.last_formatting_failure.as_deref()
9270 }
9271
9272 pub fn reset_last_formatting_failure(&mut self) {
9273 self.last_formatting_failure = None;
9274 }
9275
9276 pub fn environment_for_buffer(
9277 &self,
9278 buffer: &Entity<Buffer>,
9279 cx: &mut Context<Self>,
9280 ) -> Shared<Task<Option<HashMap<String, String>>>> {
9281 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
9282 environment.update(cx, |env, cx| {
9283 env.get_buffer_environment(&buffer, &self.worktree_store, cx)
9284 })
9285 } else {
9286 Task::ready(None).shared()
9287 }
9288 }
9289
9290 pub fn format(
9291 &mut self,
9292 buffers: HashSet<Entity<Buffer>>,
9293 target: LspFormatTarget,
9294 push_to_history: bool,
9295 trigger: FormatTrigger,
9296 cx: &mut Context<Self>,
9297 ) -> Task<anyhow::Result<ProjectTransaction>> {
9298 let logger = zlog::scoped!("format");
9299 if let Some(_) = self.as_local() {
9300 zlog::trace!(logger => "Formatting locally");
9301 let logger = zlog::scoped!(logger => "local");
9302 let buffers = buffers
9303 .into_iter()
9304 .map(|buffer_handle| {
9305 let buffer = buffer_handle.read(cx);
9306 let buffer_abs_path = File::from_dyn(buffer.file())
9307 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
9308
9309 (buffer_handle, buffer_abs_path, buffer.remote_id())
9310 })
9311 .collect::<Vec<_>>();
9312
9313 cx.spawn(async move |lsp_store, cx| {
9314 let mut formattable_buffers = Vec::with_capacity(buffers.len());
9315
9316 for (handle, abs_path, id) in buffers {
9317 let env = lsp_store
9318 .update(cx, |lsp_store, cx| {
9319 lsp_store.environment_for_buffer(&handle, cx)
9320 })?
9321 .await;
9322
9323 let ranges = match &target {
9324 LspFormatTarget::Buffers => None,
9325 LspFormatTarget::Ranges(ranges) => {
9326 Some(ranges.get(&id).context("No format ranges provided for buffer")?.clone())
9327 }
9328 };
9329
9330 formattable_buffers.push(FormattableBuffer {
9331 handle,
9332 abs_path,
9333 env,
9334 ranges,
9335 });
9336 }
9337 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
9338
9339 let format_timer = zlog::time!(logger => "Formatting buffers");
9340 let result = LocalLspStore::format_locally(
9341 lsp_store.clone(),
9342 formattable_buffers,
9343 push_to_history,
9344 trigger,
9345 logger,
9346 cx,
9347 )
9348 .await;
9349 format_timer.end();
9350
9351 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
9352
9353 lsp_store.update(cx, |lsp_store, _| {
9354 lsp_store.update_last_formatting_failure(&result);
9355 })?;
9356
9357 result
9358 })
9359 } else if let Some((client, project_id)) = self.upstream_client() {
9360 zlog::trace!(logger => "Formatting remotely");
9361 let logger = zlog::scoped!(logger => "remote");
9362 // Don't support formatting ranges via remote
9363 match target {
9364 LspFormatTarget::Buffers => {}
9365 LspFormatTarget::Ranges(_) => {
9366 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
9367 return Task::ready(Ok(ProjectTransaction::default()));
9368 }
9369 }
9370
9371 let buffer_store = self.buffer_store();
9372 cx.spawn(async move |lsp_store, cx| {
9373 zlog::trace!(logger => "Sending remote format request");
9374 let request_timer = zlog::time!(logger => "remote format request");
9375 let result = client
9376 .request(proto::FormatBuffers {
9377 project_id,
9378 trigger: trigger as i32,
9379 buffer_ids: buffers
9380 .iter()
9381 .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id().into()))
9382 .collect::<Result<_>>()?,
9383 })
9384 .await
9385 .and_then(|result| result.transaction.context("missing transaction"));
9386 request_timer.end();
9387
9388 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
9389
9390 lsp_store.update(cx, |lsp_store, _| {
9391 lsp_store.update_last_formatting_failure(&result);
9392 })?;
9393
9394 let transaction_response = result?;
9395 let _timer = zlog::time!(logger => "deserializing project transaction");
9396 buffer_store
9397 .update(cx, |buffer_store, cx| {
9398 buffer_store.deserialize_project_transaction(
9399 transaction_response,
9400 push_to_history,
9401 cx,
9402 )
9403 })?
9404 .await
9405 })
9406 } else {
9407 zlog::trace!(logger => "Not formatting");
9408 Task::ready(Ok(ProjectTransaction::default()))
9409 }
9410 }
9411
9412 async fn handle_format_buffers(
9413 this: Entity<Self>,
9414 envelope: TypedEnvelope<proto::FormatBuffers>,
9415 mut cx: AsyncApp,
9416 ) -> Result<proto::FormatBuffersResponse> {
9417 let sender_id = envelope.original_sender_id().unwrap_or_default();
9418 let format = this.update(&mut cx, |this, cx| {
9419 let mut buffers = HashSet::default();
9420 for buffer_id in &envelope.payload.buffer_ids {
9421 let buffer_id = BufferId::new(*buffer_id)?;
9422 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9423 }
9424 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
9425 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
9426 })??;
9427
9428 let project_transaction = format.await?;
9429 let project_transaction = this.update(&mut cx, |this, cx| {
9430 this.buffer_store.update(cx, |buffer_store, cx| {
9431 buffer_store.serialize_project_transaction_for_peer(
9432 project_transaction,
9433 sender_id,
9434 cx,
9435 )
9436 })
9437 })?;
9438 Ok(proto::FormatBuffersResponse {
9439 transaction: Some(project_transaction),
9440 })
9441 }
9442
9443 async fn handle_apply_code_action_kind(
9444 this: Entity<Self>,
9445 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
9446 mut cx: AsyncApp,
9447 ) -> Result<proto::ApplyCodeActionKindResponse> {
9448 let sender_id = envelope.original_sender_id().unwrap_or_default();
9449 let format = this.update(&mut cx, |this, cx| {
9450 let mut buffers = HashSet::default();
9451 for buffer_id in &envelope.payload.buffer_ids {
9452 let buffer_id = BufferId::new(*buffer_id)?;
9453 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9454 }
9455 let kind = match envelope.payload.kind.as_str() {
9456 "" => CodeActionKind::EMPTY,
9457 "quickfix" => CodeActionKind::QUICKFIX,
9458 "refactor" => CodeActionKind::REFACTOR,
9459 "refactor.extract" => CodeActionKind::REFACTOR_EXTRACT,
9460 "refactor.inline" => CodeActionKind::REFACTOR_INLINE,
9461 "refactor.rewrite" => CodeActionKind::REFACTOR_REWRITE,
9462 "source" => CodeActionKind::SOURCE,
9463 "source.organizeImports" => CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
9464 "source.fixAll" => CodeActionKind::SOURCE_FIX_ALL,
9465 _ => anyhow::bail!(
9466 "Invalid code action kind {}",
9467 envelope.payload.kind.as_str()
9468 ),
9469 };
9470 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
9471 })??;
9472
9473 let project_transaction = format.await?;
9474 let project_transaction = this.update(&mut cx, |this, cx| {
9475 this.buffer_store.update(cx, |buffer_store, cx| {
9476 buffer_store.serialize_project_transaction_for_peer(
9477 project_transaction,
9478 sender_id,
9479 cx,
9480 )
9481 })
9482 })?;
9483 Ok(proto::ApplyCodeActionKindResponse {
9484 transaction: Some(project_transaction),
9485 })
9486 }
9487
9488 async fn shutdown_language_server(
9489 server_state: Option<LanguageServerState>,
9490 name: LanguageServerName,
9491 cx: &mut AsyncApp,
9492 ) {
9493 let server = match server_state {
9494 Some(LanguageServerState::Starting { startup, .. }) => {
9495 let mut timer = cx
9496 .background_executor()
9497 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
9498 .fuse();
9499
9500 select! {
9501 server = startup.fuse() => server,
9502 () = timer => {
9503 log::info!("timeout waiting for language server {name} to finish launching before stopping");
9504 None
9505 },
9506 }
9507 }
9508
9509 Some(LanguageServerState::Running { server, .. }) => Some(server),
9510
9511 None => None,
9512 };
9513
9514 if let Some(server) = server {
9515 if let Some(shutdown) = server.shutdown() {
9516 shutdown.await;
9517 }
9518 }
9519 }
9520
9521 // Returns a list of all of the worktrees which no longer have a language server and the root path
9522 // for the stopped server
9523 fn stop_local_language_server(
9524 &mut self,
9525 server_id: LanguageServerId,
9526 cx: &mut Context<Self>,
9527 ) -> Task<Vec<WorktreeId>> {
9528 let local = match &mut self.mode {
9529 LspStoreMode::Local(local) => local,
9530 _ => {
9531 return Task::ready(Vec::new());
9532 }
9533 };
9534
9535 let mut orphaned_worktrees = Vec::new();
9536 // Remove this server ID from all entries in the given worktree.
9537 local.language_server_ids.retain(|(worktree, _), ids| {
9538 if !ids.remove(&server_id) {
9539 return true;
9540 }
9541
9542 if ids.is_empty() {
9543 orphaned_worktrees.push(*worktree);
9544 false
9545 } else {
9546 true
9547 }
9548 });
9549 self.buffer_store.update(cx, |buffer_store, cx| {
9550 for buffer in buffer_store.buffers() {
9551 buffer.update(cx, |buffer, cx| {
9552 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
9553 buffer.set_completion_triggers(server_id, Default::default(), cx);
9554 });
9555 }
9556 });
9557
9558 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
9559 summaries.retain(|path, summaries_by_server_id| {
9560 if summaries_by_server_id.remove(&server_id).is_some() {
9561 if let Some((client, project_id)) = self.downstream_client.clone() {
9562 client
9563 .send(proto::UpdateDiagnosticSummary {
9564 project_id,
9565 worktree_id: worktree_id.to_proto(),
9566 summary: Some(proto::DiagnosticSummary {
9567 path: path.as_ref().to_proto(),
9568 language_server_id: server_id.0 as u64,
9569 error_count: 0,
9570 warning_count: 0,
9571 }),
9572 })
9573 .log_err();
9574 }
9575 !summaries_by_server_id.is_empty()
9576 } else {
9577 true
9578 }
9579 });
9580 }
9581
9582 let local = self.as_local_mut().unwrap();
9583 for diagnostics in local.diagnostics.values_mut() {
9584 diagnostics.retain(|_, diagnostics_by_server_id| {
9585 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
9586 diagnostics_by_server_id.remove(ix);
9587 !diagnostics_by_server_id.is_empty()
9588 } else {
9589 true
9590 }
9591 });
9592 }
9593 local.language_server_watched_paths.remove(&server_id);
9594
9595 let server_state = local.language_servers.remove(&server_id);
9596 self.cleanup_lsp_data(server_id);
9597 let name = self
9598 .language_server_statuses
9599 .remove(&server_id)
9600 .map(|status| LanguageServerName::from(status.name.as_str()))
9601 .or_else(|| {
9602 if let Some(LanguageServerState::Running { adapter, .. }) = server_state.as_ref() {
9603 Some(adapter.name())
9604 } else {
9605 None
9606 }
9607 });
9608
9609 if let Some(name) = name {
9610 log::info!("stopping language server {name}");
9611 self.languages
9612 .update_lsp_binary_status(name.clone(), BinaryStatus::Stopping);
9613 cx.notify();
9614
9615 return cx.spawn(async move |lsp_store, cx| {
9616 Self::shutdown_language_server(server_state, name.clone(), cx).await;
9617 lsp_store
9618 .update(cx, |lsp_store, cx| {
9619 lsp_store
9620 .languages
9621 .update_lsp_binary_status(name, BinaryStatus::Stopped);
9622 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
9623 cx.notify();
9624 })
9625 .ok();
9626 orphaned_worktrees
9627 });
9628 }
9629
9630 if server_state.is_some() {
9631 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
9632 }
9633 Task::ready(orphaned_worktrees)
9634 }
9635
9636 pub fn stop_all_language_servers(&mut self, cx: &mut Context<Self>) {
9637 if let Some((client, project_id)) = self.upstream_client() {
9638 let request = client.request(proto::StopLanguageServers {
9639 project_id,
9640 buffer_ids: Vec::new(),
9641 also_servers: Vec::new(),
9642 all: true,
9643 });
9644 cx.background_spawn(request).detach_and_log_err(cx);
9645 } else {
9646 let Some(local) = self.as_local_mut() else {
9647 return;
9648 };
9649 let language_servers_to_stop = local
9650 .language_server_ids
9651 .values()
9652 .flatten()
9653 .copied()
9654 .collect();
9655 local.lsp_tree.update(cx, |this, _| {
9656 this.remove_nodes(&language_servers_to_stop);
9657 });
9658 let tasks = language_servers_to_stop
9659 .into_iter()
9660 .map(|server| self.stop_local_language_server(server, cx))
9661 .collect::<Vec<_>>();
9662 cx.background_spawn(async move {
9663 futures::future::join_all(tasks).await;
9664 })
9665 .detach();
9666 }
9667 }
9668
9669 pub fn restart_language_servers_for_buffers(
9670 &mut self,
9671 buffers: Vec<Entity<Buffer>>,
9672 only_restart_servers: HashSet<LanguageServerSelector>,
9673 cx: &mut Context<Self>,
9674 ) {
9675 if let Some((client, project_id)) = self.upstream_client() {
9676 let request = client.request(proto::RestartLanguageServers {
9677 project_id,
9678 buffer_ids: buffers
9679 .into_iter()
9680 .map(|b| b.read(cx).remote_id().to_proto())
9681 .collect(),
9682 only_servers: only_restart_servers
9683 .into_iter()
9684 .map(|selector| {
9685 let selector = match selector {
9686 LanguageServerSelector::Id(language_server_id) => {
9687 proto::language_server_selector::Selector::ServerId(
9688 language_server_id.to_proto(),
9689 )
9690 }
9691 LanguageServerSelector::Name(language_server_name) => {
9692 proto::language_server_selector::Selector::Name(
9693 language_server_name.to_string(),
9694 )
9695 }
9696 };
9697 proto::LanguageServerSelector {
9698 selector: Some(selector),
9699 }
9700 })
9701 .collect(),
9702 all: false,
9703 });
9704 cx.background_spawn(request).detach_and_log_err(cx);
9705 } else {
9706 let stop_task = if only_restart_servers.is_empty() {
9707 self.stop_local_language_servers_for_buffers(&buffers, HashSet::default(), cx)
9708 } else {
9709 self.stop_local_language_servers_for_buffers(&[], only_restart_servers.clone(), cx)
9710 };
9711 cx.spawn(async move |lsp_store, cx| {
9712 stop_task.await;
9713 lsp_store
9714 .update(cx, |lsp_store, cx| {
9715 for buffer in buffers {
9716 lsp_store.register_buffer_with_language_servers(
9717 &buffer,
9718 only_restart_servers.clone(),
9719 true,
9720 cx,
9721 );
9722 }
9723 })
9724 .ok()
9725 })
9726 .detach();
9727 }
9728 }
9729
9730 pub fn stop_language_servers_for_buffers(
9731 &mut self,
9732 buffers: Vec<Entity<Buffer>>,
9733 also_restart_servers: HashSet<LanguageServerSelector>,
9734 cx: &mut Context<Self>,
9735 ) {
9736 if let Some((client, project_id)) = self.upstream_client() {
9737 let request = client.request(proto::StopLanguageServers {
9738 project_id,
9739 buffer_ids: buffers
9740 .into_iter()
9741 .map(|b| b.read(cx).remote_id().to_proto())
9742 .collect(),
9743 also_servers: also_restart_servers
9744 .into_iter()
9745 .map(|selector| {
9746 let selector = match selector {
9747 LanguageServerSelector::Id(language_server_id) => {
9748 proto::language_server_selector::Selector::ServerId(
9749 language_server_id.to_proto(),
9750 )
9751 }
9752 LanguageServerSelector::Name(language_server_name) => {
9753 proto::language_server_selector::Selector::Name(
9754 language_server_name.to_string(),
9755 )
9756 }
9757 };
9758 proto::LanguageServerSelector {
9759 selector: Some(selector),
9760 }
9761 })
9762 .collect(),
9763 all: false,
9764 });
9765 cx.background_spawn(request).detach_and_log_err(cx);
9766 } else {
9767 self.stop_local_language_servers_for_buffers(&buffers, also_restart_servers, cx)
9768 .detach();
9769 }
9770 }
9771
9772 fn stop_local_language_servers_for_buffers(
9773 &mut self,
9774 buffers: &[Entity<Buffer>],
9775 also_restart_servers: HashSet<LanguageServerSelector>,
9776 cx: &mut Context<Self>,
9777 ) -> Task<()> {
9778 let Some(local) = self.as_local_mut() else {
9779 return Task::ready(());
9780 };
9781 let mut language_server_names_to_stop = BTreeSet::default();
9782 let mut language_servers_to_stop = also_restart_servers
9783 .into_iter()
9784 .flat_map(|selector| match selector {
9785 LanguageServerSelector::Id(id) => Some(id),
9786 LanguageServerSelector::Name(name) => {
9787 language_server_names_to_stop.insert(name);
9788 None
9789 }
9790 })
9791 .collect::<BTreeSet<_>>();
9792
9793 let mut covered_worktrees = HashSet::default();
9794 for buffer in buffers {
9795 buffer.update(cx, |buffer, cx| {
9796 language_servers_to_stop.extend(local.language_server_ids_for_buffer(buffer, cx));
9797 if let Some(worktree_id) = buffer.file().map(|f| f.worktree_id(cx)) {
9798 if covered_worktrees.insert(worktree_id) {
9799 language_server_names_to_stop.retain(|name| {
9800 match local.language_server_ids.get(&(worktree_id, name.clone())) {
9801 Some(server_ids) => {
9802 language_servers_to_stop
9803 .extend(server_ids.into_iter().copied());
9804 false
9805 }
9806 None => true,
9807 }
9808 });
9809 }
9810 }
9811 });
9812 }
9813 for name in language_server_names_to_stop {
9814 if let Some(server_ids) = local
9815 .language_server_ids
9816 .iter()
9817 .filter(|((_, server_name), _)| server_name == &name)
9818 .map(|((_, _), server_ids)| server_ids)
9819 .max_by_key(|server_ids| server_ids.len())
9820 {
9821 language_servers_to_stop.extend(server_ids.into_iter().copied());
9822 }
9823 }
9824
9825 local.lsp_tree.update(cx, |this, _| {
9826 this.remove_nodes(&language_servers_to_stop);
9827 });
9828 let tasks = language_servers_to_stop
9829 .into_iter()
9830 .map(|server| self.stop_local_language_server(server, cx))
9831 .collect::<Vec<_>>();
9832
9833 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
9834 }
9835
9836 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
9837 let (worktree, relative_path) =
9838 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
9839
9840 let project_path = ProjectPath {
9841 worktree_id: worktree.read(cx).id(),
9842 path: relative_path.into(),
9843 };
9844
9845 Some(
9846 self.buffer_store()
9847 .read(cx)
9848 .get_by_path(&project_path)?
9849 .read(cx),
9850 )
9851 }
9852
9853 pub fn update_diagnostics(
9854 &mut self,
9855 language_server_id: LanguageServerId,
9856 params: lsp::PublishDiagnosticsParams,
9857 result_id: Option<String>,
9858 source_kind: DiagnosticSourceKind,
9859 disk_based_sources: &[String],
9860 cx: &mut Context<Self>,
9861 ) -> Result<()> {
9862 self.merge_diagnostics(
9863 language_server_id,
9864 params,
9865 result_id,
9866 source_kind,
9867 disk_based_sources,
9868 |_, _, _| false,
9869 cx,
9870 )
9871 }
9872
9873 pub fn merge_diagnostics(
9874 &mut self,
9875 language_server_id: LanguageServerId,
9876 mut params: lsp::PublishDiagnosticsParams,
9877 result_id: Option<String>,
9878 source_kind: DiagnosticSourceKind,
9879 disk_based_sources: &[String],
9880 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
9881 cx: &mut Context<Self>,
9882 ) -> Result<()> {
9883 anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
9884 let abs_path = params
9885 .uri
9886 .to_file_path()
9887 .map_err(|()| anyhow!("URI is not a file"))?;
9888 let mut diagnostics = Vec::default();
9889 let mut primary_diagnostic_group_ids = HashMap::default();
9890 let mut sources_by_group_id = HashMap::default();
9891 let mut supporting_diagnostics = HashMap::default();
9892
9893 let adapter = self.language_server_adapter_for_id(language_server_id);
9894
9895 // Ensure that primary diagnostics are always the most severe
9896 params.diagnostics.sort_by_key(|item| item.severity);
9897
9898 for diagnostic in ¶ms.diagnostics {
9899 let source = diagnostic.source.as_ref();
9900 let range = range_from_lsp(diagnostic.range);
9901 let is_supporting = diagnostic
9902 .related_information
9903 .as_ref()
9904 .map_or(false, |infos| {
9905 infos.iter().any(|info| {
9906 primary_diagnostic_group_ids.contains_key(&(
9907 source,
9908 diagnostic.code.clone(),
9909 range_from_lsp(info.location.range),
9910 ))
9911 })
9912 });
9913
9914 let is_unnecessary = diagnostic
9915 .tags
9916 .as_ref()
9917 .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
9918
9919 let underline = self
9920 .language_server_adapter_for_id(language_server_id)
9921 .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
9922
9923 if is_supporting {
9924 supporting_diagnostics.insert(
9925 (source, diagnostic.code.clone(), range),
9926 (diagnostic.severity, is_unnecessary),
9927 );
9928 } else {
9929 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
9930 let is_disk_based =
9931 source.map_or(false, |source| disk_based_sources.contains(source));
9932
9933 sources_by_group_id.insert(group_id, source);
9934 primary_diagnostic_group_ids
9935 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
9936
9937 diagnostics.push(DiagnosticEntry {
9938 range,
9939 diagnostic: Diagnostic {
9940 source: diagnostic.source.clone(),
9941 source_kind,
9942 code: diagnostic.code.clone(),
9943 code_description: diagnostic
9944 .code_description
9945 .as_ref()
9946 .map(|d| d.href.clone()),
9947 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
9948 markdown: adapter.as_ref().and_then(|adapter| {
9949 adapter.diagnostic_message_to_markdown(&diagnostic.message)
9950 }),
9951 message: diagnostic.message.trim().to_string(),
9952 group_id,
9953 is_primary: true,
9954 is_disk_based,
9955 is_unnecessary,
9956 underline,
9957 data: diagnostic.data.clone(),
9958 },
9959 });
9960 if let Some(infos) = &diagnostic.related_information {
9961 for info in infos {
9962 if info.location.uri == params.uri && !info.message.is_empty() {
9963 let range = range_from_lsp(info.location.range);
9964 diagnostics.push(DiagnosticEntry {
9965 range,
9966 diagnostic: Diagnostic {
9967 source: diagnostic.source.clone(),
9968 source_kind,
9969 code: diagnostic.code.clone(),
9970 code_description: diagnostic
9971 .code_description
9972 .as_ref()
9973 .map(|c| c.href.clone()),
9974 severity: DiagnosticSeverity::INFORMATION,
9975 markdown: adapter.as_ref().and_then(|adapter| {
9976 adapter.diagnostic_message_to_markdown(&info.message)
9977 }),
9978 message: info.message.trim().to_string(),
9979 group_id,
9980 is_primary: false,
9981 is_disk_based,
9982 is_unnecessary: false,
9983 underline,
9984 data: diagnostic.data.clone(),
9985 },
9986 });
9987 }
9988 }
9989 }
9990 }
9991 }
9992
9993 for entry in &mut diagnostics {
9994 let diagnostic = &mut entry.diagnostic;
9995 if !diagnostic.is_primary {
9996 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
9997 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
9998 source,
9999 diagnostic.code.clone(),
10000 entry.range.clone(),
10001 )) {
10002 if let Some(severity) = severity {
10003 diagnostic.severity = severity;
10004 }
10005 diagnostic.is_unnecessary = is_unnecessary;
10006 }
10007 }
10008 }
10009
10010 self.merge_diagnostic_entries(
10011 language_server_id,
10012 abs_path,
10013 result_id,
10014 params.version,
10015 diagnostics,
10016 filter,
10017 cx,
10018 )?;
10019 Ok(())
10020 }
10021
10022 fn insert_newly_running_language_server(
10023 &mut self,
10024 adapter: Arc<CachedLspAdapter>,
10025 language_server: Arc<LanguageServer>,
10026 server_id: LanguageServerId,
10027 key: (WorktreeId, LanguageServerName),
10028 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
10029 cx: &mut Context<Self>,
10030 ) {
10031 let Some(local) = self.as_local_mut() else {
10032 return;
10033 };
10034 // If the language server for this key doesn't match the server id, don't store the
10035 // server. Which will cause it to be dropped, killing the process
10036 if local
10037 .language_server_ids
10038 .get(&key)
10039 .map(|ids| !ids.contains(&server_id))
10040 .unwrap_or(false)
10041 {
10042 return;
10043 }
10044
10045 // Update language_servers collection with Running variant of LanguageServerState
10046 // indicating that the server is up and running and ready
10047 let workspace_folders = workspace_folders.lock().clone();
10048 language_server.set_workspace_folders(workspace_folders);
10049
10050 local.language_servers.insert(
10051 server_id,
10052 LanguageServerState::Running {
10053 workspace_refresh_task: lsp_workspace_diagnostics_refresh(
10054 language_server.clone(),
10055 cx,
10056 ),
10057 adapter: adapter.clone(),
10058 server: language_server.clone(),
10059 simulate_disk_based_diagnostics_completion: None,
10060 },
10061 );
10062 local
10063 .languages
10064 .update_lsp_binary_status(adapter.name(), BinaryStatus::None);
10065 if let Some(file_ops_caps) = language_server
10066 .capabilities()
10067 .workspace
10068 .as_ref()
10069 .and_then(|ws| ws.file_operations.as_ref())
10070 {
10071 let did_rename_caps = file_ops_caps.did_rename.as_ref();
10072 let will_rename_caps = file_ops_caps.will_rename.as_ref();
10073 if did_rename_caps.or(will_rename_caps).is_some() {
10074 let watcher = RenamePathsWatchedForServer::default()
10075 .with_did_rename_patterns(did_rename_caps)
10076 .with_will_rename_patterns(will_rename_caps);
10077 local
10078 .language_server_paths_watched_for_rename
10079 .insert(server_id, watcher);
10080 }
10081 }
10082
10083 self.language_server_statuses.insert(
10084 server_id,
10085 LanguageServerStatus {
10086 name: language_server.name().to_string(),
10087 pending_work: Default::default(),
10088 has_pending_diagnostic_updates: false,
10089 progress_tokens: Default::default(),
10090 },
10091 );
10092
10093 cx.emit(LspStoreEvent::LanguageServerAdded(
10094 server_id,
10095 language_server.name(),
10096 Some(key.0),
10097 ));
10098 cx.emit(LspStoreEvent::RefreshInlayHints);
10099
10100 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
10101 downstream_client
10102 .send(proto::StartLanguageServer {
10103 project_id: *project_id,
10104 server: Some(proto::LanguageServer {
10105 id: server_id.0 as u64,
10106 name: language_server.name().to_string(),
10107 worktree_id: Some(key.0.to_proto()),
10108 }),
10109 })
10110 .log_err();
10111 }
10112
10113 // Tell the language server about every open buffer in the worktree that matches the language.
10114 let mut buffer_paths_registered = Vec::new();
10115 self.buffer_store.clone().update(cx, |buffer_store, cx| {
10116 for buffer_handle in buffer_store.buffers() {
10117 let buffer = buffer_handle.read(cx);
10118 let file = match File::from_dyn(buffer.file()) {
10119 Some(file) => file,
10120 None => continue,
10121 };
10122 let language = match buffer.language() {
10123 Some(language) => language,
10124 None => continue,
10125 };
10126
10127 if file.worktree.read(cx).id() != key.0
10128 || !self
10129 .languages
10130 .lsp_adapters(&language.name())
10131 .iter()
10132 .any(|a| a.name == key.1)
10133 {
10134 continue;
10135 }
10136 // didOpen
10137 let file = match file.as_local() {
10138 Some(file) => file,
10139 None => continue,
10140 };
10141
10142 let local = self.as_local_mut().unwrap();
10143
10144 if local.registered_buffers.contains_key(&buffer.remote_id()) {
10145 let versions = local
10146 .buffer_snapshots
10147 .entry(buffer.remote_id())
10148 .or_default()
10149 .entry(server_id)
10150 .and_modify(|_| {
10151 assert!(
10152 false,
10153 "There should not be an existing snapshot for a newly inserted buffer"
10154 )
10155 })
10156 .or_insert_with(|| {
10157 vec![LspBufferSnapshot {
10158 version: 0,
10159 snapshot: buffer.text_snapshot(),
10160 }]
10161 });
10162
10163 let snapshot = versions.last().unwrap();
10164 let version = snapshot.version;
10165 let initial_snapshot = &snapshot.snapshot;
10166 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
10167 language_server.register_buffer(
10168 uri,
10169 adapter.language_id(&language.name()),
10170 version,
10171 initial_snapshot.text(),
10172 );
10173 buffer_paths_registered.push(file.abs_path(cx));
10174 local
10175 .buffers_opened_in_servers
10176 .entry(buffer.remote_id())
10177 .or_default()
10178 .insert(server_id);
10179 }
10180 buffer_handle.update(cx, |buffer, cx| {
10181 buffer.set_completion_triggers(
10182 server_id,
10183 language_server
10184 .capabilities()
10185 .completion_provider
10186 .as_ref()
10187 .and_then(|provider| {
10188 provider
10189 .trigger_characters
10190 .as_ref()
10191 .map(|characters| characters.iter().cloned().collect())
10192 })
10193 .unwrap_or_default(),
10194 cx,
10195 )
10196 });
10197 }
10198 });
10199
10200 for abs_path in buffer_paths_registered {
10201 cx.emit(LspStoreEvent::LanguageServerUpdate {
10202 language_server_id: server_id,
10203 name: Some(adapter.name()),
10204 message: proto::update_language_server::Variant::RegisteredForBuffer(
10205 proto::RegisteredForBuffer {
10206 buffer_abs_path: abs_path.to_string_lossy().to_string(),
10207 },
10208 ),
10209 });
10210 }
10211
10212 cx.notify();
10213 }
10214
10215 pub fn language_servers_running_disk_based_diagnostics(
10216 &self,
10217 ) -> impl Iterator<Item = LanguageServerId> + '_ {
10218 self.language_server_statuses
10219 .iter()
10220 .filter_map(|(id, status)| {
10221 if status.has_pending_diagnostic_updates {
10222 Some(*id)
10223 } else {
10224 None
10225 }
10226 })
10227 }
10228
10229 pub(crate) fn cancel_language_server_work_for_buffers(
10230 &mut self,
10231 buffers: impl IntoIterator<Item = Entity<Buffer>>,
10232 cx: &mut Context<Self>,
10233 ) {
10234 if let Some((client, project_id)) = self.upstream_client() {
10235 let request = client.request(proto::CancelLanguageServerWork {
10236 project_id,
10237 work: Some(proto::cancel_language_server_work::Work::Buffers(
10238 proto::cancel_language_server_work::Buffers {
10239 buffer_ids: buffers
10240 .into_iter()
10241 .map(|b| b.read(cx).remote_id().to_proto())
10242 .collect(),
10243 },
10244 )),
10245 });
10246 cx.background_spawn(request).detach_and_log_err(cx);
10247 } else if let Some(local) = self.as_local() {
10248 let servers = buffers
10249 .into_iter()
10250 .flat_map(|buffer| {
10251 buffer.update(cx, |buffer, cx| {
10252 local.language_server_ids_for_buffer(buffer, cx).into_iter()
10253 })
10254 })
10255 .collect::<HashSet<_>>();
10256 for server_id in servers {
10257 self.cancel_language_server_work(server_id, None, cx);
10258 }
10259 }
10260 }
10261
10262 pub(crate) fn cancel_language_server_work(
10263 &mut self,
10264 server_id: LanguageServerId,
10265 token_to_cancel: Option<String>,
10266 cx: &mut Context<Self>,
10267 ) {
10268 if let Some(local) = self.as_local() {
10269 let status = self.language_server_statuses.get(&server_id);
10270 let server = local.language_servers.get(&server_id);
10271 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
10272 {
10273 for (token, progress) in &status.pending_work {
10274 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
10275 if token != token_to_cancel {
10276 continue;
10277 }
10278 }
10279 if progress.is_cancellable {
10280 server
10281 .notify::<lsp::notification::WorkDoneProgressCancel>(
10282 &WorkDoneProgressCancelParams {
10283 token: lsp::NumberOrString::String(token.clone()),
10284 },
10285 )
10286 .ok();
10287 }
10288 }
10289 }
10290 } else if let Some((client, project_id)) = self.upstream_client() {
10291 let request = client.request(proto::CancelLanguageServerWork {
10292 project_id,
10293 work: Some(
10294 proto::cancel_language_server_work::Work::LanguageServerWork(
10295 proto::cancel_language_server_work::LanguageServerWork {
10296 language_server_id: server_id.to_proto(),
10297 token: token_to_cancel,
10298 },
10299 ),
10300 ),
10301 });
10302 cx.background_spawn(request).detach_and_log_err(cx);
10303 }
10304 }
10305
10306 fn register_supplementary_language_server(
10307 &mut self,
10308 id: LanguageServerId,
10309 name: LanguageServerName,
10310 server: Arc<LanguageServer>,
10311 cx: &mut Context<Self>,
10312 ) {
10313 if let Some(local) = self.as_local_mut() {
10314 local
10315 .supplementary_language_servers
10316 .insert(id, (name.clone(), server));
10317 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
10318 }
10319 }
10320
10321 fn unregister_supplementary_language_server(
10322 &mut self,
10323 id: LanguageServerId,
10324 cx: &mut Context<Self>,
10325 ) {
10326 if let Some(local) = self.as_local_mut() {
10327 local.supplementary_language_servers.remove(&id);
10328 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
10329 }
10330 }
10331
10332 pub(crate) fn supplementary_language_servers(
10333 &self,
10334 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
10335 self.as_local().into_iter().flat_map(|local| {
10336 local
10337 .supplementary_language_servers
10338 .iter()
10339 .map(|(id, (name, _))| (*id, name.clone()))
10340 })
10341 }
10342
10343 pub fn language_server_adapter_for_id(
10344 &self,
10345 id: LanguageServerId,
10346 ) -> Option<Arc<CachedLspAdapter>> {
10347 self.as_local()
10348 .and_then(|local| local.language_servers.get(&id))
10349 .and_then(|language_server_state| match language_server_state {
10350 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
10351 _ => None,
10352 })
10353 }
10354
10355 pub(super) fn update_local_worktree_language_servers(
10356 &mut self,
10357 worktree_handle: &Entity<Worktree>,
10358 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
10359 cx: &mut Context<Self>,
10360 ) {
10361 if changes.is_empty() {
10362 return;
10363 }
10364
10365 let Some(local) = self.as_local() else { return };
10366
10367 local.prettier_store.update(cx, |prettier_store, cx| {
10368 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
10369 });
10370
10371 let worktree_id = worktree_handle.read(cx).id();
10372 let mut language_server_ids = local
10373 .language_server_ids
10374 .iter()
10375 .flat_map(|((server_worktree, _), server_ids)| {
10376 server_ids
10377 .iter()
10378 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
10379 })
10380 .collect::<Vec<_>>();
10381 language_server_ids.sort();
10382 language_server_ids.dedup();
10383
10384 let abs_path = worktree_handle.read(cx).abs_path();
10385 for server_id in &language_server_ids {
10386 if let Some(LanguageServerState::Running { server, .. }) =
10387 local.language_servers.get(server_id)
10388 {
10389 if let Some(watched_paths) = local
10390 .language_server_watched_paths
10391 .get(server_id)
10392 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
10393 {
10394 let params = lsp::DidChangeWatchedFilesParams {
10395 changes: changes
10396 .iter()
10397 .filter_map(|(path, _, change)| {
10398 if !watched_paths.is_match(path) {
10399 return None;
10400 }
10401 let typ = match change {
10402 PathChange::Loaded => return None,
10403 PathChange::Added => lsp::FileChangeType::CREATED,
10404 PathChange::Removed => lsp::FileChangeType::DELETED,
10405 PathChange::Updated => lsp::FileChangeType::CHANGED,
10406 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
10407 };
10408 Some(lsp::FileEvent {
10409 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
10410 typ,
10411 })
10412 })
10413 .collect(),
10414 };
10415 if !params.changes.is_empty() {
10416 server
10417 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
10418 .ok();
10419 }
10420 }
10421 }
10422 }
10423 }
10424
10425 pub fn wait_for_remote_buffer(
10426 &mut self,
10427 id: BufferId,
10428 cx: &mut Context<Self>,
10429 ) -> Task<Result<Entity<Buffer>>> {
10430 self.buffer_store.update(cx, |buffer_store, cx| {
10431 buffer_store.wait_for_remote_buffer(id, cx)
10432 })
10433 }
10434
10435 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10436 proto::Symbol {
10437 language_server_name: symbol.language_server_name.0.to_string(),
10438 source_worktree_id: symbol.source_worktree_id.to_proto(),
10439 language_server_id: symbol.source_language_server_id.to_proto(),
10440 worktree_id: symbol.path.worktree_id.to_proto(),
10441 path: symbol.path.path.as_ref().to_proto(),
10442 name: symbol.name.clone(),
10443 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
10444 start: Some(proto::PointUtf16 {
10445 row: symbol.range.start.0.row,
10446 column: symbol.range.start.0.column,
10447 }),
10448 end: Some(proto::PointUtf16 {
10449 row: symbol.range.end.0.row,
10450 column: symbol.range.end.0.column,
10451 }),
10452 signature: symbol.signature.to_vec(),
10453 }
10454 }
10455
10456 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
10457 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
10458 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
10459 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
10460 let path = ProjectPath {
10461 worktree_id,
10462 path: Arc::<Path>::from_proto(serialized_symbol.path),
10463 };
10464
10465 let start = serialized_symbol.start.context("invalid start")?;
10466 let end = serialized_symbol.end.context("invalid end")?;
10467 Ok(CoreSymbol {
10468 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
10469 source_worktree_id,
10470 source_language_server_id: LanguageServerId::from_proto(
10471 serialized_symbol.language_server_id,
10472 ),
10473 path,
10474 name: serialized_symbol.name,
10475 range: Unclipped(PointUtf16::new(start.row, start.column))
10476 ..Unclipped(PointUtf16::new(end.row, end.column)),
10477 kind,
10478 signature: serialized_symbol
10479 .signature
10480 .try_into()
10481 .map_err(|_| anyhow!("invalid signature"))?,
10482 })
10483 }
10484
10485 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10486 let mut serialized_completion = proto::Completion {
10487 old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
10488 old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
10489 new_text: completion.new_text.clone(),
10490 ..proto::Completion::default()
10491 };
10492 match &completion.source {
10493 CompletionSource::Lsp {
10494 insert_range,
10495 server_id,
10496 lsp_completion,
10497 lsp_defaults,
10498 resolved,
10499 } => {
10500 let (old_insert_start, old_insert_end) = insert_range
10501 .as_ref()
10502 .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
10503 .unzip();
10504
10505 serialized_completion.old_insert_start = old_insert_start;
10506 serialized_completion.old_insert_end = old_insert_end;
10507 serialized_completion.source = proto::completion::Source::Lsp as i32;
10508 serialized_completion.server_id = server_id.0 as u64;
10509 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
10510 serialized_completion.lsp_defaults = lsp_defaults
10511 .as_deref()
10512 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
10513 serialized_completion.resolved = *resolved;
10514 }
10515 CompletionSource::BufferWord {
10516 word_range,
10517 resolved,
10518 } => {
10519 serialized_completion.source = proto::completion::Source::BufferWord as i32;
10520 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
10521 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
10522 serialized_completion.resolved = *resolved;
10523 }
10524 CompletionSource::Custom => {
10525 serialized_completion.source = proto::completion::Source::Custom as i32;
10526 serialized_completion.resolved = true;
10527 }
10528 }
10529
10530 serialized_completion
10531 }
10532
10533 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10534 let old_replace_start = completion
10535 .old_replace_start
10536 .and_then(deserialize_anchor)
10537 .context("invalid old start")?;
10538 let old_replace_end = completion
10539 .old_replace_end
10540 .and_then(deserialize_anchor)
10541 .context("invalid old end")?;
10542 let insert_range = {
10543 match completion.old_insert_start.zip(completion.old_insert_end) {
10544 Some((start, end)) => {
10545 let start = deserialize_anchor(start).context("invalid insert old start")?;
10546 let end = deserialize_anchor(end).context("invalid insert old end")?;
10547 Some(start..end)
10548 }
10549 None => None,
10550 }
10551 };
10552 Ok(CoreCompletion {
10553 replace_range: old_replace_start..old_replace_end,
10554 new_text: completion.new_text,
10555 source: match proto::completion::Source::from_i32(completion.source) {
10556 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
10557 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
10558 insert_range,
10559 server_id: LanguageServerId::from_proto(completion.server_id),
10560 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
10561 lsp_defaults: completion
10562 .lsp_defaults
10563 .as_deref()
10564 .map(serde_json::from_slice)
10565 .transpose()?,
10566 resolved: completion.resolved,
10567 },
10568 Some(proto::completion::Source::BufferWord) => {
10569 let word_range = completion
10570 .buffer_word_start
10571 .and_then(deserialize_anchor)
10572 .context("invalid buffer word start")?
10573 ..completion
10574 .buffer_word_end
10575 .and_then(deserialize_anchor)
10576 .context("invalid buffer word end")?;
10577 CompletionSource::BufferWord {
10578 word_range,
10579 resolved: completion.resolved,
10580 }
10581 }
10582 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
10583 },
10584 })
10585 }
10586
10587 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10588 let (kind, lsp_action) = match &action.lsp_action {
10589 LspAction::Action(code_action) => (
10590 proto::code_action::Kind::Action as i32,
10591 serde_json::to_vec(code_action).unwrap(),
10592 ),
10593 LspAction::Command(command) => (
10594 proto::code_action::Kind::Command as i32,
10595 serde_json::to_vec(command).unwrap(),
10596 ),
10597 LspAction::CodeLens(code_lens) => (
10598 proto::code_action::Kind::CodeLens as i32,
10599 serde_json::to_vec(code_lens).unwrap(),
10600 ),
10601 };
10602
10603 proto::CodeAction {
10604 server_id: action.server_id.0 as u64,
10605 start: Some(serialize_anchor(&action.range.start)),
10606 end: Some(serialize_anchor(&action.range.end)),
10607 lsp_action,
10608 kind,
10609 resolved: action.resolved,
10610 }
10611 }
10612
10613 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10614 let start = action
10615 .start
10616 .and_then(deserialize_anchor)
10617 .context("invalid start")?;
10618 let end = action
10619 .end
10620 .and_then(deserialize_anchor)
10621 .context("invalid end")?;
10622 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
10623 Some(proto::code_action::Kind::Action) => {
10624 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
10625 }
10626 Some(proto::code_action::Kind::Command) => {
10627 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
10628 }
10629 Some(proto::code_action::Kind::CodeLens) => {
10630 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
10631 }
10632 None => anyhow::bail!("Unknown action kind {}", action.kind),
10633 };
10634 Ok(CodeAction {
10635 server_id: LanguageServerId(action.server_id as usize),
10636 range: start..end,
10637 resolved: action.resolved,
10638 lsp_action,
10639 })
10640 }
10641
10642 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
10643 match &formatting_result {
10644 Ok(_) => self.last_formatting_failure = None,
10645 Err(error) => {
10646 let error_string = format!("{error:#}");
10647 log::error!("Formatting failed: {error_string}");
10648 self.last_formatting_failure
10649 .replace(error_string.lines().join(" "));
10650 }
10651 }
10652 }
10653
10654 fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
10655 for buffer_lsp_data in self.lsp_data.values_mut() {
10656 buffer_lsp_data.colors.remove(&for_server);
10657 buffer_lsp_data.cache_version += 1;
10658 }
10659 if let Some(local) = self.as_local_mut() {
10660 local.buffer_pull_diagnostics_result_ids.remove(&for_server);
10661 for buffer_servers in local.buffers_opened_in_servers.values_mut() {
10662 buffer_servers.remove(&for_server);
10663 }
10664 }
10665 }
10666
10667 pub fn result_id(
10668 &self,
10669 server_id: LanguageServerId,
10670 buffer_id: BufferId,
10671 cx: &App,
10672 ) -> Option<String> {
10673 let abs_path = self
10674 .buffer_store
10675 .read(cx)
10676 .get(buffer_id)
10677 .and_then(|b| File::from_dyn(b.read(cx).file()))
10678 .map(|f| f.abs_path(cx))?;
10679 self.as_local()?
10680 .buffer_pull_diagnostics_result_ids
10681 .get(&server_id)?
10682 .get(&abs_path)?
10683 .clone()
10684 }
10685
10686 pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
10687 let Some(local) = self.as_local() else {
10688 return HashMap::default();
10689 };
10690 local
10691 .buffer_pull_diagnostics_result_ids
10692 .get(&server_id)
10693 .into_iter()
10694 .flatten()
10695 .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
10696 .collect()
10697 }
10698
10699 pub fn pull_workspace_diagnostics(&mut self, server_id: LanguageServerId) {
10700 if let Some(LanguageServerState::Running {
10701 workspace_refresh_task: Some((tx, _)),
10702 ..
10703 }) = self
10704 .as_local_mut()
10705 .and_then(|local| local.language_servers.get_mut(&server_id))
10706 {
10707 tx.try_send(()).ok();
10708 }
10709 }
10710
10711 pub fn pull_workspace_diagnostics_for_buffer(&mut self, buffer_id: BufferId, cx: &mut App) {
10712 let Some(buffer) = self.buffer_store().read(cx).get_existing(buffer_id).ok() else {
10713 return;
10714 };
10715 let Some(local) = self.as_local_mut() else {
10716 return;
10717 };
10718
10719 for server_id in buffer.update(cx, |buffer, cx| {
10720 local.language_server_ids_for_buffer(buffer, cx)
10721 }) {
10722 if let Some(LanguageServerState::Running {
10723 workspace_refresh_task: Some((tx, _)),
10724 ..
10725 }) = local.language_servers.get_mut(&server_id)
10726 {
10727 tx.try_send(()).ok();
10728 }
10729 }
10730 }
10731}
10732
10733fn subscribe_to_binary_statuses(
10734 languages: &Arc<LanguageRegistry>,
10735 cx: &mut Context<'_, LspStore>,
10736) -> Task<()> {
10737 let mut server_statuses = languages.language_server_binary_statuses();
10738 cx.spawn(async move |lsp_store, cx| {
10739 while let Some((server_name, binary_status)) = server_statuses.next().await {
10740 if lsp_store
10741 .update(cx, |_, cx| {
10742 let mut message = None;
10743 let binary_status = match binary_status {
10744 BinaryStatus::None => proto::ServerBinaryStatus::None,
10745 BinaryStatus::CheckingForUpdate => {
10746 proto::ServerBinaryStatus::CheckingForUpdate
10747 }
10748 BinaryStatus::Downloading => proto::ServerBinaryStatus::Downloading,
10749 BinaryStatus::Starting => proto::ServerBinaryStatus::Starting,
10750 BinaryStatus::Stopping => proto::ServerBinaryStatus::Stopping,
10751 BinaryStatus::Stopped => proto::ServerBinaryStatus::Stopped,
10752 BinaryStatus::Failed { error } => {
10753 message = Some(error);
10754 proto::ServerBinaryStatus::Failed
10755 }
10756 };
10757 cx.emit(LspStoreEvent::LanguageServerUpdate {
10758 // Binary updates are about the binary that might not have any language server id at that point.
10759 // Reuse `LanguageServerUpdate` for them and provide a fake id that won't be used on the receiver side.
10760 language_server_id: LanguageServerId(0),
10761 name: Some(server_name),
10762 message: proto::update_language_server::Variant::StatusUpdate(
10763 proto::StatusUpdate {
10764 message,
10765 status: Some(proto::status_update::Status::Binary(
10766 binary_status as i32,
10767 )),
10768 },
10769 ),
10770 });
10771 })
10772 .is_err()
10773 {
10774 break;
10775 }
10776 }
10777 })
10778}
10779
10780fn lsp_workspace_diagnostics_refresh(
10781 server: Arc<LanguageServer>,
10782 cx: &mut Context<'_, LspStore>,
10783) -> Option<(mpsc::Sender<()>, Task<()>)> {
10784 let identifier = match server.capabilities().diagnostic_provider? {
10785 lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {
10786 if !diagnostic_options.workspace_diagnostics {
10787 return None;
10788 }
10789 diagnostic_options.identifier
10790 }
10791 lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {
10792 let diagnostic_options = registration_options.diagnostic_options;
10793 if !diagnostic_options.workspace_diagnostics {
10794 return None;
10795 }
10796 diagnostic_options.identifier
10797 }
10798 };
10799
10800 let (mut tx, mut rx) = mpsc::channel(1);
10801 tx.try_send(()).ok();
10802
10803 let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {
10804 let mut attempts = 0;
10805 let max_attempts = 50;
10806
10807 loop {
10808 let Some(()) = rx.recv().await else {
10809 return;
10810 };
10811
10812 'request: loop {
10813 if attempts > max_attempts {
10814 log::error!(
10815 "Failed to pull workspace diagnostics {max_attempts} times, aborting"
10816 );
10817 return;
10818 }
10819 let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);
10820 cx.background_executor()
10821 .timer(Duration::from_millis(backoff_millis))
10822 .await;
10823 attempts += 1;
10824
10825 let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
10826 lsp_store
10827 .all_result_ids(server.server_id())
10828 .into_iter()
10829 .filter_map(|(abs_path, result_id)| {
10830 let uri = file_path_to_lsp_url(&abs_path).ok()?;
10831 Some(lsp::PreviousResultId {
10832 uri,
10833 value: result_id,
10834 })
10835 })
10836 .collect()
10837 }) else {
10838 return;
10839 };
10840
10841 let response_result = server
10842 .request::<lsp::WorkspaceDiagnosticRequest>(lsp::WorkspaceDiagnosticParams {
10843 previous_result_ids,
10844 identifier: identifier.clone(),
10845 work_done_progress_params: Default::default(),
10846 partial_result_params: Default::default(),
10847 })
10848 .await;
10849 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh
10850 // > If a server closes a workspace diagnostic pull request the client should re-trigger the request.
10851 match response_result {
10852 ConnectionResult::Timeout => {
10853 log::error!("Timeout during workspace diagnostics pull");
10854 continue 'request;
10855 }
10856 ConnectionResult::ConnectionReset => {
10857 log::error!("Server closed a workspace diagnostics pull request");
10858 continue 'request;
10859 }
10860 ConnectionResult::Result(Err(e)) => {
10861 log::error!("Error during workspace diagnostics pull: {e:#}");
10862 break 'request;
10863 }
10864 ConnectionResult::Result(Ok(pulled_diagnostics)) => {
10865 attempts = 0;
10866 if lsp_store
10867 .update(cx, |lsp_store, cx| {
10868 let workspace_diagnostics =
10869 GetDocumentDiagnostics::deserialize_workspace_diagnostics_report(pulled_diagnostics, server.server_id());
10870 for workspace_diagnostics in workspace_diagnostics {
10871 let LspPullDiagnostics::Response {
10872 server_id,
10873 uri,
10874 diagnostics,
10875 } = workspace_diagnostics.diagnostics
10876 else {
10877 continue;
10878 };
10879
10880 let adapter = lsp_store.language_server_adapter_for_id(server_id);
10881 let disk_based_sources = adapter
10882 .as_ref()
10883 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
10884 .unwrap_or(&[]);
10885
10886 match diagnostics {
10887 PulledDiagnostics::Unchanged { result_id } => {
10888 lsp_store
10889 .merge_diagnostics(
10890 server_id,
10891 lsp::PublishDiagnosticsParams {
10892 uri: uri.clone(),
10893 diagnostics: Vec::new(),
10894 version: None,
10895 },
10896 Some(result_id),
10897 DiagnosticSourceKind::Pulled,
10898 disk_based_sources,
10899 |_, _, _| true,
10900 cx,
10901 )
10902 .log_err();
10903 }
10904 PulledDiagnostics::Changed {
10905 diagnostics,
10906 result_id,
10907 } => {
10908 lsp_store
10909 .merge_diagnostics(
10910 server_id,
10911 lsp::PublishDiagnosticsParams {
10912 uri: uri.clone(),
10913 diagnostics,
10914 version: workspace_diagnostics.version,
10915 },
10916 result_id,
10917 DiagnosticSourceKind::Pulled,
10918 disk_based_sources,
10919 |buffer, old_diagnostic, cx| match old_diagnostic.source_kind {
10920 DiagnosticSourceKind::Pulled => {
10921 let buffer_url = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx))
10922 .and_then(|abs_path| file_path_to_lsp_url(&abs_path).ok());
10923 buffer_url.is_none_or(|buffer_url| buffer_url != uri)
10924 },
10925 DiagnosticSourceKind::Other
10926 | DiagnosticSourceKind::Pushed => true,
10927 },
10928 cx,
10929 )
10930 .log_err();
10931 }
10932 }
10933 }
10934 })
10935 .is_err()
10936 {
10937 return;
10938 }
10939 break 'request;
10940 }
10941 }
10942 }
10943 }
10944 });
10945
10946 Some((tx, workspace_query_language_server))
10947}
10948
10949fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
10950 let CompletionSource::BufferWord {
10951 word_range,
10952 resolved,
10953 } = &mut completion.source
10954 else {
10955 return;
10956 };
10957 if *resolved {
10958 return;
10959 }
10960
10961 if completion.new_text
10962 != snapshot
10963 .text_for_range(word_range.clone())
10964 .collect::<String>()
10965 {
10966 return;
10967 }
10968
10969 let mut offset = 0;
10970 for chunk in snapshot.chunks(word_range.clone(), true) {
10971 let end_offset = offset + chunk.text.len();
10972 if let Some(highlight_id) = chunk.syntax_highlight_id {
10973 completion
10974 .label
10975 .runs
10976 .push((offset..end_offset, highlight_id));
10977 }
10978 offset = end_offset;
10979 }
10980 *resolved = true;
10981}
10982
10983impl EventEmitter<LspStoreEvent> for LspStore {}
10984
10985fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10986 hover
10987 .contents
10988 .retain(|hover_block| !hover_block.text.trim().is_empty());
10989 if hover.contents.is_empty() {
10990 None
10991 } else {
10992 Some(hover)
10993 }
10994}
10995
10996async fn populate_labels_for_completions(
10997 new_completions: Vec<CoreCompletion>,
10998 language: Option<Arc<Language>>,
10999 lsp_adapter: Option<Arc<CachedLspAdapter>>,
11000) -> Vec<Completion> {
11001 let lsp_completions = new_completions
11002 .iter()
11003 .filter_map(|new_completion| {
11004 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
11005 Some(lsp_completion.into_owned())
11006 } else {
11007 None
11008 }
11009 })
11010 .collect::<Vec<_>>();
11011
11012 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
11013 lsp_adapter
11014 .labels_for_completions(&lsp_completions, language)
11015 .await
11016 .log_err()
11017 .unwrap_or_default()
11018 } else {
11019 Vec::new()
11020 }
11021 .into_iter()
11022 .fuse();
11023
11024 let mut completions = Vec::new();
11025 for completion in new_completions {
11026 match completion.source.lsp_completion(true) {
11027 Some(lsp_completion) => {
11028 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
11029 Some(docs.into())
11030 } else {
11031 None
11032 };
11033
11034 let mut label = labels.next().flatten().unwrap_or_else(|| {
11035 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
11036 });
11037 ensure_uniform_list_compatible_label(&mut label);
11038 completions.push(Completion {
11039 label,
11040 documentation,
11041 replace_range: completion.replace_range,
11042 new_text: completion.new_text,
11043 insert_text_mode: lsp_completion.insert_text_mode,
11044 source: completion.source,
11045 icon_path: None,
11046 confirm: None,
11047 });
11048 }
11049 None => {
11050 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
11051 ensure_uniform_list_compatible_label(&mut label);
11052 completions.push(Completion {
11053 label,
11054 documentation: None,
11055 replace_range: completion.replace_range,
11056 new_text: completion.new_text,
11057 source: completion.source,
11058 insert_text_mode: None,
11059 icon_path: None,
11060 confirm: None,
11061 });
11062 }
11063 }
11064 }
11065 completions
11066}
11067
11068#[derive(Debug)]
11069pub enum LanguageServerToQuery {
11070 /// Query language servers in order of users preference, up until one capable of handling the request is found.
11071 FirstCapable,
11072 /// Query a specific language server.
11073 Other(LanguageServerId),
11074}
11075
11076#[derive(Default)]
11077struct RenamePathsWatchedForServer {
11078 did_rename: Vec<RenameActionPredicate>,
11079 will_rename: Vec<RenameActionPredicate>,
11080}
11081
11082impl RenamePathsWatchedForServer {
11083 fn with_did_rename_patterns(
11084 mut self,
11085 did_rename: Option<&FileOperationRegistrationOptions>,
11086 ) -> Self {
11087 if let Some(did_rename) = did_rename {
11088 self.did_rename = did_rename
11089 .filters
11090 .iter()
11091 .filter_map(|filter| filter.try_into().log_err())
11092 .collect();
11093 }
11094 self
11095 }
11096 fn with_will_rename_patterns(
11097 mut self,
11098 will_rename: Option<&FileOperationRegistrationOptions>,
11099 ) -> Self {
11100 if let Some(will_rename) = will_rename {
11101 self.will_rename = will_rename
11102 .filters
11103 .iter()
11104 .filter_map(|filter| filter.try_into().log_err())
11105 .collect();
11106 }
11107 self
11108 }
11109
11110 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
11111 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
11112 }
11113 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
11114 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
11115 }
11116}
11117
11118impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
11119 type Error = globset::Error;
11120 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
11121 Ok(Self {
11122 kind: ops.pattern.matches.clone(),
11123 glob: GlobBuilder::new(&ops.pattern.glob)
11124 .case_insensitive(
11125 ops.pattern
11126 .options
11127 .as_ref()
11128 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
11129 )
11130 .build()?
11131 .compile_matcher(),
11132 })
11133 }
11134}
11135struct RenameActionPredicate {
11136 glob: GlobMatcher,
11137 kind: Option<FileOperationPatternKind>,
11138}
11139
11140impl RenameActionPredicate {
11141 // Returns true if language server should be notified
11142 fn eval(&self, path: &str, is_dir: bool) -> bool {
11143 self.kind.as_ref().map_or(true, |kind| {
11144 let expected_kind = if is_dir {
11145 FileOperationPatternKind::Folder
11146 } else {
11147 FileOperationPatternKind::File
11148 };
11149 kind == &expected_kind
11150 }) && self.glob.is_match(path)
11151 }
11152}
11153
11154#[derive(Default)]
11155struct LanguageServerWatchedPaths {
11156 worktree_paths: HashMap<WorktreeId, GlobSet>,
11157 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
11158}
11159
11160#[derive(Default)]
11161struct LanguageServerWatchedPathsBuilder {
11162 worktree_paths: HashMap<WorktreeId, GlobSet>,
11163 abs_paths: HashMap<Arc<Path>, GlobSet>,
11164}
11165
11166impl LanguageServerWatchedPathsBuilder {
11167 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
11168 self.worktree_paths.insert(worktree_id, glob_set);
11169 }
11170 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
11171 self.abs_paths.insert(path, glob_set);
11172 }
11173 fn build(
11174 self,
11175 fs: Arc<dyn Fs>,
11176 language_server_id: LanguageServerId,
11177 cx: &mut Context<LspStore>,
11178 ) -> LanguageServerWatchedPaths {
11179 let project = cx.weak_entity();
11180
11181 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
11182 let abs_paths = self
11183 .abs_paths
11184 .into_iter()
11185 .map(|(abs_path, globset)| {
11186 let task = cx.spawn({
11187 let abs_path = abs_path.clone();
11188 let fs = fs.clone();
11189
11190 let lsp_store = project.clone();
11191 async move |_, cx| {
11192 maybe!(async move {
11193 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
11194 while let Some(update) = push_updates.0.next().await {
11195 let action = lsp_store
11196 .update(cx, |this, _| {
11197 let Some(local) = this.as_local() else {
11198 return ControlFlow::Break(());
11199 };
11200 let Some(watcher) = local
11201 .language_server_watched_paths
11202 .get(&language_server_id)
11203 else {
11204 return ControlFlow::Break(());
11205 };
11206 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
11207 "Watched abs path is not registered with a watcher",
11208 );
11209 let matching_entries = update
11210 .into_iter()
11211 .filter(|event| globs.is_match(&event.path))
11212 .collect::<Vec<_>>();
11213 this.lsp_notify_abs_paths_changed(
11214 language_server_id,
11215 matching_entries,
11216 );
11217 ControlFlow::Continue(())
11218 })
11219 .ok()?;
11220
11221 if action.is_break() {
11222 break;
11223 }
11224 }
11225 Some(())
11226 })
11227 .await;
11228 }
11229 });
11230 (abs_path, (globset, task))
11231 })
11232 .collect();
11233 LanguageServerWatchedPaths {
11234 worktree_paths: self.worktree_paths,
11235 abs_paths,
11236 }
11237 }
11238}
11239
11240struct LspBufferSnapshot {
11241 version: i32,
11242 snapshot: TextBufferSnapshot,
11243}
11244
11245/// A prompt requested by LSP server.
11246#[derive(Clone, Debug)]
11247pub struct LanguageServerPromptRequest {
11248 pub level: PromptLevel,
11249 pub message: String,
11250 pub actions: Vec<MessageActionItem>,
11251 pub lsp_name: String,
11252 pub(crate) response_channel: Sender<MessageActionItem>,
11253}
11254
11255impl LanguageServerPromptRequest {
11256 pub async fn respond(self, index: usize) -> Option<()> {
11257 if let Some(response) = self.actions.into_iter().nth(index) {
11258 self.response_channel.send(response).await.ok()
11259 } else {
11260 None
11261 }
11262 }
11263}
11264impl PartialEq for LanguageServerPromptRequest {
11265 fn eq(&self, other: &Self) -> bool {
11266 self.message == other.message && self.actions == other.actions
11267 }
11268}
11269
11270#[derive(Clone, Debug, PartialEq)]
11271pub enum LanguageServerLogType {
11272 Log(MessageType),
11273 Trace(Option<String>),
11274}
11275
11276impl LanguageServerLogType {
11277 pub fn to_proto(&self) -> proto::language_server_log::LogType {
11278 match self {
11279 Self::Log(log_type) => {
11280 let message_type = match *log_type {
11281 MessageType::ERROR => 1,
11282 MessageType::WARNING => 2,
11283 MessageType::INFO => 3,
11284 MessageType::LOG => 4,
11285 other => {
11286 log::warn!("Unknown lsp log message type: {:?}", other);
11287 4
11288 }
11289 };
11290 proto::language_server_log::LogType::LogMessageType(message_type)
11291 }
11292 Self::Trace(message) => {
11293 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
11294 message: message.clone(),
11295 })
11296 }
11297 }
11298 }
11299
11300 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
11301 match log_type {
11302 proto::language_server_log::LogType::LogMessageType(message_type) => {
11303 Self::Log(match message_type {
11304 1 => MessageType::ERROR,
11305 2 => MessageType::WARNING,
11306 3 => MessageType::INFO,
11307 4 => MessageType::LOG,
11308 _ => MessageType::LOG,
11309 })
11310 }
11311 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
11312 }
11313 }
11314}
11315
11316pub enum LanguageServerState {
11317 Starting {
11318 startup: Task<Option<Arc<LanguageServer>>>,
11319 /// List of language servers that will be added to the workspace once it's initialization completes.
11320 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
11321 },
11322
11323 Running {
11324 adapter: Arc<CachedLspAdapter>,
11325 server: Arc<LanguageServer>,
11326 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
11327 workspace_refresh_task: Option<(mpsc::Sender<()>, Task<()>)>,
11328 },
11329}
11330
11331impl LanguageServerState {
11332 fn add_workspace_folder(&self, uri: Url) {
11333 match self {
11334 LanguageServerState::Starting {
11335 pending_workspace_folders,
11336 ..
11337 } => {
11338 pending_workspace_folders.lock().insert(uri);
11339 }
11340 LanguageServerState::Running { server, .. } => {
11341 server.add_workspace_folder(uri);
11342 }
11343 }
11344 }
11345 fn _remove_workspace_folder(&self, uri: Url) {
11346 match self {
11347 LanguageServerState::Starting {
11348 pending_workspace_folders,
11349 ..
11350 } => {
11351 pending_workspace_folders.lock().remove(&uri);
11352 }
11353 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
11354 }
11355 }
11356}
11357
11358impl std::fmt::Debug for LanguageServerState {
11359 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11360 match self {
11361 LanguageServerState::Starting { .. } => {
11362 f.debug_struct("LanguageServerState::Starting").finish()
11363 }
11364 LanguageServerState::Running { .. } => {
11365 f.debug_struct("LanguageServerState::Running").finish()
11366 }
11367 }
11368 }
11369}
11370
11371#[derive(Clone, Debug, Serialize)]
11372pub struct LanguageServerProgress {
11373 pub is_disk_based_diagnostics_progress: bool,
11374 pub is_cancellable: bool,
11375 pub title: Option<String>,
11376 pub message: Option<String>,
11377 pub percentage: Option<usize>,
11378 #[serde(skip_serializing)]
11379 pub last_update_at: Instant,
11380}
11381
11382#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
11383pub struct DiagnosticSummary {
11384 pub error_count: usize,
11385 pub warning_count: usize,
11386}
11387
11388impl DiagnosticSummary {
11389 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
11390 let mut this = Self {
11391 error_count: 0,
11392 warning_count: 0,
11393 };
11394
11395 for entry in diagnostics {
11396 if entry.diagnostic.is_primary {
11397 match entry.diagnostic.severity {
11398 DiagnosticSeverity::ERROR => this.error_count += 1,
11399 DiagnosticSeverity::WARNING => this.warning_count += 1,
11400 _ => {}
11401 }
11402 }
11403 }
11404
11405 this
11406 }
11407
11408 pub fn is_empty(&self) -> bool {
11409 self.error_count == 0 && self.warning_count == 0
11410 }
11411
11412 pub fn to_proto(
11413 &self,
11414 language_server_id: LanguageServerId,
11415 path: &Path,
11416 ) -> proto::DiagnosticSummary {
11417 proto::DiagnosticSummary {
11418 path: path.to_proto(),
11419 language_server_id: language_server_id.0 as u64,
11420 error_count: self.error_count as u32,
11421 warning_count: self.warning_count as u32,
11422 }
11423 }
11424}
11425
11426#[derive(Clone, Debug)]
11427pub enum CompletionDocumentation {
11428 /// There is no documentation for this completion.
11429 Undocumented,
11430 /// A single line of documentation.
11431 SingleLine(SharedString),
11432 /// Multiple lines of plain text documentation.
11433 MultiLinePlainText(SharedString),
11434 /// Markdown documentation.
11435 MultiLineMarkdown(SharedString),
11436 /// Both single line and multiple lines of plain text documentation.
11437 SingleLineAndMultiLinePlainText {
11438 single_line: SharedString,
11439 plain_text: Option<SharedString>,
11440 },
11441}
11442
11443impl From<lsp::Documentation> for CompletionDocumentation {
11444 fn from(docs: lsp::Documentation) -> Self {
11445 match docs {
11446 lsp::Documentation::String(text) => {
11447 if text.lines().count() <= 1 {
11448 CompletionDocumentation::SingleLine(text.into())
11449 } else {
11450 CompletionDocumentation::MultiLinePlainText(text.into())
11451 }
11452 }
11453
11454 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
11455 lsp::MarkupKind::PlainText => {
11456 if value.lines().count() <= 1 {
11457 CompletionDocumentation::SingleLine(value.into())
11458 } else {
11459 CompletionDocumentation::MultiLinePlainText(value.into())
11460 }
11461 }
11462
11463 lsp::MarkupKind::Markdown => {
11464 CompletionDocumentation::MultiLineMarkdown(value.into())
11465 }
11466 },
11467 }
11468 }
11469}
11470
11471fn glob_literal_prefix(glob: &Path) -> PathBuf {
11472 glob.components()
11473 .take_while(|component| match component {
11474 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
11475 _ => true,
11476 })
11477 .collect()
11478}
11479
11480pub struct SshLspAdapter {
11481 name: LanguageServerName,
11482 binary: LanguageServerBinary,
11483 initialization_options: Option<String>,
11484 code_action_kinds: Option<Vec<CodeActionKind>>,
11485}
11486
11487impl SshLspAdapter {
11488 pub fn new(
11489 name: LanguageServerName,
11490 binary: LanguageServerBinary,
11491 initialization_options: Option<String>,
11492 code_action_kinds: Option<String>,
11493 ) -> Self {
11494 Self {
11495 name,
11496 binary,
11497 initialization_options,
11498 code_action_kinds: code_action_kinds
11499 .as_ref()
11500 .and_then(|c| serde_json::from_str(c).ok()),
11501 }
11502 }
11503}
11504
11505#[async_trait(?Send)]
11506impl LspAdapter for SshLspAdapter {
11507 fn name(&self) -> LanguageServerName {
11508 self.name.clone()
11509 }
11510
11511 async fn initialization_options(
11512 self: Arc<Self>,
11513 _: &dyn Fs,
11514 _: &Arc<dyn LspAdapterDelegate>,
11515 ) -> Result<Option<serde_json::Value>> {
11516 let Some(options) = &self.initialization_options else {
11517 return Ok(None);
11518 };
11519 let result = serde_json::from_str(options)?;
11520 Ok(result)
11521 }
11522
11523 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
11524 self.code_action_kinds.clone()
11525 }
11526
11527 async fn check_if_user_installed(
11528 &self,
11529 _: &dyn LspAdapterDelegate,
11530 _: Arc<dyn LanguageToolchainStore>,
11531 _: &AsyncApp,
11532 ) -> Option<LanguageServerBinary> {
11533 Some(self.binary.clone())
11534 }
11535
11536 async fn cached_server_binary(
11537 &self,
11538 _: PathBuf,
11539 _: &dyn LspAdapterDelegate,
11540 ) -> Option<LanguageServerBinary> {
11541 None
11542 }
11543
11544 async fn fetch_latest_server_version(
11545 &self,
11546 _: &dyn LspAdapterDelegate,
11547 ) -> Result<Box<dyn 'static + Send + Any>> {
11548 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
11549 }
11550
11551 async fn fetch_server_binary(
11552 &self,
11553 _: Box<dyn 'static + Send + Any>,
11554 _: PathBuf,
11555 _: &dyn LspAdapterDelegate,
11556 ) -> Result<LanguageServerBinary> {
11557 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
11558 }
11559}
11560
11561pub fn language_server_settings<'a>(
11562 delegate: &'a dyn LspAdapterDelegate,
11563 language: &LanguageServerName,
11564 cx: &'a App,
11565) -> Option<&'a LspSettings> {
11566 language_server_settings_for(
11567 SettingsLocation {
11568 worktree_id: delegate.worktree_id(),
11569 path: delegate.worktree_root_path(),
11570 },
11571 language,
11572 cx,
11573 )
11574}
11575
11576pub(crate) fn language_server_settings_for<'a>(
11577 location: SettingsLocation<'a>,
11578 language: &LanguageServerName,
11579 cx: &'a App,
11580) -> Option<&'a LspSettings> {
11581 ProjectSettings::get(Some(location), cx).lsp.get(language)
11582}
11583
11584pub struct LocalLspAdapterDelegate {
11585 lsp_store: WeakEntity<LspStore>,
11586 worktree: worktree::Snapshot,
11587 fs: Arc<dyn Fs>,
11588 http_client: Arc<dyn HttpClient>,
11589 language_registry: Arc<LanguageRegistry>,
11590 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
11591}
11592
11593impl LocalLspAdapterDelegate {
11594 pub fn new(
11595 language_registry: Arc<LanguageRegistry>,
11596 environment: &Entity<ProjectEnvironment>,
11597 lsp_store: WeakEntity<LspStore>,
11598 worktree: &Entity<Worktree>,
11599 http_client: Arc<dyn HttpClient>,
11600 fs: Arc<dyn Fs>,
11601 cx: &mut App,
11602 ) -> Arc<Self> {
11603 let load_shell_env_task = environment.update(cx, |env, cx| {
11604 env.get_worktree_environment(worktree.clone(), cx)
11605 });
11606
11607 Arc::new(Self {
11608 lsp_store,
11609 worktree: worktree.read(cx).snapshot(),
11610 fs,
11611 http_client,
11612 language_registry,
11613 load_shell_env_task,
11614 })
11615 }
11616
11617 fn from_local_lsp(
11618 local: &LocalLspStore,
11619 worktree: &Entity<Worktree>,
11620 cx: &mut App,
11621 ) -> Arc<Self> {
11622 Self::new(
11623 local.languages.clone(),
11624 &local.environment,
11625 local.weak.clone(),
11626 worktree,
11627 local.http_client.clone(),
11628 local.fs.clone(),
11629 cx,
11630 )
11631 }
11632}
11633
11634#[async_trait]
11635impl LspAdapterDelegate for LocalLspAdapterDelegate {
11636 fn show_notification(&self, message: &str, cx: &mut App) {
11637 self.lsp_store
11638 .update(cx, |_, cx| {
11639 cx.emit(LspStoreEvent::Notification(message.to_owned()))
11640 })
11641 .ok();
11642 }
11643
11644 fn http_client(&self) -> Arc<dyn HttpClient> {
11645 self.http_client.clone()
11646 }
11647
11648 fn worktree_id(&self) -> WorktreeId {
11649 self.worktree.id()
11650 }
11651
11652 fn worktree_root_path(&self) -> &Path {
11653 self.worktree.abs_path().as_ref()
11654 }
11655
11656 async fn shell_env(&self) -> HashMap<String, String> {
11657 let task = self.load_shell_env_task.clone();
11658 task.await.unwrap_or_default()
11659 }
11660
11661 async fn npm_package_installed_version(
11662 &self,
11663 package_name: &str,
11664 ) -> Result<Option<(PathBuf, String)>> {
11665 let local_package_directory = self.worktree_root_path();
11666 let node_modules_directory = local_package_directory.join("node_modules");
11667
11668 if let Some(version) =
11669 read_package_installed_version(node_modules_directory.clone(), package_name).await?
11670 {
11671 return Ok(Some((node_modules_directory, version)));
11672 }
11673 let Some(npm) = self.which("npm".as_ref()).await else {
11674 log::warn!(
11675 "Failed to find npm executable for {:?}",
11676 local_package_directory
11677 );
11678 return Ok(None);
11679 };
11680
11681 let env = self.shell_env().await;
11682 let output = util::command::new_smol_command(&npm)
11683 .args(["root", "-g"])
11684 .envs(env)
11685 .current_dir(local_package_directory)
11686 .output()
11687 .await?;
11688 let global_node_modules =
11689 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
11690
11691 if let Some(version) =
11692 read_package_installed_version(global_node_modules.clone(), package_name).await?
11693 {
11694 return Ok(Some((global_node_modules, version)));
11695 }
11696 return Ok(None);
11697 }
11698
11699 #[cfg(not(target_os = "windows"))]
11700 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11701 let worktree_abs_path = self.worktree.abs_path();
11702 let shell_path = self.shell_env().await.get("PATH").cloned();
11703 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
11704 }
11705
11706 #[cfg(target_os = "windows")]
11707 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11708 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11709 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11710 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11711 which::which(command).ok()
11712 }
11713
11714 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
11715 let working_dir = self.worktree_root_path();
11716 let output = util::command::new_smol_command(&command.path)
11717 .args(command.arguments)
11718 .envs(command.env.clone().unwrap_or_default())
11719 .current_dir(working_dir)
11720 .output()
11721 .await?;
11722
11723 anyhow::ensure!(
11724 output.status.success(),
11725 "{}, stdout: {:?}, stderr: {:?}",
11726 output.status,
11727 String::from_utf8_lossy(&output.stdout),
11728 String::from_utf8_lossy(&output.stderr)
11729 );
11730 Ok(())
11731 }
11732
11733 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
11734 self.language_registry
11735 .update_lsp_binary_status(server_name, status);
11736 }
11737
11738 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
11739 self.language_registry
11740 .all_lsp_adapters()
11741 .into_iter()
11742 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
11743 .collect()
11744 }
11745
11746 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
11747 let dir = self.language_registry.language_server_download_dir(name)?;
11748
11749 if !dir.exists() {
11750 smol::fs::create_dir_all(&dir)
11751 .await
11752 .context("failed to create container directory")
11753 .log_err()?;
11754 }
11755
11756 Some(dir)
11757 }
11758
11759 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11760 let entry = self
11761 .worktree
11762 .entry_for_path(&path)
11763 .with_context(|| format!("no worktree entry for path {path:?}"))?;
11764 let abs_path = self
11765 .worktree
11766 .absolutize(&entry.path)
11767 .with_context(|| format!("cannot absolutize path {path:?}"))?;
11768
11769 self.fs.load(&abs_path).await
11770 }
11771}
11772
11773async fn populate_labels_for_symbols(
11774 symbols: Vec<CoreSymbol>,
11775 language_registry: &Arc<LanguageRegistry>,
11776 lsp_adapter: Option<Arc<CachedLspAdapter>>,
11777 output: &mut Vec<Symbol>,
11778) {
11779 #[allow(clippy::mutable_key_type)]
11780 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
11781
11782 let mut unknown_paths = BTreeSet::new();
11783 for symbol in symbols {
11784 let language = language_registry
11785 .language_for_file_path(&symbol.path.path)
11786 .await
11787 .ok()
11788 .or_else(|| {
11789 unknown_paths.insert(symbol.path.path.clone());
11790 None
11791 });
11792 symbols_by_language
11793 .entry(language)
11794 .or_default()
11795 .push(symbol);
11796 }
11797
11798 for unknown_path in unknown_paths {
11799 log::info!(
11800 "no language found for symbol path {}",
11801 unknown_path.display()
11802 );
11803 }
11804
11805 let mut label_params = Vec::new();
11806 for (language, mut symbols) in symbols_by_language {
11807 label_params.clear();
11808 label_params.extend(
11809 symbols
11810 .iter_mut()
11811 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
11812 );
11813
11814 let mut labels = Vec::new();
11815 if let Some(language) = language {
11816 let lsp_adapter = lsp_adapter.clone().or_else(|| {
11817 language_registry
11818 .lsp_adapters(&language.name())
11819 .first()
11820 .cloned()
11821 });
11822 if let Some(lsp_adapter) = lsp_adapter {
11823 labels = lsp_adapter
11824 .labels_for_symbols(&label_params, &language)
11825 .await
11826 .log_err()
11827 .unwrap_or_default();
11828 }
11829 }
11830
11831 for ((symbol, (name, _)), label) in symbols
11832 .into_iter()
11833 .zip(label_params.drain(..))
11834 .zip(labels.into_iter().chain(iter::repeat(None)))
11835 {
11836 output.push(Symbol {
11837 language_server_name: symbol.language_server_name,
11838 source_worktree_id: symbol.source_worktree_id,
11839 source_language_server_id: symbol.source_language_server_id,
11840 path: symbol.path,
11841 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
11842 name,
11843 kind: symbol.kind,
11844 range: symbol.range,
11845 signature: symbol.signature,
11846 });
11847 }
11848 }
11849}
11850
11851fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
11852 match server.capabilities().text_document_sync.as_ref()? {
11853 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
11854 lsp::TextDocumentSyncKind::NONE => None,
11855 lsp::TextDocumentSyncKind::FULL => Some(true),
11856 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
11857 _ => None,
11858 },
11859 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
11860 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
11861 if *supported {
11862 Some(true)
11863 } else {
11864 None
11865 }
11866 }
11867 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
11868 Some(save_options.include_text.unwrap_or(false))
11869 }
11870 },
11871 }
11872}
11873
11874/// Completion items are displayed in a `UniformList`.
11875/// Usually, those items are single-line strings, but in LSP responses,
11876/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
11877/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
11878/// All that may lead to a newline being inserted into resulting `CodeLabel.text`, which will force `UniformList` to bloat each entry to occupy more space,
11879/// breaking the completions menu presentation.
11880///
11881/// Sanitize the text to ensure there are no newlines, or, if there are some, remove them and also remove long space sequences if there were newlines.
11882fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
11883 let mut new_text = String::with_capacity(label.text.len());
11884 let mut offset_map = vec![0; label.text.len() + 1];
11885 let mut last_char_was_space = false;
11886 let mut new_idx = 0;
11887 let mut chars = label.text.char_indices().fuse();
11888 let mut newlines_removed = false;
11889
11890 while let Some((idx, c)) = chars.next() {
11891 offset_map[idx] = new_idx;
11892
11893 match c {
11894 '\n' if last_char_was_space => {
11895 newlines_removed = true;
11896 }
11897 '\t' | ' ' if last_char_was_space => {}
11898 '\n' if !last_char_was_space => {
11899 new_text.push(' ');
11900 new_idx += 1;
11901 last_char_was_space = true;
11902 newlines_removed = true;
11903 }
11904 ' ' | '\t' => {
11905 new_text.push(' ');
11906 new_idx += 1;
11907 last_char_was_space = true;
11908 }
11909 _ => {
11910 new_text.push(c);
11911 new_idx += c.len_utf8();
11912 last_char_was_space = false;
11913 }
11914 }
11915 }
11916 offset_map[label.text.len()] = new_idx;
11917
11918 // Only modify the label if newlines were removed.
11919 if !newlines_removed {
11920 return;
11921 }
11922
11923 let last_index = new_idx;
11924 let mut run_ranges_errors = Vec::new();
11925 label.runs.retain_mut(|(range, _)| {
11926 match offset_map.get(range.start) {
11927 Some(&start) => range.start = start,
11928 None => {
11929 run_ranges_errors.push(range.clone());
11930 return false;
11931 }
11932 }
11933
11934 match offset_map.get(range.end) {
11935 Some(&end) => range.end = end,
11936 None => {
11937 run_ranges_errors.push(range.clone());
11938 range.end = last_index;
11939 }
11940 }
11941 true
11942 });
11943 if !run_ranges_errors.is_empty() {
11944 log::error!(
11945 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
11946 label.text
11947 );
11948 }
11949
11950 let mut wrong_filter_range = None;
11951 if label.filter_range == (0..label.text.len()) {
11952 label.filter_range = 0..new_text.len();
11953 } else {
11954 let mut original_filter_range = Some(label.filter_range.clone());
11955 match offset_map.get(label.filter_range.start) {
11956 Some(&start) => label.filter_range.start = start,
11957 None => {
11958 wrong_filter_range = original_filter_range.take();
11959 label.filter_range.start = last_index;
11960 }
11961 }
11962
11963 match offset_map.get(label.filter_range.end) {
11964 Some(&end) => label.filter_range.end = end,
11965 None => {
11966 wrong_filter_range = original_filter_range.take();
11967 label.filter_range.end = last_index;
11968 }
11969 }
11970 }
11971 if let Some(wrong_filter_range) = wrong_filter_range {
11972 log::error!(
11973 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
11974 label.text
11975 );
11976 }
11977
11978 label.text = new_text;
11979}
11980
11981#[cfg(test)]
11982mod tests {
11983 use language::HighlightId;
11984
11985 use super::*;
11986
11987 #[test]
11988 fn test_glob_literal_prefix() {
11989 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
11990 assert_eq!(
11991 glob_literal_prefix(Path::new("node_modules/**/*.js")),
11992 Path::new("node_modules")
11993 );
11994 assert_eq!(
11995 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
11996 Path::new("foo")
11997 );
11998 assert_eq!(
11999 glob_literal_prefix(Path::new("foo/bar/baz.js")),
12000 Path::new("foo/bar/baz.js")
12001 );
12002
12003 #[cfg(target_os = "windows")]
12004 {
12005 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
12006 assert_eq!(
12007 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
12008 Path::new("node_modules")
12009 );
12010 assert_eq!(
12011 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12012 Path::new("foo")
12013 );
12014 assert_eq!(
12015 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
12016 Path::new("foo/bar/baz.js")
12017 );
12018 }
12019 }
12020
12021 #[test]
12022 fn test_multi_len_chars_normalization() {
12023 let mut label = CodeLabel {
12024 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
12025 runs: vec![(0..6, HighlightId(1))],
12026 filter_range: 0..6,
12027 };
12028 ensure_uniform_list_compatible_label(&mut label);
12029 assert_eq!(
12030 label,
12031 CodeLabel {
12032 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
12033 runs: vec![(0..6, HighlightId(1))],
12034 filter_range: 0..6,
12035 }
12036 );
12037 }
12038}