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