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 sum_tree::Dimensions;
100use text::{Anchor, BufferId, LineEnding, OffsetRangeExt};
101use url::Url;
102use util::{
103 ConnectionResult, ResultExt as _, debug_panic, defer, maybe, merge_json_value_into,
104 paths::{PathExt, SanitizedPath},
105 post_inc,
106};
107
108pub use fs::*;
109pub use language::Location;
110#[cfg(any(test, feature = "test-support"))]
111pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
112pub use worktree::{
113 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
114 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
115};
116
117const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
118pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum FormatTrigger {
122 Save,
123 Manual,
124}
125
126pub enum LspFormatTarget {
127 Buffers,
128 Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
129}
130
131pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
132
133impl FormatTrigger {
134 fn from_proto(value: i32) -> FormatTrigger {
135 match value {
136 0 => FormatTrigger::Save,
137 1 => FormatTrigger::Manual,
138 _ => FormatTrigger::Save,
139 }
140 }
141}
142
143pub struct LocalLspStore {
144 weak: WeakEntity<LspStore>,
145 worktree_store: Entity<WorktreeStore>,
146 toolchain_store: Entity<ToolchainStore>,
147 http_client: Arc<dyn HttpClient>,
148 environment: Entity<ProjectEnvironment>,
149 fs: Arc<dyn Fs>,
150 languages: Arc<LanguageRegistry>,
151 language_server_ids: HashMap<(WorktreeId, LanguageServerName), BTreeSet<LanguageServerId>>,
152 yarn: Entity<YarnPathStore>,
153 pub language_servers: HashMap<LanguageServerId, LanguageServerState>,
154 buffers_being_formatted: HashSet<BufferId>,
155 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
156 language_server_watched_paths: HashMap<LanguageServerId, LanguageServerWatchedPaths>,
157 language_server_paths_watched_for_rename:
158 HashMap<LanguageServerId, RenamePathsWatchedForServer>,
159 language_server_watcher_registrations:
160 HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
161 supplementary_language_servers:
162 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
163 prettier_store: Entity<PrettierStore>,
164 next_diagnostic_group_id: usize,
165 diagnostics: HashMap<
166 WorktreeId,
167 HashMap<
168 Arc<Path>,
169 Vec<(
170 LanguageServerId,
171 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
172 )>,
173 >,
174 >,
175 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
176 _subscription: gpui::Subscription,
177 lsp_tree: Entity<LanguageServerTree>,
178 registered_buffers: HashMap<BufferId, usize>,
179 buffers_opened_in_servers: HashMap<BufferId, HashSet<LanguageServerId>>,
180 buffer_pull_diagnostics_result_ids: HashMap<LanguageServerId, HashMap<PathBuf, Option<String>>>,
181}
182
183impl LocalLspStore {
184 /// Returns the running language server for the given ID. Note if the language server is starting, it will not be returned.
185 pub fn running_language_server_for_id(
186 &self,
187 id: LanguageServerId,
188 ) -> Option<&Arc<LanguageServer>> {
189 let language_server_state = self.language_servers.get(&id)?;
190
191 match language_server_state {
192 LanguageServerState::Running { server, .. } => Some(server),
193 LanguageServerState::Starting { .. } => None,
194 }
195 }
196
197 fn start_language_server(
198 &mut self,
199 worktree_handle: &Entity<Worktree>,
200 delegate: Arc<LocalLspAdapterDelegate>,
201 adapter: Arc<CachedLspAdapter>,
202 settings: Arc<LspSettings>,
203 cx: &mut App,
204 ) -> LanguageServerId {
205 let worktree = worktree_handle.read(cx);
206 let worktree_id = worktree.id();
207 let root_path = worktree.abs_path();
208 let key = (worktree_id, adapter.name.clone());
209
210 let override_options = settings.initialization_options.clone();
211
212 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
213
214 let server_id = self.languages.next_language_server_id();
215 log::info!(
216 "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
217 adapter.name.0
218 );
219
220 let binary = self.get_language_server_binary(adapter.clone(), delegate.clone(), true, cx);
221 let pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
222
223 let pending_server = cx.spawn({
224 let adapter = adapter.clone();
225 let server_name = adapter.name.clone();
226 let stderr_capture = stderr_capture.clone();
227 #[cfg(any(test, feature = "test-support"))]
228 let lsp_store = self.weak.clone();
229 let pending_workspace_folders = pending_workspace_folders.clone();
230 async move |cx| {
231 let binary = binary.await?;
232 #[cfg(any(test, feature = "test-support"))]
233 if let Some(server) = lsp_store
234 .update(&mut cx.clone(), |this, cx| {
235 this.languages.create_fake_language_server(
236 server_id,
237 &server_name,
238 binary.clone(),
239 &mut cx.to_async(),
240 )
241 })
242 .ok()
243 .flatten()
244 {
245 return Ok(server);
246 }
247
248 let code_action_kinds = adapter.code_action_kinds();
249 lsp::LanguageServer::new(
250 stderr_capture,
251 server_id,
252 server_name,
253 binary,
254 &root_path,
255 code_action_kinds,
256 Some(pending_workspace_folders).filter(|_| {
257 adapter.adapter.workspace_folders_content()
258 == WorkspaceFoldersContent::SubprojectRoots
259 }),
260 cx,
261 )
262 }
263 });
264
265 let startup = {
266 let server_name = adapter.name.0.clone();
267 let delegate = delegate as Arc<dyn LspAdapterDelegate>;
268 let key = key.clone();
269 let adapter = adapter.clone();
270 let lsp_store = self.weak.clone();
271 let pending_workspace_folders = pending_workspace_folders.clone();
272 let fs = self.fs.clone();
273 let pull_diagnostics = ProjectSettings::get_global(cx)
274 .diagnostics
275 .lsp_pull_diagnostics
276 .enabled;
277 cx.spawn(async move |cx| {
278 let result = async {
279 let toolchains =
280 lsp_store.update(cx, |lsp_store, cx| lsp_store.toolchain_store(cx))?;
281 let language_server = pending_server.await?;
282
283 let workspace_config = Self::workspace_configuration_for_adapter(
284 adapter.adapter.clone(),
285 fs.as_ref(),
286 &delegate,
287 toolchains.clone(),
288 cx,
289 )
290 .await?;
291
292 let mut initialization_options = Self::initialization_options_for_adapter(
293 adapter.adapter.clone(),
294 fs.as_ref(),
295 &delegate,
296 )
297 .await?;
298
299 match (&mut initialization_options, override_options) {
300 (Some(initialization_options), Some(override_options)) => {
301 merge_json_value_into(override_options, initialization_options);
302 }
303 (None, override_options) => initialization_options = override_options,
304 _ => {}
305 }
306
307 let initialization_params = cx.update(|cx| {
308 let mut params =
309 language_server.default_initialize_params(pull_diagnostics, cx);
310 params.initialization_options = initialization_options;
311 adapter.adapter.prepare_initialize_params(params, cx)
312 })??;
313
314 Self::setup_lsp_messages(
315 lsp_store.clone(),
316 fs,
317 &language_server,
318 delegate.clone(),
319 adapter.clone(),
320 );
321
322 let did_change_configuration_params =
323 Arc::new(lsp::DidChangeConfigurationParams {
324 settings: workspace_config,
325 });
326 let language_server = cx
327 .update(|cx| {
328 language_server.initialize(
329 initialization_params,
330 did_change_configuration_params.clone(),
331 cx,
332 )
333 })?
334 .await
335 .inspect_err(|_| {
336 if let Some(lsp_store) = lsp_store.upgrade() {
337 lsp_store
338 .update(cx, |lsp_store, cx| {
339 lsp_store.cleanup_lsp_data(server_id);
340 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id))
341 })
342 .ok();
343 }
344 })?;
345
346 language_server
347 .notify::<lsp::notification::DidChangeConfiguration>(
348 &did_change_configuration_params,
349 )
350 .ok();
351
352 anyhow::Ok(language_server)
353 }
354 .await;
355
356 match result {
357 Ok(server) => {
358 lsp_store
359 .update(cx, |lsp_store, mut cx| {
360 lsp_store.insert_newly_running_language_server(
361 adapter,
362 server.clone(),
363 server_id,
364 key,
365 pending_workspace_folders,
366 &mut cx,
367 );
368 })
369 .ok();
370 stderr_capture.lock().take();
371 Some(server)
372 }
373
374 Err(err) => {
375 let log = stderr_capture.lock().take().unwrap_or_default();
376 delegate.update_status(
377 adapter.name(),
378 BinaryStatus::Failed {
379 error: format!("{err}\n-- stderr--\n{log}"),
380 },
381 );
382 let message =
383 format!("Failed to start language server {server_name:?}: {err:#?}");
384 log::error!("{message}");
385 log::error!("server stderr: {log}");
386 None
387 }
388 }
389 })
390 };
391 let state = LanguageServerState::Starting {
392 startup,
393 pending_workspace_folders,
394 };
395
396 self.languages
397 .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
398
399 self.language_servers.insert(server_id, state);
400 self.language_server_ids
401 .entry(key)
402 .or_default()
403 .insert(server_id);
404 server_id
405 }
406
407 fn get_language_server_binary(
408 &self,
409 adapter: Arc<CachedLspAdapter>,
410 delegate: Arc<dyn LspAdapterDelegate>,
411 allow_binary_download: bool,
412 cx: &mut App,
413 ) -> Task<Result<LanguageServerBinary>> {
414 let settings = ProjectSettings::get(
415 Some(SettingsLocation {
416 worktree_id: delegate.worktree_id(),
417 path: Path::new(""),
418 }),
419 cx,
420 )
421 .lsp
422 .get(&adapter.name)
423 .and_then(|s| s.binary.clone());
424
425 if settings.as_ref().is_some_and(|b| b.path.is_some()) {
426 let settings = settings.unwrap();
427
428 return cx.background_spawn(async move {
429 let mut env = delegate.shell_env().await;
430 env.extend(settings.env.unwrap_or_default());
431
432 Ok(LanguageServerBinary {
433 path: PathBuf::from(&settings.path.unwrap()),
434 env: Some(env),
435 arguments: settings
436 .arguments
437 .unwrap_or_default()
438 .iter()
439 .map(Into::into)
440 .collect(),
441 })
442 });
443 }
444 let lsp_binary_options = LanguageServerBinaryOptions {
445 allow_path_lookup: !settings
446 .as_ref()
447 .and_then(|b| b.ignore_system_version)
448 .unwrap_or_default(),
449 allow_binary_download,
450 };
451 let toolchains = self.toolchain_store.read(cx).as_language_toolchain_store();
452 cx.spawn(async move |cx| {
453 let binary_result = adapter
454 .clone()
455 .get_language_server_command(delegate.clone(), toolchains, lsp_binary_options, cx)
456 .await;
457
458 delegate.update_status(adapter.name.clone(), BinaryStatus::None);
459
460 let mut binary = binary_result?;
461 let mut shell_env = delegate.shell_env().await;
462
463 shell_env.extend(binary.env.unwrap_or_default());
464
465 if let Some(settings) = settings {
466 if let Some(arguments) = settings.arguments {
467 binary.arguments = arguments.into_iter().map(Into::into).collect();
468 }
469 if let Some(env) = settings.env {
470 shell_env.extend(env);
471 }
472 }
473
474 binary.env = Some(shell_env);
475 Ok(binary)
476 })
477 }
478
479 fn setup_lsp_messages(
480 this: WeakEntity<LspStore>,
481 fs: Arc<dyn Fs>,
482 language_server: &LanguageServer,
483 delegate: Arc<dyn LspAdapterDelegate>,
484 adapter: Arc<CachedLspAdapter>,
485 ) {
486 let name = language_server.name();
487 let server_id = language_server.server_id();
488 language_server
489 .on_notification::<lsp::notification::PublishDiagnostics, _>({
490 let adapter = adapter.clone();
491 let this = this.clone();
492 move |mut params, cx| {
493 let adapter = adapter.clone();
494 if let Some(this) = this.upgrade() {
495 this.update(cx, |this, cx| {
496 {
497 let buffer = params
498 .uri
499 .to_file_path()
500 .map(|file_path| this.get_buffer(&file_path, cx))
501 .ok()
502 .flatten();
503 adapter.process_diagnostics(&mut params, server_id, buffer);
504 }
505
506 this.merge_diagnostics(
507 server_id,
508 params,
509 None,
510 DiagnosticSourceKind::Pushed,
511 &adapter.disk_based_diagnostic_sources,
512 |_, diagnostic, cx| match diagnostic.source_kind {
513 DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => {
514 adapter.retain_old_diagnostic(diagnostic, cx)
515 }
516 DiagnosticSourceKind::Pulled => true,
517 },
518 cx,
519 )
520 .log_err();
521 })
522 .ok();
523 }
524 }
525 })
526 .detach();
527 language_server
528 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
529 let adapter = adapter.adapter.clone();
530 let delegate = delegate.clone();
531 let this = this.clone();
532 let fs = fs.clone();
533 move |params, cx| {
534 let adapter = adapter.clone();
535 let delegate = delegate.clone();
536 let this = this.clone();
537 let fs = fs.clone();
538 let mut cx = cx.clone();
539 async move {
540 let toolchains =
541 this.update(&mut cx, |this, cx| this.toolchain_store(cx))?;
542
543 let workspace_config = Self::workspace_configuration_for_adapter(
544 adapter.clone(),
545 fs.as_ref(),
546 &delegate,
547 toolchains.clone(),
548 &mut cx,
549 )
550 .await?;
551
552 Ok(params
553 .items
554 .into_iter()
555 .map(|item| {
556 if let Some(section) = &item.section {
557 workspace_config
558 .get(section)
559 .cloned()
560 .unwrap_or(serde_json::Value::Null)
561 } else {
562 workspace_config.clone()
563 }
564 })
565 .collect())
566 }
567 }
568 })
569 .detach();
570
571 language_server
572 .on_request::<lsp::request::WorkspaceFoldersRequest, _, _>({
573 let this = this.clone();
574 move |_, cx| {
575 let this = this.clone();
576 let mut cx = cx.clone();
577 async move {
578 let Some(server) = this
579 .read_with(&mut cx, |this, _| this.language_server_for_id(server_id))?
580 else {
581 return Ok(None);
582 };
583 let root = server.workspace_folders();
584 Ok(Some(
585 root.into_iter()
586 .map(|uri| WorkspaceFolder {
587 uri,
588 name: Default::default(),
589 })
590 .collect(),
591 ))
592 }
593 }
594 })
595 .detach();
596 // Even though we don't have handling for these requests, respond to them to
597 // avoid stalling any language server like `gopls` which waits for a response
598 // to these requests when initializing.
599 language_server
600 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
601 let this = this.clone();
602 move |params, cx| {
603 let this = this.clone();
604 let mut cx = cx.clone();
605 async move {
606 this.update(&mut cx, |this, _| {
607 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
608 {
609 if let lsp::NumberOrString::String(token) = params.token {
610 status.progress_tokens.insert(token);
611 }
612 }
613 })?;
614
615 Ok(())
616 }
617 }
618 })
619 .detach();
620
621 language_server
622 .on_request::<lsp::request::RegisterCapability, _, _>({
623 let this = this.clone();
624 move |params, cx| {
625 let this = this.clone();
626 let mut cx = cx.clone();
627 async move {
628 for reg in params.registrations {
629 match reg.method.as_str() {
630 "workspace/didChangeWatchedFiles" => {
631 if let Some(options) = reg.register_options {
632 let options = serde_json::from_value(options)?;
633 this.update(&mut cx, |this, cx| {
634 this.as_local_mut()?.on_lsp_did_change_watched_files(
635 server_id, ®.id, options, cx,
636 );
637 Some(())
638 })?;
639 }
640 }
641 "textDocument/rangeFormatting" => {
642 this.read_with(&mut cx, |this, _| {
643 if let Some(server) = this.language_server_for_id(server_id)
644 {
645 let options = reg
646 .register_options
647 .map(|options| {
648 serde_json::from_value::<
649 lsp::DocumentRangeFormattingOptions,
650 >(
651 options
652 )
653 })
654 .transpose()?;
655 let provider = match options {
656 None => OneOf::Left(true),
657 Some(options) => OneOf::Right(options),
658 };
659 server.update_capabilities(|capabilities| {
660 capabilities.document_range_formatting_provider =
661 Some(provider);
662 })
663 }
664 anyhow::Ok(())
665 })??;
666 }
667 "textDocument/onTypeFormatting" => {
668 this.read_with(&mut cx, |this, _| {
669 if let Some(server) = this.language_server_for_id(server_id)
670 {
671 let options = reg
672 .register_options
673 .map(|options| {
674 serde_json::from_value::<
675 lsp::DocumentOnTypeFormattingOptions,
676 >(
677 options
678 )
679 })
680 .transpose()?;
681 if let Some(options) = options {
682 server.update_capabilities(|capabilities| {
683 capabilities
684 .document_on_type_formatting_provider =
685 Some(options);
686 })
687 }
688 }
689 anyhow::Ok(())
690 })??;
691 }
692 "textDocument/formatting" => {
693 this.read_with(&mut cx, |this, _| {
694 if let Some(server) = this.language_server_for_id(server_id)
695 {
696 let options = reg
697 .register_options
698 .map(|options| {
699 serde_json::from_value::<
700 lsp::DocumentFormattingOptions,
701 >(
702 options
703 )
704 })
705 .transpose()?;
706 let provider = match options {
707 None => OneOf::Left(true),
708 Some(options) => OneOf::Right(options),
709 };
710 server.update_capabilities(|capabilities| {
711 capabilities.document_formatting_provider =
712 Some(provider);
713 })
714 }
715 anyhow::Ok(())
716 })??;
717 }
718 "workspace/didChangeConfiguration" => {
719 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
720 }
721 "textDocument/rename" => {
722 this.read_with(&mut cx, |this, _| {
723 if let Some(server) = this.language_server_for_id(server_id)
724 {
725 let options = reg
726 .register_options
727 .map(|options| {
728 serde_json::from_value::<lsp::RenameOptions>(
729 options,
730 )
731 })
732 .transpose()?;
733 let options = match options {
734 None => OneOf::Left(true),
735 Some(options) => OneOf::Right(options),
736 };
737
738 server.update_capabilities(|capabilities| {
739 capabilities.rename_provider = Some(options);
740 })
741 }
742 anyhow::Ok(())
743 })??;
744 }
745 _ => log::warn!("unhandled capability registration: {reg:?}"),
746 }
747 }
748 Ok(())
749 }
750 }
751 })
752 .detach();
753
754 language_server
755 .on_request::<lsp::request::UnregisterCapability, _, _>({
756 let this = this.clone();
757 move |params, cx| {
758 let this = this.clone();
759 let mut cx = cx.clone();
760 async move {
761 for unreg in params.unregisterations.iter() {
762 match unreg.method.as_str() {
763 "workspace/didChangeWatchedFiles" => {
764 this.update(&mut cx, |this, cx| {
765 this.as_local_mut()?
766 .on_lsp_unregister_did_change_watched_files(
767 server_id, &unreg.id, cx,
768 );
769 Some(())
770 })?;
771 }
772 "workspace/didChangeConfiguration" => {
773 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
774 }
775 "textDocument/rename" => {
776 this.read_with(&mut cx, |this, _| {
777 if let Some(server) = this.language_server_for_id(server_id)
778 {
779 server.update_capabilities(|capabilities| {
780 capabilities.rename_provider = None
781 })
782 }
783 })?;
784 }
785 "textDocument/rangeFormatting" => {
786 this.read_with(&mut cx, |this, _| {
787 if let Some(server) = this.language_server_for_id(server_id)
788 {
789 server.update_capabilities(|capabilities| {
790 capabilities.document_range_formatting_provider =
791 None
792 })
793 }
794 })?;
795 }
796 "textDocument/onTypeFormatting" => {
797 this.read_with(&mut cx, |this, _| {
798 if let Some(server) = this.language_server_for_id(server_id)
799 {
800 server.update_capabilities(|capabilities| {
801 capabilities.document_on_type_formatting_provider =
802 None;
803 })
804 }
805 })?;
806 }
807 "textDocument/formatting" => {
808 this.read_with(&mut cx, |this, _| {
809 if let Some(server) = this.language_server_for_id(server_id)
810 {
811 server.update_capabilities(|capabilities| {
812 capabilities.document_formatting_provider = None;
813 })
814 }
815 })?;
816 }
817 _ => log::warn!("unhandled capability unregistration: {unreg:?}"),
818 }
819 }
820 Ok(())
821 }
822 }
823 })
824 .detach();
825
826 language_server
827 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
828 let adapter = adapter.clone();
829 let this = this.clone();
830 move |params, cx| {
831 let mut cx = cx.clone();
832 let this = this.clone();
833 let adapter = adapter.clone();
834 async move {
835 LocalLspStore::on_lsp_workspace_edit(
836 this.clone(),
837 params,
838 server_id,
839 adapter.clone(),
840 &mut cx,
841 )
842 .await
843 }
844 }
845 })
846 .detach();
847
848 language_server
849 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
850 let this = this.clone();
851 move |(), cx| {
852 let this = this.clone();
853 let mut cx = cx.clone();
854 async move {
855 this.update(&mut cx, |this, cx| {
856 cx.emit(LspStoreEvent::RefreshInlayHints);
857 this.downstream_client.as_ref().map(|(client, project_id)| {
858 client.send(proto::RefreshInlayHints {
859 project_id: *project_id,
860 })
861 })
862 })?
863 .transpose()?;
864 Ok(())
865 }
866 }
867 })
868 .detach();
869
870 language_server
871 .on_request::<lsp::request::CodeLensRefresh, _, _>({
872 let this = this.clone();
873 move |(), cx| {
874 let this = this.clone();
875 let mut cx = cx.clone();
876 async move {
877 this.update(&mut cx, |this, cx| {
878 cx.emit(LspStoreEvent::RefreshCodeLens);
879 this.downstream_client.as_ref().map(|(client, project_id)| {
880 client.send(proto::RefreshCodeLens {
881 project_id: *project_id,
882 })
883 })
884 })?
885 .transpose()?;
886 Ok(())
887 }
888 }
889 })
890 .detach();
891
892 language_server
893 .on_request::<lsp::request::WorkspaceDiagnosticRefresh, _, _>({
894 let this = this.clone();
895 move |(), cx| {
896 let this = this.clone();
897 let mut cx = cx.clone();
898 async move {
899 this.update(&mut cx, |lsp_store, _| {
900 lsp_store.pull_workspace_diagnostics(server_id);
901 lsp_store
902 .downstream_client
903 .as_ref()
904 .map(|(client, project_id)| {
905 client.send(proto::PullWorkspaceDiagnostics {
906 project_id: *project_id,
907 server_id: server_id.to_proto(),
908 })
909 })
910 })?
911 .transpose()?;
912 Ok(())
913 }
914 }
915 })
916 .detach();
917
918 language_server
919 .on_request::<lsp::request::ShowMessageRequest, _, _>({
920 let this = this.clone();
921 let name = name.to_string();
922 move |params, cx| {
923 let this = this.clone();
924 let name = name.to_string();
925 let mut cx = cx.clone();
926 async move {
927 let actions = params.actions.unwrap_or_default();
928 let (tx, rx) = smol::channel::bounded(1);
929 let request = LanguageServerPromptRequest {
930 level: match params.typ {
931 lsp::MessageType::ERROR => PromptLevel::Critical,
932 lsp::MessageType::WARNING => PromptLevel::Warning,
933 _ => PromptLevel::Info,
934 },
935 message: params.message,
936 actions,
937 response_channel: tx,
938 lsp_name: name.clone(),
939 };
940
941 let did_update = this
942 .update(&mut cx, |_, cx| {
943 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
944 })
945 .is_ok();
946 if did_update {
947 let response = rx.recv().await.ok();
948 Ok(response)
949 } else {
950 Ok(None)
951 }
952 }
953 }
954 })
955 .detach();
956 language_server
957 .on_notification::<lsp::notification::ShowMessage, _>({
958 let this = this.clone();
959 let name = name.to_string();
960 move |params, cx| {
961 let this = this.clone();
962 let name = name.to_string();
963 let mut cx = cx.clone();
964
965 let (tx, _) = smol::channel::bounded(1);
966 let request = LanguageServerPromptRequest {
967 level: match params.typ {
968 lsp::MessageType::ERROR => PromptLevel::Critical,
969 lsp::MessageType::WARNING => PromptLevel::Warning,
970 _ => PromptLevel::Info,
971 },
972 message: params.message,
973 actions: vec![],
974 response_channel: tx,
975 lsp_name: name.clone(),
976 };
977
978 let _ = this.update(&mut cx, |_, cx| {
979 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
980 });
981 }
982 })
983 .detach();
984
985 let disk_based_diagnostics_progress_token =
986 adapter.disk_based_diagnostics_progress_token.clone();
987
988 language_server
989 .on_notification::<lsp::notification::Progress, _>({
990 let this = this.clone();
991 move |params, cx| {
992 if let Some(this) = this.upgrade() {
993 this.update(cx, |this, cx| {
994 this.on_lsp_progress(
995 params,
996 server_id,
997 disk_based_diagnostics_progress_token.clone(),
998 cx,
999 );
1000 })
1001 .ok();
1002 }
1003 }
1004 })
1005 .detach();
1006
1007 language_server
1008 .on_notification::<lsp::notification::LogMessage, _>({
1009 let this = this.clone();
1010 move |params, cx| {
1011 if let Some(this) = this.upgrade() {
1012 this.update(cx, |_, cx| {
1013 cx.emit(LspStoreEvent::LanguageServerLog(
1014 server_id,
1015 LanguageServerLogType::Log(params.typ),
1016 params.message,
1017 ));
1018 })
1019 .ok();
1020 }
1021 }
1022 })
1023 .detach();
1024
1025 language_server
1026 .on_notification::<lsp::notification::LogTrace, _>({
1027 let this = this.clone();
1028 move |params, cx| {
1029 let mut cx = cx.clone();
1030 if let Some(this) = this.upgrade() {
1031 this.update(&mut cx, |_, cx| {
1032 cx.emit(LspStoreEvent::LanguageServerLog(
1033 server_id,
1034 LanguageServerLogType::Trace(params.verbose),
1035 params.message,
1036 ));
1037 })
1038 .ok();
1039 }
1040 }
1041 })
1042 .detach();
1043
1044 json_language_server_ext::register_requests(this.clone(), language_server);
1045 rust_analyzer_ext::register_notifications(this.clone(), language_server);
1046 clangd_ext::register_notifications(this, language_server, adapter);
1047 }
1048
1049 fn shutdown_language_servers_on_quit(
1050 &mut self,
1051 _: &mut Context<LspStore>,
1052 ) -> impl Future<Output = ()> + use<> {
1053 let shutdown_futures = self
1054 .language_servers
1055 .drain()
1056 .map(|(_, server_state)| Self::shutdown_server(server_state))
1057 .collect::<Vec<_>>();
1058
1059 async move {
1060 join_all(shutdown_futures).await;
1061 }
1062 }
1063
1064 async fn shutdown_server(server_state: LanguageServerState) -> anyhow::Result<()> {
1065 match server_state {
1066 LanguageServerState::Running { server, .. } => {
1067 if let Some(shutdown) = server.shutdown() {
1068 shutdown.await;
1069 }
1070 }
1071 LanguageServerState::Starting { startup, .. } => {
1072 if let Some(server) = startup.await {
1073 if let Some(shutdown) = server.shutdown() {
1074 shutdown.await;
1075 }
1076 }
1077 }
1078 }
1079 Ok(())
1080 }
1081
1082 fn language_servers_for_worktree(
1083 &self,
1084 worktree_id: WorktreeId,
1085 ) -> impl Iterator<Item = &Arc<LanguageServer>> {
1086 self.language_server_ids
1087 .iter()
1088 .flat_map(move |((language_server_path, _), ids)| {
1089 ids.iter().filter_map(move |id| {
1090 if *language_server_path != worktree_id {
1091 return None;
1092 }
1093 if let Some(LanguageServerState::Running { server, .. }) =
1094 self.language_servers.get(id)
1095 {
1096 return Some(server);
1097 } else {
1098 None
1099 }
1100 })
1101 })
1102 }
1103
1104 fn language_server_ids_for_project_path(
1105 &self,
1106 project_path: ProjectPath,
1107 language: &Language,
1108 cx: &mut App,
1109 ) -> Vec<LanguageServerId> {
1110 let Some(worktree) = self
1111 .worktree_store
1112 .read(cx)
1113 .worktree_for_id(project_path.worktree_id, cx)
1114 else {
1115 return Vec::new();
1116 };
1117 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
1118 let root = self.lsp_tree.update(cx, |this, cx| {
1119 this.get(
1120 project_path,
1121 AdapterQuery::Language(&language.name()),
1122 delegate,
1123 cx,
1124 )
1125 .filter_map(|node| node.server_id())
1126 .collect::<Vec<_>>()
1127 });
1128
1129 root
1130 }
1131
1132 fn language_server_ids_for_buffer(
1133 &self,
1134 buffer: &Buffer,
1135 cx: &mut App,
1136 ) -> Vec<LanguageServerId> {
1137 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
1138 let worktree_id = file.worktree_id(cx);
1139
1140 let path: Arc<Path> = file
1141 .path()
1142 .parent()
1143 .map(Arc::from)
1144 .unwrap_or_else(|| file.path().clone());
1145 let worktree_path = ProjectPath { worktree_id, path };
1146 self.language_server_ids_for_project_path(worktree_path, language, cx)
1147 } else {
1148 Vec::new()
1149 }
1150 }
1151
1152 fn language_servers_for_buffer<'a>(
1153 &'a self,
1154 buffer: &'a Buffer,
1155 cx: &'a mut App,
1156 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1157 self.language_server_ids_for_buffer(buffer, cx)
1158 .into_iter()
1159 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
1160 LanguageServerState::Running {
1161 adapter, server, ..
1162 } => Some((adapter, server)),
1163 _ => None,
1164 })
1165 }
1166
1167 async fn execute_code_action_kind_locally(
1168 lsp_store: WeakEntity<LspStore>,
1169 mut buffers: Vec<Entity<Buffer>>,
1170 kind: CodeActionKind,
1171 push_to_history: bool,
1172 cx: &mut AsyncApp,
1173 ) -> anyhow::Result<ProjectTransaction> {
1174 // Do not allow multiple concurrent code actions requests for the
1175 // same buffer.
1176 lsp_store.update(cx, |this, cx| {
1177 let this = this.as_local_mut().unwrap();
1178 buffers.retain(|buffer| {
1179 this.buffers_being_formatted
1180 .insert(buffer.read(cx).remote_id())
1181 });
1182 })?;
1183 let _cleanup = defer({
1184 let this = lsp_store.clone();
1185 let mut cx = cx.clone();
1186 let buffers = &buffers;
1187 move || {
1188 this.update(&mut cx, |this, cx| {
1189 let this = this.as_local_mut().unwrap();
1190 for buffer in buffers {
1191 this.buffers_being_formatted
1192 .remove(&buffer.read(cx).remote_id());
1193 }
1194 })
1195 .ok();
1196 }
1197 });
1198 let mut project_transaction = ProjectTransaction::default();
1199
1200 for buffer in &buffers {
1201 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1202 buffer.update(cx, |buffer, cx| {
1203 lsp_store
1204 .as_local()
1205 .unwrap()
1206 .language_servers_for_buffer(buffer, cx)
1207 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1208 .collect::<Vec<_>>()
1209 })
1210 })?;
1211 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
1212 let actions = Self::get_server_code_actions_from_action_kinds(
1213 &lsp_store,
1214 language_server.server_id(),
1215 vec![kind.clone()],
1216 buffer,
1217 cx,
1218 )
1219 .await?;
1220 Self::execute_code_actions_on_server(
1221 &lsp_store,
1222 language_server,
1223 lsp_adapter,
1224 actions,
1225 push_to_history,
1226 &mut project_transaction,
1227 cx,
1228 )
1229 .await?;
1230 }
1231 }
1232 Ok(project_transaction)
1233 }
1234
1235 async fn format_locally(
1236 lsp_store: WeakEntity<LspStore>,
1237 mut buffers: Vec<FormattableBuffer>,
1238 push_to_history: bool,
1239 trigger: FormatTrigger,
1240 logger: zlog::Logger,
1241 cx: &mut AsyncApp,
1242 ) -> anyhow::Result<ProjectTransaction> {
1243 // Do not allow multiple concurrent formatting requests for the
1244 // same buffer.
1245 lsp_store.update(cx, |this, cx| {
1246 let this = this.as_local_mut().unwrap();
1247 buffers.retain(|buffer| {
1248 this.buffers_being_formatted
1249 .insert(buffer.handle.read(cx).remote_id())
1250 });
1251 })?;
1252
1253 let _cleanup = defer({
1254 let this = lsp_store.clone();
1255 let mut cx = cx.clone();
1256 let buffers = &buffers;
1257 move || {
1258 this.update(&mut cx, |this, cx| {
1259 let this = this.as_local_mut().unwrap();
1260 for buffer in buffers {
1261 this.buffers_being_formatted
1262 .remove(&buffer.handle.read(cx).remote_id());
1263 }
1264 })
1265 .ok();
1266 }
1267 });
1268
1269 let mut project_transaction = ProjectTransaction::default();
1270
1271 for buffer in &buffers {
1272 zlog::debug!(
1273 logger =>
1274 "formatting buffer '{:?}'",
1275 buffer.abs_path.as_ref().unwrap_or(&PathBuf::from("unknown")).display()
1276 );
1277 // Create an empty transaction to hold all of the formatting edits.
1278 let formatting_transaction_id = buffer.handle.update(cx, |buffer, cx| {
1279 // ensure no transactions created while formatting are
1280 // grouped with the previous transaction in the history
1281 // based on the transaction group interval
1282 buffer.finalize_last_transaction();
1283 buffer
1284 .start_transaction()
1285 .context("transaction already open")?;
1286 buffer.end_transaction(cx);
1287 let transaction_id = buffer.push_empty_transaction(cx.background_executor().now());
1288 buffer.finalize_last_transaction();
1289 anyhow::Ok(transaction_id)
1290 })??;
1291
1292 let result = Self::format_buffer_locally(
1293 lsp_store.clone(),
1294 buffer,
1295 formatting_transaction_id,
1296 trigger,
1297 logger,
1298 cx,
1299 )
1300 .await;
1301
1302 buffer.handle.update(cx, |buffer, cx| {
1303 let Some(formatting_transaction) =
1304 buffer.get_transaction(formatting_transaction_id).cloned()
1305 else {
1306 zlog::warn!(logger => "no formatting transaction");
1307 return;
1308 };
1309 if formatting_transaction.edit_ids.is_empty() {
1310 zlog::debug!(logger => "no changes made while formatting");
1311 buffer.forget_transaction(formatting_transaction_id);
1312 return;
1313 }
1314 if !push_to_history {
1315 zlog::trace!(logger => "forgetting format transaction");
1316 buffer.forget_transaction(formatting_transaction.id);
1317 }
1318 project_transaction
1319 .0
1320 .insert(cx.entity(), formatting_transaction);
1321 })?;
1322
1323 result?;
1324 }
1325
1326 Ok(project_transaction)
1327 }
1328
1329 async fn format_buffer_locally(
1330 lsp_store: WeakEntity<LspStore>,
1331 buffer: &FormattableBuffer,
1332 formatting_transaction_id: clock::Lamport,
1333 trigger: FormatTrigger,
1334 logger: zlog::Logger,
1335 cx: &mut AsyncApp,
1336 ) -> Result<()> {
1337 let (adapters_and_servers, settings) = lsp_store.update(cx, |lsp_store, cx| {
1338 buffer.handle.update(cx, |buffer, cx| {
1339 let adapters_and_servers = lsp_store
1340 .as_local()
1341 .unwrap()
1342 .language_servers_for_buffer(buffer, cx)
1343 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1344 .collect::<Vec<_>>();
1345 let settings =
1346 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
1347 .into_owned();
1348 (adapters_and_servers, settings)
1349 })
1350 })?;
1351
1352 /// Apply edits to the buffer that will become part of the formatting transaction.
1353 /// Fails if the buffer has been edited since the start of that transaction.
1354 fn extend_formatting_transaction(
1355 buffer: &FormattableBuffer,
1356 formatting_transaction_id: text::TransactionId,
1357 cx: &mut AsyncApp,
1358 operation: impl FnOnce(&mut Buffer, &mut Context<Buffer>),
1359 ) -> anyhow::Result<()> {
1360 buffer.handle.update(cx, |buffer, cx| {
1361 let last_transaction_id = buffer.peek_undo_stack().map(|t| t.transaction_id());
1362 if last_transaction_id != Some(formatting_transaction_id) {
1363 anyhow::bail!("Buffer edited while formatting. Aborting")
1364 }
1365 buffer.start_transaction();
1366 operation(buffer, cx);
1367 if let Some(transaction_id) = buffer.end_transaction(cx) {
1368 buffer.merge_transactions(transaction_id, formatting_transaction_id);
1369 }
1370 Ok(())
1371 })?
1372 }
1373
1374 // handle whitespace formatting
1375 if settings.remove_trailing_whitespace_on_save {
1376 zlog::trace!(logger => "removing trailing whitespace");
1377 let diff = buffer
1378 .handle
1379 .read_with(cx, |buffer, cx| buffer.remove_trailing_whitespace(cx))?
1380 .await;
1381 extend_formatting_transaction(buffer, formatting_transaction_id, cx, |buffer, cx| {
1382 buffer.apply_diff(diff, cx);
1383 })?;
1384 }
1385
1386 if settings.ensure_final_newline_on_save {
1387 zlog::trace!(logger => "ensuring final newline");
1388 extend_formatting_transaction(buffer, formatting_transaction_id, cx, |buffer, cx| {
1389 buffer.ensure_final_newline(cx);
1390 })?;
1391 }
1392
1393 // Formatter for `code_actions_on_format` that runs before
1394 // the rest of the formatters
1395 let mut code_actions_on_format_formatter = None;
1396 let should_run_code_actions_on_format = !matches!(
1397 (trigger, &settings.format_on_save),
1398 (FormatTrigger::Save, &FormatOnSave::Off)
1399 );
1400 if should_run_code_actions_on_format {
1401 let have_code_actions_to_run_on_format = settings
1402 .code_actions_on_format
1403 .values()
1404 .any(|enabled| *enabled);
1405 if have_code_actions_to_run_on_format {
1406 zlog::trace!(logger => "going to run code actions on format");
1407 code_actions_on_format_formatter = Some(Formatter::CodeActions(
1408 settings.code_actions_on_format.clone(),
1409 ));
1410 }
1411 }
1412
1413 let formatters = match (trigger, &settings.format_on_save) {
1414 (FormatTrigger::Save, FormatOnSave::Off) => &[],
1415 (FormatTrigger::Save, FormatOnSave::List(formatters)) => formatters.as_ref(),
1416 (FormatTrigger::Manual, _) | (FormatTrigger::Save, FormatOnSave::On) => {
1417 match &settings.formatter {
1418 SelectedFormatter::Auto => {
1419 if settings.prettier.allowed {
1420 zlog::trace!(logger => "Formatter set to auto: defaulting to prettier");
1421 std::slice::from_ref(&Formatter::Prettier)
1422 } else {
1423 zlog::trace!(logger => "Formatter set to auto: defaulting to primary language server");
1424 std::slice::from_ref(&Formatter::LanguageServer { name: None })
1425 }
1426 }
1427 SelectedFormatter::List(formatter_list) => formatter_list.as_ref(),
1428 }
1429 }
1430 };
1431
1432 let formatters = code_actions_on_format_formatter.iter().chain(formatters);
1433
1434 for formatter in formatters {
1435 match formatter {
1436 Formatter::Prettier => {
1437 let logger = zlog::scoped!(logger => "prettier");
1438 zlog::trace!(logger => "formatting");
1439 let _timer = zlog::time!(logger => "Formatting buffer via prettier");
1440
1441 let prettier = lsp_store.read_with(cx, |lsp_store, _cx| {
1442 lsp_store.prettier_store().unwrap().downgrade()
1443 })?;
1444 let diff = prettier_store::format_with_prettier(&prettier, &buffer.handle, cx)
1445 .await
1446 .transpose()?;
1447 let Some(diff) = diff else {
1448 zlog::trace!(logger => "No changes");
1449 continue;
1450 };
1451
1452 extend_formatting_transaction(
1453 buffer,
1454 formatting_transaction_id,
1455 cx,
1456 |buffer, cx| {
1457 buffer.apply_diff(diff, cx);
1458 },
1459 )?;
1460 }
1461 Formatter::External { command, arguments } => {
1462 let logger = zlog::scoped!(logger => "command");
1463 zlog::trace!(logger => "formatting");
1464 let _timer = zlog::time!(logger => "Formatting buffer via external command");
1465
1466 let diff = Self::format_via_external_command(
1467 buffer,
1468 command.as_ref(),
1469 arguments.as_deref(),
1470 cx,
1471 )
1472 .await
1473 .with_context(|| {
1474 format!("Failed to format buffer via external command: {}", command)
1475 })?;
1476 let Some(diff) = diff else {
1477 zlog::trace!(logger => "No changes");
1478 continue;
1479 };
1480
1481 extend_formatting_transaction(
1482 buffer,
1483 formatting_transaction_id,
1484 cx,
1485 |buffer, cx| {
1486 buffer.apply_diff(diff, cx);
1487 },
1488 )?;
1489 }
1490 Formatter::LanguageServer { name } => {
1491 let logger = zlog::scoped!(logger => "language-server");
1492 zlog::trace!(logger => "formatting");
1493 let _timer = zlog::time!(logger => "Formatting buffer using language server");
1494
1495 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1496 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using language servers. Skipping");
1497 continue;
1498 };
1499
1500 let language_server = if let Some(name) = name.as_deref() {
1501 adapters_and_servers.iter().find_map(|(adapter, server)| {
1502 if adapter.name.0.as_ref() == name {
1503 Some(server.clone())
1504 } else {
1505 None
1506 }
1507 })
1508 } else {
1509 adapters_and_servers.first().map(|e| e.1.clone())
1510 };
1511
1512 let Some(language_server) = language_server else {
1513 log::debug!(
1514 "No language server found to format buffer '{:?}'. Skipping",
1515 buffer_path_abs.as_path().to_string_lossy()
1516 );
1517 continue;
1518 };
1519
1520 zlog::trace!(
1521 logger =>
1522 "Formatting buffer '{:?}' using language server '{:?}'",
1523 buffer_path_abs.as_path().to_string_lossy(),
1524 language_server.name()
1525 );
1526
1527 let edits = if let Some(ranges) = buffer.ranges.as_ref() {
1528 zlog::trace!(logger => "formatting ranges");
1529 Self::format_ranges_via_lsp(
1530 &lsp_store,
1531 &buffer.handle,
1532 ranges,
1533 buffer_path_abs,
1534 &language_server,
1535 &settings,
1536 cx,
1537 )
1538 .await
1539 .context("Failed to format ranges via language server")?
1540 } else {
1541 zlog::trace!(logger => "formatting full");
1542 Self::format_via_lsp(
1543 &lsp_store,
1544 &buffer.handle,
1545 buffer_path_abs,
1546 &language_server,
1547 &settings,
1548 cx,
1549 )
1550 .await
1551 .context("failed to format via language server")?
1552 };
1553
1554 if edits.is_empty() {
1555 zlog::trace!(logger => "No changes");
1556 continue;
1557 }
1558 extend_formatting_transaction(
1559 buffer,
1560 formatting_transaction_id,
1561 cx,
1562 |buffer, cx| {
1563 buffer.edit(edits, None, cx);
1564 },
1565 )?;
1566 }
1567 Formatter::CodeActions(code_actions) => {
1568 let logger = zlog::scoped!(logger => "code-actions");
1569 zlog::trace!(logger => "formatting");
1570 let _timer = zlog::time!(logger => "Formatting buffer using code actions");
1571
1572 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1573 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using code actions. Skipping");
1574 continue;
1575 };
1576 let code_action_kinds = code_actions
1577 .iter()
1578 .filter_map(|(action_kind, enabled)| {
1579 enabled.then_some(action_kind.clone().into())
1580 })
1581 .collect::<Vec<_>>();
1582 if code_action_kinds.is_empty() {
1583 zlog::trace!(logger => "No code action kinds enabled, skipping");
1584 continue;
1585 }
1586 zlog::trace!(logger => "Attempting to resolve code actions {:?}", &code_action_kinds);
1587
1588 let mut actions_and_servers = Vec::new();
1589
1590 for (index, (_, language_server)) in adapters_and_servers.iter().enumerate() {
1591 let actions_result = Self::get_server_code_actions_from_action_kinds(
1592 &lsp_store,
1593 language_server.server_id(),
1594 code_action_kinds.clone(),
1595 &buffer.handle,
1596 cx,
1597 )
1598 .await
1599 .with_context(
1600 || format!("Failed to resolve code actions with kinds {:?} for language server {}",
1601 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1602 language_server.name())
1603 );
1604 let Ok(actions) = actions_result else {
1605 // note: it may be better to set result to the error and break formatters here
1606 // but for now we try to execute the actions that we can resolve and skip the rest
1607 zlog::error!(
1608 logger =>
1609 "Failed to resolve code actions with kinds {:?} with language server {}",
1610 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1611 language_server.name()
1612 );
1613 continue;
1614 };
1615 for action in actions {
1616 actions_and_servers.push((action, index));
1617 }
1618 }
1619
1620 if actions_and_servers.is_empty() {
1621 zlog::warn!(logger => "No code actions were resolved, continuing");
1622 continue;
1623 }
1624
1625 'actions: for (mut action, server_index) in actions_and_servers {
1626 let server = &adapters_and_servers[server_index].1;
1627
1628 let describe_code_action = |action: &CodeAction| {
1629 format!(
1630 "code action '{}' with title \"{}\" on server {}",
1631 action
1632 .lsp_action
1633 .action_kind()
1634 .unwrap_or("unknown".into())
1635 .as_str(),
1636 action.lsp_action.title(),
1637 server.name(),
1638 )
1639 };
1640
1641 zlog::trace!(logger => "Executing {}", describe_code_action(&action));
1642
1643 if let Err(err) = Self::try_resolve_code_action(server, &mut action).await {
1644 zlog::error!(
1645 logger =>
1646 "Failed to resolve {}. Error: {}",
1647 describe_code_action(&action),
1648 err
1649 );
1650 continue;
1651 }
1652
1653 if let Some(edit) = action.lsp_action.edit().cloned() {
1654 // NOTE: code below duplicated from `Self::deserialize_workspace_edit`
1655 // but filters out and logs warnings for code actions that cause unreasonably
1656 // difficult handling on our part, such as:
1657 // - applying edits that call commands
1658 // which can result in arbitrary workspace edits being sent from the server that
1659 // have no way of being tied back to the command that initiated them (i.e. we
1660 // can't know which edits are part of the format request, or if the server is done sending
1661 // actions in response to the command)
1662 // - actions that create/delete/modify/rename files other than the one we are formatting
1663 // as we then would need to handle such changes correctly in the local history as well
1664 // as the remote history through the ProjectTransaction
1665 // - actions with snippet edits, as these simply don't make sense in the context of a format request
1666 // Supporting these actions is not impossible, but not supported as of yet.
1667 if edit.changes.is_none() && edit.document_changes.is_none() {
1668 zlog::trace!(
1669 logger =>
1670 "No changes for code action. Skipping {}",
1671 describe_code_action(&action),
1672 );
1673 continue;
1674 }
1675
1676 let mut operations = Vec::new();
1677 if let Some(document_changes) = edit.document_changes {
1678 match document_changes {
1679 lsp::DocumentChanges::Edits(edits) => operations.extend(
1680 edits.into_iter().map(lsp::DocumentChangeOperation::Edit),
1681 ),
1682 lsp::DocumentChanges::Operations(ops) => operations = ops,
1683 }
1684 } else if let Some(changes) = edit.changes {
1685 operations.extend(changes.into_iter().map(|(uri, edits)| {
1686 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1687 text_document:
1688 lsp::OptionalVersionedTextDocumentIdentifier {
1689 uri,
1690 version: None,
1691 },
1692 edits: edits.into_iter().map(Edit::Plain).collect(),
1693 })
1694 }));
1695 }
1696
1697 let mut edits = Vec::with_capacity(operations.len());
1698
1699 if operations.is_empty() {
1700 zlog::trace!(
1701 logger =>
1702 "No changes for code action. Skipping {}",
1703 describe_code_action(&action),
1704 );
1705 continue;
1706 }
1707 for operation in operations {
1708 let op = match operation {
1709 lsp::DocumentChangeOperation::Edit(op) => op,
1710 lsp::DocumentChangeOperation::Op(_) => {
1711 zlog::warn!(
1712 logger =>
1713 "Code actions which create, delete, or rename files are not supported on format. Skipping {}",
1714 describe_code_action(&action),
1715 );
1716 continue 'actions;
1717 }
1718 };
1719 let Ok(file_path) = op.text_document.uri.to_file_path() else {
1720 zlog::warn!(
1721 logger =>
1722 "Failed to convert URI '{:?}' to file path. Skipping {}",
1723 &op.text_document.uri,
1724 describe_code_action(&action),
1725 );
1726 continue 'actions;
1727 };
1728 if &file_path != buffer_path_abs {
1729 zlog::warn!(
1730 logger =>
1731 "File path '{:?}' does not match buffer path '{:?}'. Skipping {}",
1732 file_path,
1733 buffer_path_abs,
1734 describe_code_action(&action),
1735 );
1736 continue 'actions;
1737 }
1738
1739 let mut lsp_edits = Vec::new();
1740 for edit in op.edits {
1741 match edit {
1742 Edit::Plain(edit) => {
1743 if !lsp_edits.contains(&edit) {
1744 lsp_edits.push(edit);
1745 }
1746 }
1747 Edit::Annotated(edit) => {
1748 if !lsp_edits.contains(&edit.text_edit) {
1749 lsp_edits.push(edit.text_edit);
1750 }
1751 }
1752 Edit::Snippet(_) => {
1753 zlog::warn!(
1754 logger =>
1755 "Code actions which produce snippet edits are not supported during formatting. Skipping {}",
1756 describe_code_action(&action),
1757 );
1758 continue 'actions;
1759 }
1760 }
1761 }
1762 let edits_result = lsp_store
1763 .update(cx, |lsp_store, cx| {
1764 lsp_store.as_local_mut().unwrap().edits_from_lsp(
1765 &buffer.handle,
1766 lsp_edits,
1767 server.server_id(),
1768 op.text_document.version,
1769 cx,
1770 )
1771 })?
1772 .await;
1773 let Ok(resolved_edits) = edits_result else {
1774 zlog::warn!(
1775 logger =>
1776 "Failed to resolve edits from LSP for buffer {:?} while handling {}",
1777 buffer_path_abs.as_path(),
1778 describe_code_action(&action),
1779 );
1780 continue 'actions;
1781 };
1782 edits.extend(resolved_edits);
1783 }
1784
1785 if edits.is_empty() {
1786 zlog::warn!(logger => "No edits resolved from LSP");
1787 continue;
1788 }
1789
1790 extend_formatting_transaction(
1791 buffer,
1792 formatting_transaction_id,
1793 cx,
1794 |buffer, cx| {
1795 buffer.edit(edits, None, cx);
1796 },
1797 )?;
1798 }
1799
1800 if let Some(command) = action.lsp_action.command() {
1801 zlog::warn!(
1802 logger =>
1803 "Executing code action command '{}'. This may cause formatting to abort unnecessarily as well as splitting formatting into two entries in the undo history",
1804 &command.command,
1805 );
1806
1807 // bail early if command is invalid
1808 let server_capabilities = server.capabilities();
1809 let available_commands = server_capabilities
1810 .execute_command_provider
1811 .as_ref()
1812 .map(|options| options.commands.as_slice())
1813 .unwrap_or_default();
1814 if !available_commands.contains(&command.command) {
1815 zlog::warn!(
1816 logger =>
1817 "Cannot execute a command {} not listed in the language server capabilities of server {}",
1818 command.command,
1819 server.name(),
1820 );
1821 continue;
1822 }
1823
1824 // noop so we just ensure buffer hasn't been edited since resolving code actions
1825 extend_formatting_transaction(
1826 buffer,
1827 formatting_transaction_id,
1828 cx,
1829 |_, _| {},
1830 )?;
1831 zlog::info!(logger => "Executing command {}", &command.command);
1832
1833 lsp_store.update(cx, |this, _| {
1834 this.as_local_mut()
1835 .unwrap()
1836 .last_workspace_edits_by_language_server
1837 .remove(&server.server_id());
1838 })?;
1839
1840 let execute_command_result = server
1841 .request::<lsp::request::ExecuteCommand>(
1842 lsp::ExecuteCommandParams {
1843 command: command.command.clone(),
1844 arguments: command.arguments.clone().unwrap_or_default(),
1845 ..Default::default()
1846 },
1847 )
1848 .await
1849 .into_response();
1850
1851 if execute_command_result.is_err() {
1852 zlog::error!(
1853 logger =>
1854 "Failed to execute command '{}' as part of {}",
1855 &command.command,
1856 describe_code_action(&action),
1857 );
1858 continue 'actions;
1859 }
1860
1861 let mut project_transaction_command =
1862 lsp_store.update(cx, |this, _| {
1863 this.as_local_mut()
1864 .unwrap()
1865 .last_workspace_edits_by_language_server
1866 .remove(&server.server_id())
1867 .unwrap_or_default()
1868 })?;
1869
1870 if let Some(transaction) =
1871 project_transaction_command.0.remove(&buffer.handle)
1872 {
1873 zlog::trace!(
1874 logger =>
1875 "Successfully captured {} edits that resulted from command {}",
1876 transaction.edit_ids.len(),
1877 &command.command,
1878 );
1879 let transaction_id_project_transaction = transaction.id;
1880 buffer.handle.update(cx, |buffer, _| {
1881 // it may have been removed from history if push_to_history was
1882 // false in deserialize_workspace_edit. If so push it so we
1883 // can merge it with the format transaction
1884 // and pop the combined transaction off the history stack
1885 // later if push_to_history is false
1886 if buffer.get_transaction(transaction.id).is_none() {
1887 buffer.push_transaction(transaction, Instant::now());
1888 }
1889 buffer.merge_transactions(
1890 transaction_id_project_transaction,
1891 formatting_transaction_id,
1892 );
1893 })?;
1894 }
1895
1896 if !project_transaction_command.0.is_empty() {
1897 let extra_buffers = project_transaction_command
1898 .0
1899 .keys()
1900 .filter_map(|buffer_handle| {
1901 buffer_handle
1902 .read_with(cx, |b, cx| b.project_path(cx))
1903 .ok()
1904 .flatten()
1905 })
1906 .map(|p| p.path.to_sanitized_string())
1907 .join(", ");
1908 zlog::warn!(
1909 logger =>
1910 "Unexpected edits to buffers other than the buffer actively being formatted due to command {}. Impacted buffers: [{}].",
1911 &command.command,
1912 extra_buffers,
1913 );
1914 // NOTE: if this case is hit, the proper thing to do is to for each buffer, merge the extra transaction
1915 // into the existing transaction in project_transaction if there is one, and if there isn't one in project_transaction,
1916 // add it so it's included, and merge it into the format transaction when its created later
1917 }
1918 }
1919 }
1920 }
1921 }
1922 }
1923
1924 Ok(())
1925 }
1926
1927 pub async fn format_ranges_via_lsp(
1928 this: &WeakEntity<LspStore>,
1929 buffer_handle: &Entity<Buffer>,
1930 ranges: &[Range<Anchor>],
1931 abs_path: &Path,
1932 language_server: &Arc<LanguageServer>,
1933 settings: &LanguageSettings,
1934 cx: &mut AsyncApp,
1935 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1936 let capabilities = &language_server.capabilities();
1937 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1938 if range_formatting_provider.map_or(false, |provider| provider == &OneOf::Left(false)) {
1939 anyhow::bail!(
1940 "{} language server does not support range formatting",
1941 language_server.name()
1942 );
1943 }
1944
1945 let uri = file_path_to_lsp_url(abs_path)?;
1946 let text_document = lsp::TextDocumentIdentifier::new(uri);
1947
1948 let lsp_edits = {
1949 let mut lsp_ranges = Vec::new();
1950 this.update(cx, |_this, cx| {
1951 // TODO(#22930): In the case of formatting multibuffer selections, this buffer may
1952 // not have been sent to the language server. This seems like a fairly systemic
1953 // issue, though, the resolution probably is not specific to formatting.
1954 //
1955 // TODO: Instead of using current snapshot, should use the latest snapshot sent to
1956 // LSP.
1957 let snapshot = buffer_handle.read(cx).snapshot();
1958 for range in ranges {
1959 lsp_ranges.push(range_to_lsp(range.to_point_utf16(&snapshot))?);
1960 }
1961 anyhow::Ok(())
1962 })??;
1963
1964 let mut edits = None;
1965 for range in lsp_ranges {
1966 if let Some(mut edit) = language_server
1967 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1968 text_document: text_document.clone(),
1969 range,
1970 options: lsp_command::lsp_formatting_options(settings),
1971 work_done_progress_params: Default::default(),
1972 })
1973 .await
1974 .into_response()?
1975 {
1976 edits.get_or_insert_with(Vec::new).append(&mut edit);
1977 }
1978 }
1979 edits
1980 };
1981
1982 if let Some(lsp_edits) = lsp_edits {
1983 this.update(cx, |this, cx| {
1984 this.as_local_mut().unwrap().edits_from_lsp(
1985 &buffer_handle,
1986 lsp_edits,
1987 language_server.server_id(),
1988 None,
1989 cx,
1990 )
1991 })?
1992 .await
1993 } else {
1994 Ok(Vec::with_capacity(0))
1995 }
1996 }
1997
1998 async fn format_via_lsp(
1999 this: &WeakEntity<LspStore>,
2000 buffer: &Entity<Buffer>,
2001 abs_path: &Path,
2002 language_server: &Arc<LanguageServer>,
2003 settings: &LanguageSettings,
2004 cx: &mut AsyncApp,
2005 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
2006 let logger = zlog::scoped!("lsp_format");
2007 zlog::info!(logger => "Formatting via LSP");
2008
2009 let uri = file_path_to_lsp_url(abs_path)?;
2010 let text_document = lsp::TextDocumentIdentifier::new(uri);
2011 let capabilities = &language_server.capabilities();
2012
2013 let formatting_provider = capabilities.document_formatting_provider.as_ref();
2014 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
2015
2016 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
2017 let _timer = zlog::time!(logger => "format-full");
2018 language_server
2019 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2020 text_document,
2021 options: lsp_command::lsp_formatting_options(settings),
2022 work_done_progress_params: Default::default(),
2023 })
2024 .await
2025 .into_response()?
2026 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
2027 let _timer = zlog::time!(logger => "format-range");
2028 let buffer_start = lsp::Position::new(0, 0);
2029 let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
2030 language_server
2031 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2032 text_document: text_document.clone(),
2033 range: lsp::Range::new(buffer_start, buffer_end),
2034 options: lsp_command::lsp_formatting_options(settings),
2035 work_done_progress_params: Default::default(),
2036 })
2037 .await
2038 .into_response()?
2039 } else {
2040 None
2041 };
2042
2043 if let Some(lsp_edits) = lsp_edits {
2044 this.update(cx, |this, cx| {
2045 this.as_local_mut().unwrap().edits_from_lsp(
2046 buffer,
2047 lsp_edits,
2048 language_server.server_id(),
2049 None,
2050 cx,
2051 )
2052 })?
2053 .await
2054 } else {
2055 Ok(Vec::with_capacity(0))
2056 }
2057 }
2058
2059 async fn format_via_external_command(
2060 buffer: &FormattableBuffer,
2061 command: &str,
2062 arguments: Option<&[String]>,
2063 cx: &mut AsyncApp,
2064 ) -> Result<Option<Diff>> {
2065 let working_dir_path = buffer.handle.update(cx, |buffer, cx| {
2066 let file = File::from_dyn(buffer.file())?;
2067 let worktree = file.worktree.read(cx);
2068 let mut worktree_path = worktree.abs_path().to_path_buf();
2069 if worktree.root_entry()?.is_file() {
2070 worktree_path.pop();
2071 }
2072 Some(worktree_path)
2073 })?;
2074
2075 let mut child = util::command::new_smol_command(command);
2076
2077 if let Some(buffer_env) = buffer.env.as_ref() {
2078 child.envs(buffer_env);
2079 }
2080
2081 if let Some(working_dir_path) = working_dir_path {
2082 child.current_dir(working_dir_path);
2083 }
2084
2085 if let Some(arguments) = arguments {
2086 child.args(arguments.iter().map(|arg| {
2087 if let Some(buffer_abs_path) = buffer.abs_path.as_ref() {
2088 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2089 } else {
2090 arg.replace("{buffer_path}", "Untitled")
2091 }
2092 }));
2093 }
2094
2095 let mut child = child
2096 .stdin(smol::process::Stdio::piped())
2097 .stdout(smol::process::Stdio::piped())
2098 .stderr(smol::process::Stdio::piped())
2099 .spawn()?;
2100
2101 let stdin = child.stdin.as_mut().context("failed to acquire stdin")?;
2102 let text = buffer
2103 .handle
2104 .read_with(cx, |buffer, _| buffer.as_rope().clone())?;
2105 for chunk in text.chunks() {
2106 stdin.write_all(chunk.as_bytes()).await?;
2107 }
2108 stdin.flush().await?;
2109
2110 let output = child.output().await?;
2111 anyhow::ensure!(
2112 output.status.success(),
2113 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
2114 output.status.code(),
2115 String::from_utf8_lossy(&output.stdout),
2116 String::from_utf8_lossy(&output.stderr),
2117 );
2118
2119 let stdout = String::from_utf8(output.stdout)?;
2120 Ok(Some(
2121 buffer
2122 .handle
2123 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
2124 .await,
2125 ))
2126 }
2127
2128 async fn try_resolve_code_action(
2129 lang_server: &LanguageServer,
2130 action: &mut CodeAction,
2131 ) -> anyhow::Result<()> {
2132 match &mut action.lsp_action {
2133 LspAction::Action(lsp_action) => {
2134 if !action.resolved
2135 && GetCodeActions::can_resolve_actions(&lang_server.capabilities())
2136 && lsp_action.data.is_some()
2137 && (lsp_action.command.is_none() || lsp_action.edit.is_none())
2138 {
2139 *lsp_action = Box::new(
2140 lang_server
2141 .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
2142 .await
2143 .into_response()?,
2144 );
2145 }
2146 }
2147 LspAction::CodeLens(lens) => {
2148 if !action.resolved && GetCodeLens::can_resolve_lens(&lang_server.capabilities()) {
2149 *lens = lang_server
2150 .request::<lsp::request::CodeLensResolve>(lens.clone())
2151 .await
2152 .into_response()?;
2153 }
2154 }
2155 LspAction::Command(_) => {}
2156 }
2157
2158 action.resolved = true;
2159 anyhow::Ok(())
2160 }
2161
2162 fn initialize_buffer(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<LspStore>) {
2163 let buffer = buffer_handle.read(cx);
2164
2165 let file = buffer.file().cloned();
2166 let Some(file) = File::from_dyn(file.as_ref()) else {
2167 return;
2168 };
2169 if !file.is_local() {
2170 return;
2171 }
2172
2173 let worktree_id = file.worktree_id(cx);
2174 let language = buffer.language().cloned();
2175
2176 if let Some(diagnostics) = self.diagnostics.get(&worktree_id) {
2177 for (server_id, diagnostics) in
2178 diagnostics.get(file.path()).cloned().unwrap_or_default()
2179 {
2180 self.update_buffer_diagnostics(
2181 buffer_handle,
2182 server_id,
2183 None,
2184 None,
2185 diagnostics,
2186 Vec::new(),
2187 cx,
2188 )
2189 .log_err();
2190 }
2191 }
2192 let Some(language) = language else {
2193 return;
2194 };
2195 for adapter in self.languages.lsp_adapters(&language.name()) {
2196 let servers = self
2197 .language_server_ids
2198 .get(&(worktree_id, adapter.name.clone()));
2199 if let Some(server_ids) = servers {
2200 for server_id in server_ids {
2201 let server = self
2202 .language_servers
2203 .get(server_id)
2204 .and_then(|server_state| {
2205 if let LanguageServerState::Running { server, .. } = server_state {
2206 Some(server.clone())
2207 } else {
2208 None
2209 }
2210 });
2211 let server = match server {
2212 Some(server) => server,
2213 None => continue,
2214 };
2215
2216 buffer_handle.update(cx, |buffer, cx| {
2217 buffer.set_completion_triggers(
2218 server.server_id(),
2219 server
2220 .capabilities()
2221 .completion_provider
2222 .as_ref()
2223 .and_then(|provider| {
2224 provider
2225 .trigger_characters
2226 .as_ref()
2227 .map(|characters| characters.iter().cloned().collect())
2228 })
2229 .unwrap_or_default(),
2230 cx,
2231 );
2232 });
2233 }
2234 }
2235 }
2236 }
2237
2238 pub(crate) fn reset_buffer(&mut self, buffer: &Entity<Buffer>, old_file: &File, cx: &mut App) {
2239 buffer.update(cx, |buffer, cx| {
2240 let Some(language) = buffer.language() else {
2241 return;
2242 };
2243 let path = ProjectPath {
2244 worktree_id: old_file.worktree_id(cx),
2245 path: old_file.path.clone(),
2246 };
2247 for server_id in self.language_server_ids_for_project_path(path, language, cx) {
2248 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
2249 buffer.set_completion_triggers(server_id, Default::default(), cx);
2250 }
2251 });
2252 }
2253
2254 fn update_buffer_diagnostics(
2255 &mut self,
2256 buffer: &Entity<Buffer>,
2257 server_id: LanguageServerId,
2258 result_id: Option<String>,
2259 version: Option<i32>,
2260 new_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2261 reused_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2262 cx: &mut Context<LspStore>,
2263 ) -> Result<()> {
2264 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2265 Ordering::Equal
2266 .then_with(|| b.is_primary.cmp(&a.is_primary))
2267 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2268 .then_with(|| a.severity.cmp(&b.severity))
2269 .then_with(|| a.message.cmp(&b.message))
2270 }
2271
2272 let mut diagnostics = Vec::with_capacity(new_diagnostics.len() + reused_diagnostics.len());
2273 diagnostics.extend(new_diagnostics.into_iter().map(|d| (true, d)));
2274 diagnostics.extend(reused_diagnostics.into_iter().map(|d| (false, d)));
2275
2276 diagnostics.sort_unstable_by(|(_, a), (_, b)| {
2277 Ordering::Equal
2278 .then_with(|| a.range.start.cmp(&b.range.start))
2279 .then_with(|| b.range.end.cmp(&a.range.end))
2280 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2281 });
2282
2283 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
2284
2285 let edits_since_save = std::cell::LazyCell::new(|| {
2286 let saved_version = buffer.read(cx).saved_version();
2287 Patch::new(snapshot.edits_since::<PointUtf16>(saved_version).collect())
2288 });
2289
2290 let mut sanitized_diagnostics = Vec::with_capacity(diagnostics.len());
2291
2292 for (new_diagnostic, entry) in diagnostics {
2293 let start;
2294 let end;
2295 if new_diagnostic && entry.diagnostic.is_disk_based {
2296 // Some diagnostics are based on files on disk instead of buffers'
2297 // current contents. Adjust these diagnostics' ranges to reflect
2298 // any unsaved edits.
2299 // Do not alter the reused ones though, as their coordinates were stored as anchors
2300 // and were properly adjusted on reuse.
2301 start = Unclipped((*edits_since_save).old_to_new(entry.range.start.0));
2302 end = Unclipped((*edits_since_save).old_to_new(entry.range.end.0));
2303 } else {
2304 start = entry.range.start;
2305 end = entry.range.end;
2306 }
2307
2308 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2309 ..snapshot.clip_point_utf16(end, Bias::Right);
2310
2311 // Expand empty ranges by one codepoint
2312 if range.start == range.end {
2313 // This will be go to the next boundary when being clipped
2314 range.end.column += 1;
2315 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2316 if range.start == range.end && range.end.column > 0 {
2317 range.start.column -= 1;
2318 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
2319 }
2320 }
2321
2322 sanitized_diagnostics.push(DiagnosticEntry {
2323 range,
2324 diagnostic: entry.diagnostic,
2325 });
2326 }
2327 drop(edits_since_save);
2328
2329 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2330 buffer.update(cx, |buffer, cx| {
2331 if let Some(abs_path) = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)) {
2332 self.buffer_pull_diagnostics_result_ids
2333 .entry(server_id)
2334 .or_default()
2335 .insert(abs_path, result_id);
2336 }
2337
2338 buffer.update_diagnostics(server_id, set, cx)
2339 });
2340
2341 Ok(())
2342 }
2343
2344 fn register_buffer_with_language_servers(
2345 &mut self,
2346 buffer_handle: &Entity<Buffer>,
2347 only_register_servers: HashSet<LanguageServerSelector>,
2348 cx: &mut Context<LspStore>,
2349 ) {
2350 let buffer = buffer_handle.read(cx);
2351 let buffer_id = buffer.remote_id();
2352
2353 let Some(file) = File::from_dyn(buffer.file()) else {
2354 return;
2355 };
2356 if !file.is_local() {
2357 return;
2358 }
2359
2360 let abs_path = file.abs_path(cx);
2361 let Some(uri) = file_path_to_lsp_url(&abs_path).log_err() else {
2362 return;
2363 };
2364 let initial_snapshot = buffer.text_snapshot();
2365 let worktree_id = file.worktree_id(cx);
2366
2367 let Some(language) = buffer.language().cloned() else {
2368 return;
2369 };
2370 let path: Arc<Path> = file
2371 .path()
2372 .parent()
2373 .map(Arc::from)
2374 .unwrap_or_else(|| file.path().clone());
2375 let Some(worktree) = self
2376 .worktree_store
2377 .read(cx)
2378 .worktree_for_id(worktree_id, cx)
2379 else {
2380 return;
2381 };
2382 let language_name = language.name();
2383 let (reused, delegate, servers) = self
2384 .lsp_tree
2385 .update(cx, |lsp_tree, cx| {
2386 self.reuse_existing_language_server(lsp_tree, &worktree, &language_name, cx)
2387 })
2388 .map(|(delegate, servers)| (true, delegate, servers))
2389 .unwrap_or_else(|| {
2390 let lsp_delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
2391 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
2392 let servers = self
2393 .lsp_tree
2394 .clone()
2395 .update(cx, |language_server_tree, cx| {
2396 language_server_tree
2397 .get(
2398 ProjectPath { worktree_id, path },
2399 AdapterQuery::Language(&language.name()),
2400 delegate.clone(),
2401 cx,
2402 )
2403 .collect::<Vec<_>>()
2404 });
2405 (false, lsp_delegate, servers)
2406 });
2407 let servers_and_adapters = servers
2408 .into_iter()
2409 .filter_map(|server_node| {
2410 if reused && server_node.server_id().is_none() {
2411 return None;
2412 }
2413 if !only_register_servers.is_empty() {
2414 if let Some(server_id) = server_node.server_id() {
2415 if !only_register_servers.contains(&LanguageServerSelector::Id(server_id)) {
2416 return None;
2417 }
2418 }
2419 if let Some(name) = server_node.name() {
2420 if !only_register_servers.contains(&LanguageServerSelector::Name(name)) {
2421 return None;
2422 }
2423 }
2424 }
2425
2426 let server_id = server_node.server_id_or_init(
2427 |LaunchDisposition {
2428 server_name,
2429
2430 path,
2431 settings,
2432 }| {
2433 let server_id =
2434 {
2435 let uri = Url::from_file_path(
2436 worktree.read(cx).abs_path().join(&path.path),
2437 );
2438 let key = (worktree_id, server_name.clone());
2439 if !self.language_server_ids.contains_key(&key) {
2440 let language_name = language.name();
2441 let adapter = self.languages
2442 .lsp_adapters(&language_name)
2443 .into_iter()
2444 .find(|adapter| &adapter.name() == server_name)
2445 .expect("To find LSP adapter");
2446 self.start_language_server(
2447 &worktree,
2448 delegate.clone(),
2449 adapter,
2450 settings,
2451 cx,
2452 );
2453 }
2454 if let Some(server_ids) = self
2455 .language_server_ids
2456 .get(&key)
2457 {
2458 debug_assert_eq!(server_ids.len(), 1);
2459 let server_id = server_ids.iter().cloned().next().unwrap();
2460 if let Some(state) = self.language_servers.get(&server_id) {
2461 if let Ok(uri) = uri {
2462 state.add_workspace_folder(uri);
2463 };
2464 }
2465 server_id
2466 } else {
2467 unreachable!("Language server ID should be available, as it's registered on demand")
2468 }
2469
2470 };
2471 let lsp_store = self.weak.clone();
2472 let server_name = server_node.name();
2473 let buffer_abs_path = abs_path.to_string_lossy().to_string();
2474 cx.defer(move |cx| {
2475 lsp_store.update(cx, |_, cx| cx.emit(LspStoreEvent::LanguageServerUpdate {
2476 language_server_id: server_id,
2477 name: server_name,
2478 message: proto::update_language_server::Variant::RegisteredForBuffer(proto::RegisteredForBuffer {
2479 buffer_abs_path,
2480 })
2481 })).ok();
2482 });
2483 server_id
2484 },
2485 )?;
2486 let server_state = self.language_servers.get(&server_id)?;
2487 if let LanguageServerState::Running { server, adapter, .. } = server_state {
2488 Some((server.clone(), adapter.clone()))
2489 } else {
2490 None
2491 }
2492 })
2493 .collect::<Vec<_>>();
2494 for (server, adapter) in servers_and_adapters {
2495 buffer_handle.update(cx, |buffer, cx| {
2496 buffer.set_completion_triggers(
2497 server.server_id(),
2498 server
2499 .capabilities()
2500 .completion_provider
2501 .as_ref()
2502 .and_then(|provider| {
2503 provider
2504 .trigger_characters
2505 .as_ref()
2506 .map(|characters| characters.iter().cloned().collect())
2507 })
2508 .unwrap_or_default(),
2509 cx,
2510 );
2511 });
2512
2513 let snapshot = LspBufferSnapshot {
2514 version: 0,
2515 snapshot: initial_snapshot.clone(),
2516 };
2517
2518 self.buffer_snapshots
2519 .entry(buffer_id)
2520 .or_default()
2521 .entry(server.server_id())
2522 .or_insert_with(|| {
2523 server.register_buffer(
2524 uri.clone(),
2525 adapter.language_id(&language.name()),
2526 0,
2527 initial_snapshot.text(),
2528 );
2529
2530 vec![snapshot]
2531 });
2532
2533 self.buffers_opened_in_servers
2534 .entry(buffer_id)
2535 .or_default()
2536 .insert(server.server_id());
2537 cx.emit(LspStoreEvent::LanguageServerUpdate {
2538 language_server_id: server.server_id(),
2539 name: None,
2540 message: proto::update_language_server::Variant::RegisteredForBuffer(
2541 proto::RegisteredForBuffer {
2542 buffer_abs_path: abs_path.to_string_lossy().to_string(),
2543 },
2544 ),
2545 });
2546 }
2547 }
2548
2549 fn reuse_existing_language_server(
2550 &self,
2551 server_tree: &mut LanguageServerTree,
2552 worktree: &Entity<Worktree>,
2553 language_name: &LanguageName,
2554 cx: &mut App,
2555 ) -> Option<(Arc<LocalLspAdapterDelegate>, Vec<LanguageServerTreeNode>)> {
2556 if worktree.read(cx).is_visible() {
2557 return None;
2558 }
2559
2560 let worktree_store = self.worktree_store.read(cx);
2561 let servers = server_tree
2562 .instances
2563 .iter()
2564 .filter(|(worktree_id, _)| {
2565 worktree_store
2566 .worktree_for_id(**worktree_id, cx)
2567 .is_some_and(|worktree| worktree.read(cx).is_visible())
2568 })
2569 .flat_map(|(worktree_id, servers)| {
2570 servers
2571 .roots
2572 .iter()
2573 .flat_map(|(_, language_servers)| language_servers)
2574 .map(move |(_, (server_node, server_languages))| {
2575 (worktree_id, server_node, server_languages)
2576 })
2577 .filter(|(_, _, server_languages)| server_languages.contains(language_name))
2578 .map(|(worktree_id, server_node, _)| {
2579 (
2580 *worktree_id,
2581 LanguageServerTreeNode::from(Arc::downgrade(server_node)),
2582 )
2583 })
2584 })
2585 .fold(HashMap::default(), |mut acc, (worktree_id, server_node)| {
2586 acc.entry(worktree_id)
2587 .or_insert_with(Vec::new)
2588 .push(server_node);
2589 acc
2590 })
2591 .into_values()
2592 .max_by_key(|servers| servers.len())?;
2593
2594 for server_node in &servers {
2595 server_tree.register_reused(
2596 worktree.read(cx).id(),
2597 language_name.clone(),
2598 server_node.clone(),
2599 );
2600 }
2601
2602 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, worktree, cx);
2603 Some((delegate, servers))
2604 }
2605
2606 pub(crate) fn unregister_old_buffer_from_language_servers(
2607 &mut self,
2608 buffer: &Entity<Buffer>,
2609 old_file: &File,
2610 cx: &mut App,
2611 ) {
2612 let old_path = match old_file.as_local() {
2613 Some(local) => local.abs_path(cx),
2614 None => return,
2615 };
2616
2617 let Ok(file_url) = lsp::Url::from_file_path(old_path.as_path()) else {
2618 debug_panic!(
2619 "`{}` is not parseable as an URI",
2620 old_path.to_string_lossy()
2621 );
2622 return;
2623 };
2624 self.unregister_buffer_from_language_servers(buffer, &file_url, cx);
2625 }
2626
2627 pub(crate) fn unregister_buffer_from_language_servers(
2628 &mut self,
2629 buffer: &Entity<Buffer>,
2630 file_url: &lsp::Url,
2631 cx: &mut App,
2632 ) {
2633 buffer.update(cx, |buffer, cx| {
2634 let _ = self.buffer_snapshots.remove(&buffer.remote_id());
2635
2636 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2637 language_server.unregister_buffer(file_url.clone());
2638 }
2639 });
2640 }
2641
2642 fn buffer_snapshot_for_lsp_version(
2643 &mut self,
2644 buffer: &Entity<Buffer>,
2645 server_id: LanguageServerId,
2646 version: Option<i32>,
2647 cx: &App,
2648 ) -> Result<TextBufferSnapshot> {
2649 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
2650
2651 if let Some(version) = version {
2652 let buffer_id = buffer.read(cx).remote_id();
2653 let snapshots = if let Some(snapshots) = self
2654 .buffer_snapshots
2655 .get_mut(&buffer_id)
2656 .and_then(|m| m.get_mut(&server_id))
2657 {
2658 snapshots
2659 } else if version == 0 {
2660 // Some language servers report version 0 even if the buffer hasn't been opened yet.
2661 // We detect this case and treat it as if the version was `None`.
2662 return Ok(buffer.read(cx).text_snapshot());
2663 } else {
2664 anyhow::bail!("no snapshots found for buffer {buffer_id} and server {server_id}");
2665 };
2666
2667 let found_snapshot = snapshots
2668 .binary_search_by_key(&version, |e| e.version)
2669 .map(|ix| snapshots[ix].snapshot.clone())
2670 .map_err(|_| {
2671 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
2672 })?;
2673
2674 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
2675 Ok(found_snapshot)
2676 } else {
2677 Ok((buffer.read(cx)).text_snapshot())
2678 }
2679 }
2680
2681 async fn get_server_code_actions_from_action_kinds(
2682 lsp_store: &WeakEntity<LspStore>,
2683 language_server_id: LanguageServerId,
2684 code_action_kinds: Vec<lsp::CodeActionKind>,
2685 buffer: &Entity<Buffer>,
2686 cx: &mut AsyncApp,
2687 ) -> Result<Vec<CodeAction>> {
2688 let actions = lsp_store
2689 .update(cx, move |this, cx| {
2690 let request = GetCodeActions {
2691 range: text::Anchor::MIN..text::Anchor::MAX,
2692 kinds: Some(code_action_kinds),
2693 };
2694 let server = LanguageServerToQuery::Other(language_server_id);
2695 this.request_lsp(buffer.clone(), server, request, cx)
2696 })?
2697 .await?;
2698 return Ok(actions);
2699 }
2700
2701 pub async fn execute_code_actions_on_server(
2702 lsp_store: &WeakEntity<LspStore>,
2703 language_server: &Arc<LanguageServer>,
2704 lsp_adapter: &Arc<CachedLspAdapter>,
2705 actions: Vec<CodeAction>,
2706 push_to_history: bool,
2707 project_transaction: &mut ProjectTransaction,
2708 cx: &mut AsyncApp,
2709 ) -> anyhow::Result<()> {
2710 for mut action in actions {
2711 Self::try_resolve_code_action(language_server, &mut action)
2712 .await
2713 .context("resolving a formatting code action")?;
2714
2715 if let Some(edit) = action.lsp_action.edit() {
2716 if edit.changes.is_none() && edit.document_changes.is_none() {
2717 continue;
2718 }
2719
2720 let new = Self::deserialize_workspace_edit(
2721 lsp_store.upgrade().context("project dropped")?,
2722 edit.clone(),
2723 push_to_history,
2724 lsp_adapter.clone(),
2725 language_server.clone(),
2726 cx,
2727 )
2728 .await?;
2729 project_transaction.0.extend(new.0);
2730 }
2731
2732 if let Some(command) = action.lsp_action.command() {
2733 let server_capabilities = language_server.capabilities();
2734 let available_commands = server_capabilities
2735 .execute_command_provider
2736 .as_ref()
2737 .map(|options| options.commands.as_slice())
2738 .unwrap_or_default();
2739 if available_commands.contains(&command.command) {
2740 lsp_store.update(cx, |lsp_store, _| {
2741 if let LspStoreMode::Local(mode) = &mut lsp_store.mode {
2742 mode.last_workspace_edits_by_language_server
2743 .remove(&language_server.server_id());
2744 }
2745 })?;
2746
2747 language_server
2748 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
2749 command: command.command.clone(),
2750 arguments: command.arguments.clone().unwrap_or_default(),
2751 ..Default::default()
2752 })
2753 .await
2754 .into_response()
2755 .context("execute command")?;
2756
2757 lsp_store.update(cx, |this, _| {
2758 if let LspStoreMode::Local(mode) = &mut this.mode {
2759 project_transaction.0.extend(
2760 mode.last_workspace_edits_by_language_server
2761 .remove(&language_server.server_id())
2762 .unwrap_or_default()
2763 .0,
2764 )
2765 }
2766 })?;
2767 } else {
2768 log::warn!(
2769 "Cannot execute a command {} not listed in the language server capabilities",
2770 command.command
2771 )
2772 }
2773 }
2774 }
2775 return Ok(());
2776 }
2777
2778 pub async fn deserialize_text_edits(
2779 this: Entity<LspStore>,
2780 buffer_to_edit: Entity<Buffer>,
2781 edits: Vec<lsp::TextEdit>,
2782 push_to_history: bool,
2783 _: Arc<CachedLspAdapter>,
2784 language_server: Arc<LanguageServer>,
2785 cx: &mut AsyncApp,
2786 ) -> Result<Option<Transaction>> {
2787 let edits = this
2788 .update(cx, |this, cx| {
2789 this.as_local_mut().unwrap().edits_from_lsp(
2790 &buffer_to_edit,
2791 edits,
2792 language_server.server_id(),
2793 None,
2794 cx,
2795 )
2796 })?
2797 .await?;
2798
2799 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2800 buffer.finalize_last_transaction();
2801 buffer.start_transaction();
2802 for (range, text) in edits {
2803 buffer.edit([(range, text)], None, cx);
2804 }
2805
2806 if buffer.end_transaction(cx).is_some() {
2807 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2808 if !push_to_history {
2809 buffer.forget_transaction(transaction.id);
2810 }
2811 Some(transaction)
2812 } else {
2813 None
2814 }
2815 })?;
2816
2817 Ok(transaction)
2818 }
2819
2820 #[allow(clippy::type_complexity)]
2821 pub(crate) fn edits_from_lsp(
2822 &mut self,
2823 buffer: &Entity<Buffer>,
2824 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
2825 server_id: LanguageServerId,
2826 version: Option<i32>,
2827 cx: &mut Context<LspStore>,
2828 ) -> Task<Result<Vec<(Range<Anchor>, Arc<str>)>>> {
2829 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
2830 cx.background_spawn(async move {
2831 let snapshot = snapshot?;
2832 let mut lsp_edits = lsp_edits
2833 .into_iter()
2834 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
2835 .collect::<Vec<_>>();
2836
2837 lsp_edits.sort_by_key(|(range, _)| (range.start, range.end));
2838
2839 let mut lsp_edits = lsp_edits.into_iter().peekable();
2840 let mut edits = Vec::new();
2841 while let Some((range, mut new_text)) = lsp_edits.next() {
2842 // Clip invalid ranges provided by the language server.
2843 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
2844 ..snapshot.clip_point_utf16(range.end, Bias::Left);
2845
2846 // Combine any LSP edits that are adjacent.
2847 //
2848 // Also, combine LSP edits that are separated from each other by only
2849 // a newline. This is important because for some code actions,
2850 // Rust-analyzer rewrites the entire buffer via a series of edits that
2851 // are separated by unchanged newline characters.
2852 //
2853 // In order for the diffing logic below to work properly, any edits that
2854 // cancel each other out must be combined into one.
2855 while let Some((next_range, next_text)) = lsp_edits.peek() {
2856 if next_range.start.0 > range.end {
2857 if next_range.start.0.row > range.end.row + 1
2858 || next_range.start.0.column > 0
2859 || snapshot.clip_point_utf16(
2860 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
2861 Bias::Left,
2862 ) > range.end
2863 {
2864 break;
2865 }
2866 new_text.push('\n');
2867 }
2868 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
2869 new_text.push_str(next_text);
2870 lsp_edits.next();
2871 }
2872
2873 // For multiline edits, perform a diff of the old and new text so that
2874 // we can identify the changes more precisely, preserving the locations
2875 // of any anchors positioned in the unchanged regions.
2876 if range.end.row > range.start.row {
2877 let offset = range.start.to_offset(&snapshot);
2878 let old_text = snapshot.text_for_range(range).collect::<String>();
2879 let range_edits = language::text_diff(old_text.as_str(), &new_text);
2880 edits.extend(range_edits.into_iter().map(|(range, replacement)| {
2881 (
2882 snapshot.anchor_after(offset + range.start)
2883 ..snapshot.anchor_before(offset + range.end),
2884 replacement,
2885 )
2886 }));
2887 } else if range.end == range.start {
2888 let anchor = snapshot.anchor_after(range.start);
2889 edits.push((anchor..anchor, new_text.into()));
2890 } else {
2891 let edit_start = snapshot.anchor_after(range.start);
2892 let edit_end = snapshot.anchor_before(range.end);
2893 edits.push((edit_start..edit_end, new_text.into()));
2894 }
2895 }
2896
2897 Ok(edits)
2898 })
2899 }
2900
2901 pub(crate) async fn deserialize_workspace_edit(
2902 this: Entity<LspStore>,
2903 edit: lsp::WorkspaceEdit,
2904 push_to_history: bool,
2905 lsp_adapter: Arc<CachedLspAdapter>,
2906 language_server: Arc<LanguageServer>,
2907 cx: &mut AsyncApp,
2908 ) -> Result<ProjectTransaction> {
2909 let fs = this.read_with(cx, |this, _| this.as_local().unwrap().fs.clone())?;
2910
2911 let mut operations = Vec::new();
2912 if let Some(document_changes) = edit.document_changes {
2913 match document_changes {
2914 lsp::DocumentChanges::Edits(edits) => {
2915 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2916 }
2917 lsp::DocumentChanges::Operations(ops) => operations = ops,
2918 }
2919 } else if let Some(changes) = edit.changes {
2920 operations.extend(changes.into_iter().map(|(uri, edits)| {
2921 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2922 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2923 uri,
2924 version: None,
2925 },
2926 edits: edits.into_iter().map(Edit::Plain).collect(),
2927 })
2928 }));
2929 }
2930
2931 let mut project_transaction = ProjectTransaction::default();
2932 for operation in operations {
2933 match operation {
2934 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2935 let abs_path = op
2936 .uri
2937 .to_file_path()
2938 .map_err(|()| anyhow!("can't convert URI to path"))?;
2939
2940 if let Some(parent_path) = abs_path.parent() {
2941 fs.create_dir(parent_path).await?;
2942 }
2943 if abs_path.ends_with("/") {
2944 fs.create_dir(&abs_path).await?;
2945 } else {
2946 fs.create_file(
2947 &abs_path,
2948 op.options
2949 .map(|options| fs::CreateOptions {
2950 overwrite: options.overwrite.unwrap_or(false),
2951 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2952 })
2953 .unwrap_or_default(),
2954 )
2955 .await?;
2956 }
2957 }
2958
2959 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2960 let source_abs_path = op
2961 .old_uri
2962 .to_file_path()
2963 .map_err(|()| anyhow!("can't convert URI to path"))?;
2964 let target_abs_path = op
2965 .new_uri
2966 .to_file_path()
2967 .map_err(|()| anyhow!("can't convert URI to path"))?;
2968 fs.rename(
2969 &source_abs_path,
2970 &target_abs_path,
2971 op.options
2972 .map(|options| fs::RenameOptions {
2973 overwrite: options.overwrite.unwrap_or(false),
2974 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2975 })
2976 .unwrap_or_default(),
2977 )
2978 .await?;
2979 }
2980
2981 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2982 let abs_path = op
2983 .uri
2984 .to_file_path()
2985 .map_err(|()| anyhow!("can't convert URI to path"))?;
2986 let options = op
2987 .options
2988 .map(|options| fs::RemoveOptions {
2989 recursive: options.recursive.unwrap_or(false),
2990 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2991 })
2992 .unwrap_or_default();
2993 if abs_path.ends_with("/") {
2994 fs.remove_dir(&abs_path, options).await?;
2995 } else {
2996 fs.remove_file(&abs_path, options).await?;
2997 }
2998 }
2999
3000 lsp::DocumentChangeOperation::Edit(op) => {
3001 let buffer_to_edit = this
3002 .update(cx, |this, cx| {
3003 this.open_local_buffer_via_lsp(
3004 op.text_document.uri.clone(),
3005 language_server.server_id(),
3006 lsp_adapter.name.clone(),
3007 cx,
3008 )
3009 })?
3010 .await?;
3011
3012 let edits = this
3013 .update(cx, |this, cx| {
3014 let path = buffer_to_edit.read(cx).project_path(cx);
3015 let active_entry = this.active_entry;
3016 let is_active_entry = path.clone().map_or(false, |project_path| {
3017 this.worktree_store
3018 .read(cx)
3019 .entry_for_path(&project_path, cx)
3020 .map_or(false, |entry| Some(entry.id) == active_entry)
3021 });
3022 let local = this.as_local_mut().unwrap();
3023
3024 let (mut edits, mut snippet_edits) = (vec![], vec![]);
3025 for edit in op.edits {
3026 match edit {
3027 Edit::Plain(edit) => {
3028 if !edits.contains(&edit) {
3029 edits.push(edit)
3030 }
3031 }
3032 Edit::Annotated(edit) => {
3033 if !edits.contains(&edit.text_edit) {
3034 edits.push(edit.text_edit)
3035 }
3036 }
3037 Edit::Snippet(edit) => {
3038 let Ok(snippet) = Snippet::parse(&edit.snippet.value)
3039 else {
3040 continue;
3041 };
3042
3043 if is_active_entry {
3044 snippet_edits.push((edit.range, snippet));
3045 } else {
3046 // Since this buffer is not focused, apply a normal edit.
3047 let new_edit = TextEdit {
3048 range: edit.range,
3049 new_text: snippet.text,
3050 };
3051 if !edits.contains(&new_edit) {
3052 edits.push(new_edit);
3053 }
3054 }
3055 }
3056 }
3057 }
3058 if !snippet_edits.is_empty() {
3059 let buffer_id = buffer_to_edit.read(cx).remote_id();
3060 let version = if let Some(buffer_version) = op.text_document.version
3061 {
3062 local
3063 .buffer_snapshot_for_lsp_version(
3064 &buffer_to_edit,
3065 language_server.server_id(),
3066 Some(buffer_version),
3067 cx,
3068 )
3069 .ok()
3070 .map(|snapshot| snapshot.version)
3071 } else {
3072 Some(buffer_to_edit.read(cx).saved_version().clone())
3073 };
3074
3075 let most_recent_edit = version.and_then(|version| {
3076 version.iter().max_by_key(|timestamp| timestamp.value)
3077 });
3078 // Check if the edit that triggered that edit has been made by this participant.
3079
3080 if let Some(most_recent_edit) = most_recent_edit {
3081 cx.emit(LspStoreEvent::SnippetEdit {
3082 buffer_id,
3083 edits: snippet_edits,
3084 most_recent_edit,
3085 });
3086 }
3087 }
3088
3089 local.edits_from_lsp(
3090 &buffer_to_edit,
3091 edits,
3092 language_server.server_id(),
3093 op.text_document.version,
3094 cx,
3095 )
3096 })?
3097 .await?;
3098
3099 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3100 buffer.finalize_last_transaction();
3101 buffer.start_transaction();
3102 for (range, text) in edits {
3103 buffer.edit([(range, text)], None, cx);
3104 }
3105
3106 let transaction = buffer.end_transaction(cx).and_then(|transaction_id| {
3107 if push_to_history {
3108 buffer.finalize_last_transaction();
3109 buffer.get_transaction(transaction_id).cloned()
3110 } else {
3111 buffer.forget_transaction(transaction_id)
3112 }
3113 });
3114
3115 transaction
3116 })?;
3117 if let Some(transaction) = transaction {
3118 project_transaction.0.insert(buffer_to_edit, transaction);
3119 }
3120 }
3121 }
3122 }
3123
3124 Ok(project_transaction)
3125 }
3126
3127 async fn on_lsp_workspace_edit(
3128 this: WeakEntity<LspStore>,
3129 params: lsp::ApplyWorkspaceEditParams,
3130 server_id: LanguageServerId,
3131 adapter: Arc<CachedLspAdapter>,
3132 cx: &mut AsyncApp,
3133 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3134 let this = this.upgrade().context("project project closed")?;
3135 let language_server = this
3136 .read_with(cx, |this, _| this.language_server_for_id(server_id))?
3137 .context("language server not found")?;
3138 let transaction = Self::deserialize_workspace_edit(
3139 this.clone(),
3140 params.edit,
3141 true,
3142 adapter.clone(),
3143 language_server.clone(),
3144 cx,
3145 )
3146 .await
3147 .log_err();
3148 this.update(cx, |this, _| {
3149 if let Some(transaction) = transaction {
3150 this.as_local_mut()
3151 .unwrap()
3152 .last_workspace_edits_by_language_server
3153 .insert(server_id, transaction);
3154 }
3155 })?;
3156 Ok(lsp::ApplyWorkspaceEditResponse {
3157 applied: true,
3158 failed_change: None,
3159 failure_reason: None,
3160 })
3161 }
3162
3163 fn remove_worktree(
3164 &mut self,
3165 id_to_remove: WorktreeId,
3166 cx: &mut Context<LspStore>,
3167 ) -> Vec<LanguageServerId> {
3168 self.diagnostics.remove(&id_to_remove);
3169 self.prettier_store.update(cx, |prettier_store, cx| {
3170 prettier_store.remove_worktree(id_to_remove, cx);
3171 });
3172
3173 let mut servers_to_remove = BTreeMap::default();
3174 let mut servers_to_preserve = HashSet::default();
3175 for ((path, server_name), ref server_ids) in &self.language_server_ids {
3176 if *path == id_to_remove {
3177 servers_to_remove.extend(server_ids.iter().map(|id| (*id, server_name.clone())));
3178 } else {
3179 servers_to_preserve.extend(server_ids.iter().cloned());
3180 }
3181 }
3182 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
3183
3184 for (server_id_to_remove, _) in &servers_to_remove {
3185 self.language_server_ids
3186 .values_mut()
3187 .for_each(|server_ids| {
3188 server_ids.remove(server_id_to_remove);
3189 });
3190 self.language_server_watched_paths
3191 .remove(server_id_to_remove);
3192 self.language_server_paths_watched_for_rename
3193 .remove(server_id_to_remove);
3194 self.last_workspace_edits_by_language_server
3195 .remove(server_id_to_remove);
3196 self.language_servers.remove(server_id_to_remove);
3197 self.buffer_pull_diagnostics_result_ids
3198 .remove(server_id_to_remove);
3199 for buffer_servers in self.buffers_opened_in_servers.values_mut() {
3200 buffer_servers.remove(server_id_to_remove);
3201 }
3202 cx.emit(LspStoreEvent::LanguageServerRemoved(*server_id_to_remove));
3203 }
3204 servers_to_remove.into_keys().collect()
3205 }
3206
3207 fn rebuild_watched_paths_inner<'a>(
3208 &'a self,
3209 language_server_id: LanguageServerId,
3210 watchers: impl Iterator<Item = &'a FileSystemWatcher>,
3211 cx: &mut Context<LspStore>,
3212 ) -> LanguageServerWatchedPathsBuilder {
3213 let worktrees = self
3214 .worktree_store
3215 .read(cx)
3216 .worktrees()
3217 .filter_map(|worktree| {
3218 self.language_servers_for_worktree(worktree.read(cx).id())
3219 .find(|server| server.server_id() == language_server_id)
3220 .map(|_| worktree)
3221 })
3222 .collect::<Vec<_>>();
3223
3224 let mut worktree_globs = HashMap::default();
3225 let mut abs_globs = HashMap::default();
3226 log::trace!(
3227 "Processing new watcher paths for language server with id {}",
3228 language_server_id
3229 );
3230
3231 for watcher in watchers {
3232 if let Some((worktree, literal_prefix, pattern)) =
3233 self.worktree_and_path_for_file_watcher(&worktrees, &watcher, cx)
3234 {
3235 worktree.update(cx, |worktree, _| {
3236 if let Some((tree, glob)) =
3237 worktree.as_local_mut().zip(Glob::new(&pattern).log_err())
3238 {
3239 tree.add_path_prefix_to_scan(literal_prefix.into());
3240 worktree_globs
3241 .entry(tree.id())
3242 .or_insert_with(GlobSetBuilder::new)
3243 .add(glob);
3244 }
3245 });
3246 } else {
3247 let (path, pattern) = match &watcher.glob_pattern {
3248 lsp::GlobPattern::String(s) => {
3249 let watcher_path = SanitizedPath::from(s);
3250 let path = glob_literal_prefix(watcher_path.as_path());
3251 let pattern = watcher_path
3252 .as_path()
3253 .strip_prefix(&path)
3254 .map(|p| p.to_string_lossy().to_string())
3255 .unwrap_or_else(|e| {
3256 debug_panic!(
3257 "Failed to strip prefix for string pattern: {}, with prefix: {}, with error: {}",
3258 s,
3259 path.display(),
3260 e
3261 );
3262 watcher_path.as_path().to_string_lossy().to_string()
3263 });
3264 (path, pattern)
3265 }
3266 lsp::GlobPattern::Relative(rp) => {
3267 let Ok(mut base_uri) = match &rp.base_uri {
3268 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3269 lsp::OneOf::Right(base_uri) => base_uri,
3270 }
3271 .to_file_path() else {
3272 continue;
3273 };
3274
3275 let path = glob_literal_prefix(Path::new(&rp.pattern));
3276 let pattern = Path::new(&rp.pattern)
3277 .strip_prefix(&path)
3278 .map(|p| p.to_string_lossy().to_string())
3279 .unwrap_or_else(|e| {
3280 debug_panic!(
3281 "Failed to strip prefix for relative pattern: {}, with prefix: {}, with error: {}",
3282 rp.pattern,
3283 path.display(),
3284 e
3285 );
3286 rp.pattern.clone()
3287 });
3288 base_uri.push(path);
3289 (base_uri, pattern)
3290 }
3291 };
3292
3293 if let Some(glob) = Glob::new(&pattern).log_err() {
3294 if !path
3295 .components()
3296 .any(|c| matches!(c, path::Component::Normal(_)))
3297 {
3298 // For an unrooted glob like `**/Cargo.toml`, watch it within each worktree,
3299 // rather than adding a new watcher for `/`.
3300 for worktree in &worktrees {
3301 worktree_globs
3302 .entry(worktree.read(cx).id())
3303 .or_insert_with(GlobSetBuilder::new)
3304 .add(glob.clone());
3305 }
3306 } else {
3307 abs_globs
3308 .entry(path.into())
3309 .or_insert_with(GlobSetBuilder::new)
3310 .add(glob);
3311 }
3312 }
3313 }
3314 }
3315
3316 let mut watch_builder = LanguageServerWatchedPathsBuilder::default();
3317 for (worktree_id, builder) in worktree_globs {
3318 if let Ok(globset) = builder.build() {
3319 watch_builder.watch_worktree(worktree_id, globset);
3320 }
3321 }
3322 for (abs_path, builder) in abs_globs {
3323 if let Ok(globset) = builder.build() {
3324 watch_builder.watch_abs_path(abs_path, globset);
3325 }
3326 }
3327 watch_builder
3328 }
3329
3330 fn worktree_and_path_for_file_watcher(
3331 &self,
3332 worktrees: &[Entity<Worktree>],
3333 watcher: &FileSystemWatcher,
3334 cx: &App,
3335 ) -> Option<(Entity<Worktree>, PathBuf, String)> {
3336 worktrees.iter().find_map(|worktree| {
3337 let tree = worktree.read(cx);
3338 let worktree_root_path = tree.abs_path();
3339 match &watcher.glob_pattern {
3340 lsp::GlobPattern::String(s) => {
3341 let watcher_path = SanitizedPath::from(s);
3342 let relative = watcher_path
3343 .as_path()
3344 .strip_prefix(&worktree_root_path)
3345 .ok()?;
3346 let literal_prefix = glob_literal_prefix(relative);
3347 Some((
3348 worktree.clone(),
3349 literal_prefix,
3350 relative.to_string_lossy().to_string(),
3351 ))
3352 }
3353 lsp::GlobPattern::Relative(rp) => {
3354 let base_uri = match &rp.base_uri {
3355 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3356 lsp::OneOf::Right(base_uri) => base_uri,
3357 }
3358 .to_file_path()
3359 .ok()?;
3360 let relative = base_uri.strip_prefix(&worktree_root_path).ok()?;
3361 let mut literal_prefix = relative.to_owned();
3362 literal_prefix.push(glob_literal_prefix(Path::new(&rp.pattern)));
3363 Some((worktree.clone(), literal_prefix, rp.pattern.clone()))
3364 }
3365 }
3366 })
3367 }
3368
3369 fn rebuild_watched_paths(
3370 &mut self,
3371 language_server_id: LanguageServerId,
3372 cx: &mut Context<LspStore>,
3373 ) {
3374 let Some(watchers) = self
3375 .language_server_watcher_registrations
3376 .get(&language_server_id)
3377 else {
3378 return;
3379 };
3380
3381 let watch_builder =
3382 self.rebuild_watched_paths_inner(language_server_id, watchers.values().flatten(), cx);
3383 let watcher = watch_builder.build(self.fs.clone(), language_server_id, cx);
3384 self.language_server_watched_paths
3385 .insert(language_server_id, watcher);
3386
3387 cx.notify();
3388 }
3389
3390 fn on_lsp_did_change_watched_files(
3391 &mut self,
3392 language_server_id: LanguageServerId,
3393 registration_id: &str,
3394 params: DidChangeWatchedFilesRegistrationOptions,
3395 cx: &mut Context<LspStore>,
3396 ) {
3397 let registrations = self
3398 .language_server_watcher_registrations
3399 .entry(language_server_id)
3400 .or_default();
3401
3402 registrations.insert(registration_id.to_string(), params.watchers);
3403
3404 self.rebuild_watched_paths(language_server_id, cx);
3405 }
3406
3407 fn on_lsp_unregister_did_change_watched_files(
3408 &mut self,
3409 language_server_id: LanguageServerId,
3410 registration_id: &str,
3411 cx: &mut Context<LspStore>,
3412 ) {
3413 let registrations = self
3414 .language_server_watcher_registrations
3415 .entry(language_server_id)
3416 .or_default();
3417
3418 if registrations.remove(registration_id).is_some() {
3419 log::info!(
3420 "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
3421 language_server_id,
3422 registration_id
3423 );
3424 } else {
3425 log::warn!(
3426 "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
3427 language_server_id,
3428 registration_id
3429 );
3430 }
3431
3432 self.rebuild_watched_paths(language_server_id, cx);
3433 }
3434
3435 async fn initialization_options_for_adapter(
3436 adapter: Arc<dyn LspAdapter>,
3437 fs: &dyn Fs,
3438 delegate: &Arc<dyn LspAdapterDelegate>,
3439 ) -> Result<Option<serde_json::Value>> {
3440 let Some(mut initialization_config) =
3441 adapter.clone().initialization_options(fs, delegate).await?
3442 else {
3443 return Ok(None);
3444 };
3445
3446 for other_adapter in delegate.registered_lsp_adapters() {
3447 if other_adapter.name() == adapter.name() {
3448 continue;
3449 }
3450 if let Ok(Some(target_config)) = other_adapter
3451 .clone()
3452 .additional_initialization_options(adapter.name(), fs, delegate)
3453 .await
3454 {
3455 merge_json_value_into(target_config.clone(), &mut initialization_config);
3456 }
3457 }
3458
3459 Ok(Some(initialization_config))
3460 }
3461
3462 async fn workspace_configuration_for_adapter(
3463 adapter: Arc<dyn LspAdapter>,
3464 fs: &dyn Fs,
3465 delegate: &Arc<dyn LspAdapterDelegate>,
3466 toolchains: Arc<dyn LanguageToolchainStore>,
3467 cx: &mut AsyncApp,
3468 ) -> Result<serde_json::Value> {
3469 let mut workspace_config = adapter
3470 .clone()
3471 .workspace_configuration(fs, delegate, toolchains.clone(), cx)
3472 .await?;
3473
3474 for other_adapter in delegate.registered_lsp_adapters() {
3475 if other_adapter.name() == adapter.name() {
3476 continue;
3477 }
3478 if let Ok(Some(target_config)) = other_adapter
3479 .clone()
3480 .additional_workspace_configuration(
3481 adapter.name(),
3482 fs,
3483 delegate,
3484 toolchains.clone(),
3485 cx,
3486 )
3487 .await
3488 {
3489 merge_json_value_into(target_config.clone(), &mut workspace_config);
3490 }
3491 }
3492
3493 Ok(workspace_config)
3494 }
3495}
3496
3497#[derive(Debug)]
3498pub struct FormattableBuffer {
3499 handle: Entity<Buffer>,
3500 abs_path: Option<PathBuf>,
3501 env: Option<HashMap<String, String>>,
3502 ranges: Option<Vec<Range<Anchor>>>,
3503}
3504
3505pub struct RemoteLspStore {
3506 upstream_client: Option<AnyProtoClient>,
3507 upstream_project_id: u64,
3508}
3509
3510pub(crate) enum LspStoreMode {
3511 Local(LocalLspStore), // ssh host and collab host
3512 Remote(RemoteLspStore), // collab guest
3513}
3514
3515impl LspStoreMode {
3516 fn is_local(&self) -> bool {
3517 matches!(self, LspStoreMode::Local(_))
3518 }
3519}
3520
3521pub struct LspStore {
3522 mode: LspStoreMode,
3523 last_formatting_failure: Option<String>,
3524 downstream_client: Option<(AnyProtoClient, u64)>,
3525 nonce: u128,
3526 buffer_store: Entity<BufferStore>,
3527 worktree_store: Entity<WorktreeStore>,
3528 toolchain_store: Option<Entity<ToolchainStore>>,
3529 pub languages: Arc<LanguageRegistry>,
3530 language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3531 active_entry: Option<ProjectEntryId>,
3532 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3533 _maintain_buffer_languages: Task<()>,
3534 diagnostic_summaries:
3535 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3536 lsp_document_colors: HashMap<BufferId, DocumentColorData>,
3537 lsp_code_lens: HashMap<BufferId, CodeLensData>,
3538}
3539
3540#[derive(Debug, Default, Clone)]
3541pub struct DocumentColors {
3542 pub colors: HashSet<DocumentColor>,
3543 pub cache_version: Option<usize>,
3544}
3545
3546type DocumentColorTask = Shared<Task<std::result::Result<DocumentColors, Arc<anyhow::Error>>>>;
3547type CodeLensTask = Shared<Task<std::result::Result<Vec<CodeAction>, Arc<anyhow::Error>>>>;
3548
3549#[derive(Debug, Default)]
3550struct DocumentColorData {
3551 colors_for_version: Global,
3552 colors: HashMap<LanguageServerId, HashSet<DocumentColor>>,
3553 cache_version: usize,
3554 colors_update: Option<(Global, DocumentColorTask)>,
3555}
3556
3557#[derive(Debug, Default)]
3558struct CodeLensData {
3559 lens_for_version: Global,
3560 lens: HashMap<LanguageServerId, Vec<CodeAction>>,
3561 update: Option<(Global, CodeLensTask)>,
3562}
3563
3564#[derive(Debug, PartialEq, Eq, Clone, Copy)]
3565pub enum LspFetchStrategy {
3566 IgnoreCache,
3567 UseCache { known_cache_version: Option<usize> },
3568}
3569
3570#[derive(Debug)]
3571pub enum LspStoreEvent {
3572 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3573 LanguageServerRemoved(LanguageServerId),
3574 LanguageServerUpdate {
3575 language_server_id: LanguageServerId,
3576 name: Option<LanguageServerName>,
3577 message: proto::update_language_server::Variant,
3578 },
3579 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3580 LanguageServerPrompt(LanguageServerPromptRequest),
3581 LanguageDetected {
3582 buffer: Entity<Buffer>,
3583 new_language: Option<Arc<Language>>,
3584 },
3585 Notification(String),
3586 RefreshInlayHints,
3587 RefreshCodeLens,
3588 DiagnosticsUpdated {
3589 language_server_id: LanguageServerId,
3590 path: ProjectPath,
3591 },
3592 DiskBasedDiagnosticsStarted {
3593 language_server_id: LanguageServerId,
3594 },
3595 DiskBasedDiagnosticsFinished {
3596 language_server_id: LanguageServerId,
3597 },
3598 SnippetEdit {
3599 buffer_id: BufferId,
3600 edits: Vec<(lsp::Range, Snippet)>,
3601 most_recent_edit: clock::Lamport,
3602 },
3603}
3604
3605#[derive(Clone, Debug, Serialize)]
3606pub struct LanguageServerStatus {
3607 pub name: String,
3608 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3609 pub has_pending_diagnostic_updates: bool,
3610 progress_tokens: HashSet<String>,
3611}
3612
3613#[derive(Clone, Debug)]
3614struct CoreSymbol {
3615 pub language_server_name: LanguageServerName,
3616 pub source_worktree_id: WorktreeId,
3617 pub source_language_server_id: LanguageServerId,
3618 pub path: ProjectPath,
3619 pub name: String,
3620 pub kind: lsp::SymbolKind,
3621 pub range: Range<Unclipped<PointUtf16>>,
3622 pub signature: [u8; 32],
3623}
3624
3625impl LspStore {
3626 pub fn init(client: &AnyProtoClient) {
3627 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3628 client.add_entity_request_handler(Self::handle_restart_language_servers);
3629 client.add_entity_request_handler(Self::handle_stop_language_servers);
3630 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3631 client.add_entity_message_handler(Self::handle_start_language_server);
3632 client.add_entity_message_handler(Self::handle_update_language_server);
3633 client.add_entity_message_handler(Self::handle_language_server_log);
3634 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3635 client.add_entity_request_handler(Self::handle_format_buffers);
3636 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3637 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3638 client.add_entity_request_handler(Self::handle_apply_code_action);
3639 client.add_entity_request_handler(Self::handle_inlay_hints);
3640 client.add_entity_request_handler(Self::handle_get_project_symbols);
3641 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3642 client.add_entity_request_handler(Self::handle_get_color_presentation);
3643 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3644 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3645 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3646 client.add_entity_request_handler(Self::handle_on_type_formatting);
3647 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3648 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3649 client.add_entity_request_handler(Self::handle_rename_project_entry);
3650 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3651 client.add_entity_request_handler(Self::handle_pull_workspace_diagnostics);
3652 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3653 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3654 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3655 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3656 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3657 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3658 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3659 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3660
3661 client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
3662 client.add_entity_request_handler(Self::handle_lsp_ext_run_flycheck);
3663 client.add_entity_request_handler(Self::handle_lsp_ext_clear_flycheck);
3664 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3665 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3666 client.add_entity_request_handler(
3667 Self::handle_lsp_command::<lsp_ext_command::GoToParentModule>,
3668 );
3669 client.add_entity_request_handler(
3670 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3671 );
3672 client.add_entity_request_handler(
3673 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3674 );
3675 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentDiagnostics>);
3676 }
3677
3678 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3679 match &self.mode {
3680 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3681 _ => None,
3682 }
3683 }
3684
3685 pub fn as_local(&self) -> Option<&LocalLspStore> {
3686 match &self.mode {
3687 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3688 _ => None,
3689 }
3690 }
3691
3692 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3693 match &mut self.mode {
3694 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3695 _ => None,
3696 }
3697 }
3698
3699 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3700 match &self.mode {
3701 LspStoreMode::Remote(RemoteLspStore {
3702 upstream_client: Some(upstream_client),
3703 upstream_project_id,
3704 ..
3705 }) => Some((upstream_client.clone(), *upstream_project_id)),
3706
3707 LspStoreMode::Remote(RemoteLspStore {
3708 upstream_client: None,
3709 ..
3710 }) => None,
3711 LspStoreMode::Local(_) => None,
3712 }
3713 }
3714
3715 pub fn new_local(
3716 buffer_store: Entity<BufferStore>,
3717 worktree_store: Entity<WorktreeStore>,
3718 prettier_store: Entity<PrettierStore>,
3719 toolchain_store: Entity<ToolchainStore>,
3720 environment: Entity<ProjectEnvironment>,
3721 manifest_tree: Entity<ManifestTree>,
3722 languages: Arc<LanguageRegistry>,
3723 http_client: Arc<dyn HttpClient>,
3724 fs: Arc<dyn Fs>,
3725 cx: &mut Context<Self>,
3726 ) -> Self {
3727 let yarn = YarnPathStore::new(fs.clone(), cx);
3728 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3729 .detach();
3730 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3731 .detach();
3732 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3733 .detach();
3734 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3735 .detach();
3736 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3737 cx.subscribe(
3738 extension_events,
3739 Self::reload_zed_json_schemas_on_extensions_changed,
3740 )
3741 .detach();
3742 } else {
3743 log::debug!("No extension events global found. Skipping JSON schema auto-reload setup");
3744 }
3745 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3746 .detach();
3747 subscribe_to_binary_statuses(&languages, cx).detach();
3748
3749 let _maintain_workspace_config = {
3750 let (sender, receiver) = watch::channel();
3751 (
3752 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3753 sender,
3754 )
3755 };
3756
3757 Self {
3758 mode: LspStoreMode::Local(LocalLspStore {
3759 weak: cx.weak_entity(),
3760 worktree_store: worktree_store.clone(),
3761 toolchain_store: toolchain_store.clone(),
3762 supplementary_language_servers: Default::default(),
3763 languages: languages.clone(),
3764 language_server_ids: Default::default(),
3765 language_servers: Default::default(),
3766 last_workspace_edits_by_language_server: Default::default(),
3767 language_server_watched_paths: Default::default(),
3768 language_server_paths_watched_for_rename: Default::default(),
3769 language_server_watcher_registrations: Default::default(),
3770 buffers_being_formatted: Default::default(),
3771 buffer_snapshots: Default::default(),
3772 prettier_store,
3773 environment,
3774 http_client,
3775 fs,
3776 yarn,
3777 next_diagnostic_group_id: Default::default(),
3778 diagnostics: Default::default(),
3779 _subscription: cx.on_app_quit(|this, cx| {
3780 this.as_local_mut()
3781 .unwrap()
3782 .shutdown_language_servers_on_quit(cx)
3783 }),
3784 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3785 registered_buffers: HashMap::default(),
3786 buffers_opened_in_servers: HashMap::default(),
3787 buffer_pull_diagnostics_result_ids: HashMap::default(),
3788 }),
3789 last_formatting_failure: None,
3790 downstream_client: None,
3791 buffer_store,
3792 worktree_store,
3793 toolchain_store: Some(toolchain_store),
3794 languages: languages.clone(),
3795 language_server_statuses: Default::default(),
3796 nonce: StdRng::from_entropy().r#gen(),
3797 diagnostic_summaries: HashMap::default(),
3798 lsp_document_colors: HashMap::default(),
3799 lsp_code_lens: HashMap::default(),
3800 active_entry: None,
3801 _maintain_workspace_config,
3802 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3803 }
3804 }
3805
3806 fn send_lsp_proto_request<R: LspCommand>(
3807 &self,
3808 buffer: Entity<Buffer>,
3809 client: AnyProtoClient,
3810 upstream_project_id: u64,
3811 request: R,
3812 cx: &mut Context<LspStore>,
3813 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3814 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3815 cx.spawn(async move |this, cx| {
3816 let response = client.request(message).await?;
3817 let this = this.upgrade().context("project dropped")?;
3818 request
3819 .response_from_proto(response, this, buffer, cx.clone())
3820 .await
3821 })
3822 }
3823
3824 pub(super) fn new_remote(
3825 buffer_store: Entity<BufferStore>,
3826 worktree_store: Entity<WorktreeStore>,
3827 toolchain_store: Option<Entity<ToolchainStore>>,
3828 languages: Arc<LanguageRegistry>,
3829 upstream_client: AnyProtoClient,
3830 project_id: u64,
3831 fs: Arc<dyn Fs>,
3832 cx: &mut Context<Self>,
3833 ) -> Self {
3834 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3835 .detach();
3836 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3837 .detach();
3838 subscribe_to_binary_statuses(&languages, cx).detach();
3839 let _maintain_workspace_config = {
3840 let (sender, receiver) = watch::channel();
3841 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3842 };
3843 Self {
3844 mode: LspStoreMode::Remote(RemoteLspStore {
3845 upstream_client: Some(upstream_client),
3846 upstream_project_id: project_id,
3847 }),
3848 downstream_client: None,
3849 last_formatting_failure: None,
3850 buffer_store,
3851 worktree_store,
3852 languages: languages.clone(),
3853 language_server_statuses: Default::default(),
3854 nonce: StdRng::from_entropy().r#gen(),
3855 diagnostic_summaries: HashMap::default(),
3856 lsp_document_colors: HashMap::default(),
3857 lsp_code_lens: HashMap::default(),
3858 active_entry: None,
3859 toolchain_store,
3860 _maintain_workspace_config,
3861 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3862 }
3863 }
3864
3865 fn on_buffer_store_event(
3866 &mut self,
3867 _: Entity<BufferStore>,
3868 event: &BufferStoreEvent,
3869 cx: &mut Context<Self>,
3870 ) {
3871 match event {
3872 BufferStoreEvent::BufferAdded(buffer) => {
3873 self.on_buffer_added(buffer, cx).log_err();
3874 }
3875 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3876 let buffer_id = buffer.read(cx).remote_id();
3877 if let Some(local) = self.as_local_mut() {
3878 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3879 local.reset_buffer(buffer, old_file, cx);
3880
3881 if local.registered_buffers.contains_key(&buffer_id) {
3882 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3883 }
3884 }
3885 }
3886
3887 self.detect_language_for_buffer(buffer, cx);
3888 if let Some(local) = self.as_local_mut() {
3889 local.initialize_buffer(buffer, cx);
3890 if local.registered_buffers.contains_key(&buffer_id) {
3891 local.register_buffer_with_language_servers(buffer, HashSet::default(), cx);
3892 }
3893 }
3894 }
3895 _ => {}
3896 }
3897 }
3898
3899 fn on_worktree_store_event(
3900 &mut self,
3901 _: Entity<WorktreeStore>,
3902 event: &WorktreeStoreEvent,
3903 cx: &mut Context<Self>,
3904 ) {
3905 match event {
3906 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3907 if !worktree.read(cx).is_local() {
3908 return;
3909 }
3910 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3911 worktree::Event::UpdatedEntries(changes) => {
3912 this.update_local_worktree_language_servers(&worktree, changes, cx);
3913 }
3914 worktree::Event::UpdatedGitRepositories(_)
3915 | worktree::Event::DeletedEntry(_) => {}
3916 })
3917 .detach()
3918 }
3919 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3920 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3921 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3922 }
3923 WorktreeStoreEvent::WorktreeReleased(..)
3924 | WorktreeStoreEvent::WorktreeOrderChanged
3925 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3926 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3927 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3928 }
3929 }
3930
3931 fn on_prettier_store_event(
3932 &mut self,
3933 _: Entity<PrettierStore>,
3934 event: &PrettierStoreEvent,
3935 cx: &mut Context<Self>,
3936 ) {
3937 match event {
3938 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3939 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3940 }
3941 PrettierStoreEvent::LanguageServerAdded {
3942 new_server_id,
3943 name,
3944 prettier_server,
3945 } => {
3946 self.register_supplementary_language_server(
3947 *new_server_id,
3948 name.clone(),
3949 prettier_server.clone(),
3950 cx,
3951 );
3952 }
3953 }
3954 }
3955
3956 fn on_toolchain_store_event(
3957 &mut self,
3958 _: Entity<ToolchainStore>,
3959 event: &ToolchainStoreEvent,
3960 _: &mut Context<Self>,
3961 ) {
3962 match event {
3963 ToolchainStoreEvent::ToolchainActivated { .. } => {
3964 self.request_workspace_config_refresh()
3965 }
3966 }
3967 }
3968
3969 fn request_workspace_config_refresh(&mut self) {
3970 *self._maintain_workspace_config.1.borrow_mut() = ();
3971 }
3972
3973 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3974 self.as_local().map(|local| local.prettier_store.clone())
3975 }
3976
3977 fn on_buffer_event(
3978 &mut self,
3979 buffer: Entity<Buffer>,
3980 event: &language::BufferEvent,
3981 cx: &mut Context<Self>,
3982 ) {
3983 match event {
3984 language::BufferEvent::Edited => {
3985 self.on_buffer_edited(buffer, cx);
3986 }
3987
3988 language::BufferEvent::Saved => {
3989 self.on_buffer_saved(buffer, cx);
3990 }
3991
3992 _ => {}
3993 }
3994 }
3995
3996 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3997 buffer
3998 .read(cx)
3999 .set_language_registry(self.languages.clone());
4000
4001 cx.subscribe(buffer, |this, buffer, event, cx| {
4002 this.on_buffer_event(buffer, event, cx);
4003 })
4004 .detach();
4005
4006 self.detect_language_for_buffer(buffer, cx);
4007 if let Some(local) = self.as_local_mut() {
4008 local.initialize_buffer(buffer, cx);
4009 }
4010
4011 Ok(())
4012 }
4013
4014 pub fn reload_zed_json_schemas_on_extensions_changed(
4015 &mut self,
4016 _: Entity<extension::ExtensionEvents>,
4017 evt: &extension::Event,
4018 cx: &mut Context<Self>,
4019 ) {
4020 match evt {
4021 extension::Event::ExtensionInstalled(_)
4022 | extension::Event::ExtensionUninstalled(_)
4023 | extension::Event::ConfigureExtensionRequested(_) => return,
4024 extension::Event::ExtensionsInstalledChanged => {}
4025 }
4026 if self.as_local().is_none() {
4027 return;
4028 }
4029 cx.spawn(async move |this, cx| {
4030 let weak_ref = this.clone();
4031
4032 let servers = this
4033 .update(cx, |this, cx| {
4034 let local = this.as_local()?;
4035
4036 let mut servers = Vec::new();
4037 for ((worktree_id, _), server_ids) in &local.language_server_ids {
4038 for server_id in server_ids {
4039 let Some(states) = local.language_servers.get(server_id) else {
4040 continue;
4041 };
4042 let (json_adapter, json_server) = match states {
4043 LanguageServerState::Running {
4044 adapter, server, ..
4045 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
4046 (adapter.adapter.clone(), server.clone())
4047 }
4048 _ => continue,
4049 };
4050
4051 let Some(worktree) = this
4052 .worktree_store
4053 .read(cx)
4054 .worktree_for_id(*worktree_id, cx)
4055 else {
4056 continue;
4057 };
4058 let json_delegate: Arc<dyn LspAdapterDelegate> =
4059 LocalLspAdapterDelegate::new(
4060 local.languages.clone(),
4061 &local.environment,
4062 weak_ref.clone(),
4063 &worktree,
4064 local.http_client.clone(),
4065 local.fs.clone(),
4066 cx,
4067 );
4068
4069 servers.push((json_adapter, json_server, json_delegate));
4070 }
4071 }
4072 return Some(servers);
4073 })
4074 .ok()
4075 .flatten();
4076
4077 let Some(servers) = servers else {
4078 return;
4079 };
4080
4081 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
4082 let local = this.as_local()?;
4083 let toolchain_store = this.toolchain_store(cx);
4084 return Some((local.fs.clone(), toolchain_store));
4085 }) else {
4086 return;
4087 };
4088 for (adapter, server, delegate) in servers {
4089 adapter.clear_zed_json_schema_cache().await;
4090
4091 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
4092 adapter,
4093 fs.as_ref(),
4094 &delegate,
4095 toolchain_store.clone(),
4096 cx,
4097 )
4098 .await
4099 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
4100 .ok()
4101 else {
4102 continue;
4103 };
4104 server
4105 .notify::<lsp::notification::DidChangeConfiguration>(
4106 &lsp::DidChangeConfigurationParams {
4107 settings: json_workspace_config,
4108 },
4109 )
4110 .ok();
4111 }
4112 })
4113 .detach();
4114 }
4115
4116 pub(crate) fn register_buffer_with_language_servers(
4117 &mut self,
4118 buffer: &Entity<Buffer>,
4119 only_register_servers: HashSet<LanguageServerSelector>,
4120 ignore_refcounts: bool,
4121 cx: &mut Context<Self>,
4122 ) -> OpenLspBufferHandle {
4123 let buffer_id = buffer.read(cx).remote_id();
4124 let handle = cx.new(|_| buffer.clone());
4125 if let Some(local) = self.as_local_mut() {
4126 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
4127 if !ignore_refcounts {
4128 *refcount += 1;
4129 }
4130
4131 // We run early exits on non-existing buffers AFTER we mark the buffer as registered in order to handle buffer saving.
4132 // 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
4133 // 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
4134 // servers in practice (we don't support non-file URI schemes in our LSP impl).
4135 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
4136 return handle;
4137 };
4138 if !file.is_local() {
4139 return handle;
4140 }
4141
4142 if ignore_refcounts || *refcount == 1 {
4143 local.register_buffer_with_language_servers(buffer, only_register_servers, cx);
4144 }
4145 if !ignore_refcounts {
4146 cx.observe_release(&handle, move |lsp_store, buffer, cx| {
4147 let refcount = {
4148 let local = lsp_store.as_local_mut().unwrap();
4149 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
4150 debug_panic!("bad refcounting");
4151 return;
4152 };
4153
4154 *refcount -= 1;
4155 *refcount
4156 };
4157 if refcount == 0 {
4158 lsp_store.lsp_document_colors.remove(&buffer_id);
4159 lsp_store.lsp_code_lens.remove(&buffer_id);
4160 let local = lsp_store.as_local_mut().unwrap();
4161 local.registered_buffers.remove(&buffer_id);
4162 local.buffers_opened_in_servers.remove(&buffer_id);
4163 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
4164 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
4165 }
4166 }
4167 })
4168 .detach();
4169 }
4170 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4171 let buffer_id = buffer.read(cx).remote_id().to_proto();
4172 cx.background_spawn(async move {
4173 upstream_client
4174 .request(proto::RegisterBufferWithLanguageServers {
4175 project_id: upstream_project_id,
4176 buffer_id,
4177 only_servers: only_register_servers
4178 .into_iter()
4179 .map(|selector| {
4180 let selector = match selector {
4181 LanguageServerSelector::Id(language_server_id) => {
4182 proto::language_server_selector::Selector::ServerId(
4183 language_server_id.to_proto(),
4184 )
4185 }
4186 LanguageServerSelector::Name(language_server_name) => {
4187 proto::language_server_selector::Selector::Name(
4188 language_server_name.to_string(),
4189 )
4190 }
4191 };
4192 proto::LanguageServerSelector {
4193 selector: Some(selector),
4194 }
4195 })
4196 .collect(),
4197 })
4198 .await
4199 })
4200 .detach();
4201 } else {
4202 panic!("oops!");
4203 }
4204 handle
4205 }
4206
4207 fn maintain_buffer_languages(
4208 languages: Arc<LanguageRegistry>,
4209 cx: &mut Context<Self>,
4210 ) -> Task<()> {
4211 let mut subscription = languages.subscribe();
4212 let mut prev_reload_count = languages.reload_count();
4213 cx.spawn(async move |this, cx| {
4214 while let Some(()) = subscription.next().await {
4215 if let Some(this) = this.upgrade() {
4216 // If the language registry has been reloaded, then remove and
4217 // re-assign the languages on all open buffers.
4218 let reload_count = languages.reload_count();
4219 if reload_count > prev_reload_count {
4220 prev_reload_count = reload_count;
4221 this.update(cx, |this, cx| {
4222 this.buffer_store.clone().update(cx, |buffer_store, cx| {
4223 for buffer in buffer_store.buffers() {
4224 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
4225 {
4226 buffer
4227 .update(cx, |buffer, cx| buffer.set_language(None, cx));
4228 if let Some(local) = this.as_local_mut() {
4229 local.reset_buffer(&buffer, &f, cx);
4230
4231 if local
4232 .registered_buffers
4233 .contains_key(&buffer.read(cx).remote_id())
4234 {
4235 if let Some(file_url) =
4236 file_path_to_lsp_url(&f.abs_path(cx)).log_err()
4237 {
4238 local.unregister_buffer_from_language_servers(
4239 &buffer, &file_url, cx,
4240 );
4241 }
4242 }
4243 }
4244 }
4245 }
4246 });
4247 })
4248 .ok();
4249 }
4250
4251 this.update(cx, |this, cx| {
4252 let mut plain_text_buffers = Vec::new();
4253 let mut buffers_with_unknown_injections = Vec::new();
4254 for handle in this.buffer_store.read(cx).buffers() {
4255 let buffer = handle.read(cx);
4256 if buffer.language().is_none()
4257 || buffer.language() == Some(&*language::PLAIN_TEXT)
4258 {
4259 plain_text_buffers.push(handle);
4260 } else if buffer.contains_unknown_injections() {
4261 buffers_with_unknown_injections.push(handle);
4262 }
4263 }
4264
4265 // Deprioritize the invisible worktrees so main worktrees' language servers can be started first,
4266 // and reused later in the invisible worktrees.
4267 plain_text_buffers.sort_by_key(|buffer| {
4268 Reverse(
4269 File::from_dyn(buffer.read(cx).file())
4270 .map(|file| file.worktree.read(cx).is_visible()),
4271 )
4272 });
4273
4274 for buffer in plain_text_buffers {
4275 this.detect_language_for_buffer(&buffer, cx);
4276 if let Some(local) = this.as_local_mut() {
4277 local.initialize_buffer(&buffer, cx);
4278 if local
4279 .registered_buffers
4280 .contains_key(&buffer.read(cx).remote_id())
4281 {
4282 local.register_buffer_with_language_servers(
4283 &buffer,
4284 HashSet::default(),
4285 cx,
4286 );
4287 }
4288 }
4289 }
4290
4291 for buffer in buffers_with_unknown_injections {
4292 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4293 }
4294 })
4295 .ok();
4296 }
4297 }
4298 })
4299 }
4300
4301 fn detect_language_for_buffer(
4302 &mut self,
4303 buffer_handle: &Entity<Buffer>,
4304 cx: &mut Context<Self>,
4305 ) -> Option<language::AvailableLanguage> {
4306 // If the buffer has a language, set it and start the language server if we haven't already.
4307 let buffer = buffer_handle.read(cx);
4308 let file = buffer.file()?;
4309
4310 let content = buffer.as_rope();
4311 let available_language = self.languages.language_for_file(file, Some(content), cx);
4312 if let Some(available_language) = &available_language {
4313 if let Some(Ok(Ok(new_language))) = self
4314 .languages
4315 .load_language(available_language)
4316 .now_or_never()
4317 {
4318 self.set_language_for_buffer(buffer_handle, new_language, cx);
4319 }
4320 } else {
4321 cx.emit(LspStoreEvent::LanguageDetected {
4322 buffer: buffer_handle.clone(),
4323 new_language: None,
4324 });
4325 }
4326
4327 available_language
4328 }
4329
4330 pub(crate) fn set_language_for_buffer(
4331 &mut self,
4332 buffer_entity: &Entity<Buffer>,
4333 new_language: Arc<Language>,
4334 cx: &mut Context<Self>,
4335 ) {
4336 let buffer = buffer_entity.read(cx);
4337 let buffer_file = buffer.file().cloned();
4338 let buffer_id = buffer.remote_id();
4339 if let Some(local_store) = self.as_local_mut() {
4340 if local_store.registered_buffers.contains_key(&buffer_id) {
4341 if let Some(abs_path) =
4342 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4343 {
4344 if let Some(file_url) = file_path_to_lsp_url(&abs_path).log_err() {
4345 local_store.unregister_buffer_from_language_servers(
4346 buffer_entity,
4347 &file_url,
4348 cx,
4349 );
4350 }
4351 }
4352 }
4353 }
4354 buffer_entity.update(cx, |buffer, cx| {
4355 if buffer.language().map_or(true, |old_language| {
4356 !Arc::ptr_eq(old_language, &new_language)
4357 }) {
4358 buffer.set_language(Some(new_language.clone()), cx);
4359 }
4360 });
4361
4362 let settings =
4363 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4364 let buffer_file = File::from_dyn(buffer_file.as_ref());
4365
4366 let worktree_id = if let Some(file) = buffer_file {
4367 let worktree = file.worktree.clone();
4368
4369 if let Some(local) = self.as_local_mut() {
4370 if local.registered_buffers.contains_key(&buffer_id) {
4371 local.register_buffer_with_language_servers(
4372 buffer_entity,
4373 HashSet::default(),
4374 cx,
4375 );
4376 }
4377 }
4378 Some(worktree.read(cx).id())
4379 } else {
4380 None
4381 };
4382
4383 if settings.prettier.allowed {
4384 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4385 {
4386 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4387 if let Some(prettier_store) = prettier_store {
4388 prettier_store.update(cx, |prettier_store, cx| {
4389 prettier_store.install_default_prettier(
4390 worktree_id,
4391 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4392 cx,
4393 )
4394 })
4395 }
4396 }
4397 }
4398
4399 cx.emit(LspStoreEvent::LanguageDetected {
4400 buffer: buffer_entity.clone(),
4401 new_language: Some(new_language),
4402 })
4403 }
4404
4405 pub fn buffer_store(&self) -> Entity<BufferStore> {
4406 self.buffer_store.clone()
4407 }
4408
4409 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4410 self.active_entry = active_entry;
4411 }
4412
4413 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4414 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4415 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4416 for (path, summaries) in summaries {
4417 for (&server_id, summary) in summaries {
4418 client
4419 .send(proto::UpdateDiagnosticSummary {
4420 project_id: downstream_project_id,
4421 worktree_id: worktree.id().to_proto(),
4422 summary: Some(summary.to_proto(server_id, path)),
4423 })
4424 .log_err();
4425 }
4426 }
4427 }
4428 }
4429 }
4430
4431 pub fn request_lsp<R: LspCommand>(
4432 &mut self,
4433 buffer_handle: Entity<Buffer>,
4434 server: LanguageServerToQuery,
4435 request: R,
4436 cx: &mut Context<Self>,
4437 ) -> Task<Result<R::Response>>
4438 where
4439 <R::LspRequest as lsp::request::Request>::Result: Send,
4440 <R::LspRequest as lsp::request::Request>::Params: Send,
4441 {
4442 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4443 return self.send_lsp_proto_request(
4444 buffer_handle,
4445 upstream_client,
4446 upstream_project_id,
4447 request,
4448 cx,
4449 );
4450 }
4451
4452 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4453 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4454 local
4455 .language_servers_for_buffer(buffer, cx)
4456 .find(|(_, server)| {
4457 request.check_capabilities(server.adapter_server_capabilities())
4458 })
4459 .map(|(_, server)| server.clone())
4460 }),
4461 LanguageServerToQuery::Other(id) => self
4462 .language_server_for_local_buffer(buffer, id, cx)
4463 .and_then(|(_, server)| {
4464 request
4465 .check_capabilities(server.adapter_server_capabilities())
4466 .then(|| Arc::clone(server))
4467 }),
4468 }) else {
4469 return Task::ready(Ok(Default::default()));
4470 };
4471
4472 let buffer = buffer_handle.read(cx);
4473 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4474
4475 let Some(file) = file else {
4476 return Task::ready(Ok(Default::default()));
4477 };
4478
4479 let lsp_params = match request.to_lsp_params_or_response(
4480 &file.abs_path(cx),
4481 buffer,
4482 &language_server,
4483 cx,
4484 ) {
4485 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4486 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4487
4488 Err(err) => {
4489 let message = format!(
4490 "{} via {} failed: {}",
4491 request.display_name(),
4492 language_server.name(),
4493 err
4494 );
4495 log::warn!("{message}");
4496 return Task::ready(Err(anyhow!(message)));
4497 }
4498 };
4499
4500 let status = request.status();
4501 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4502 return Task::ready(Ok(Default::default()));
4503 }
4504 return cx.spawn(async move |this, cx| {
4505 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4506
4507 let id = lsp_request.id();
4508 let _cleanup = if status.is_some() {
4509 cx.update(|cx| {
4510 this.update(cx, |this, cx| {
4511 this.on_lsp_work_start(
4512 language_server.server_id(),
4513 id.to_string(),
4514 LanguageServerProgress {
4515 is_disk_based_diagnostics_progress: false,
4516 is_cancellable: false,
4517 title: None,
4518 message: status.clone(),
4519 percentage: None,
4520 last_update_at: cx.background_executor().now(),
4521 },
4522 cx,
4523 );
4524 })
4525 })
4526 .log_err();
4527
4528 Some(defer(|| {
4529 cx.update(|cx| {
4530 this.update(cx, |this, cx| {
4531 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4532 })
4533 })
4534 .log_err();
4535 }))
4536 } else {
4537 None
4538 };
4539
4540 let result = lsp_request.await.into_response();
4541
4542 let response = result.map_err(|err| {
4543 let message = format!(
4544 "{} via {} failed: {}",
4545 request.display_name(),
4546 language_server.name(),
4547 err
4548 );
4549 log::warn!("{message}");
4550 anyhow::anyhow!(message)
4551 })?;
4552
4553 let response = request
4554 .response_from_lsp(
4555 response,
4556 this.upgrade().context("no app context")?,
4557 buffer_handle,
4558 language_server.server_id(),
4559 cx.clone(),
4560 )
4561 .await;
4562 response
4563 });
4564 }
4565
4566 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4567 let mut language_formatters_to_check = Vec::new();
4568 for buffer in self.buffer_store.read(cx).buffers() {
4569 let buffer = buffer.read(cx);
4570 let buffer_file = File::from_dyn(buffer.file());
4571 let buffer_language = buffer.language();
4572 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4573 if buffer_language.is_some() {
4574 language_formatters_to_check.push((
4575 buffer_file.map(|f| f.worktree_id(cx)),
4576 settings.into_owned(),
4577 ));
4578 }
4579 }
4580
4581 self.refresh_server_tree(cx);
4582
4583 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4584 prettier_store.update(cx, |prettier_store, cx| {
4585 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4586 })
4587 }
4588
4589 cx.notify();
4590 }
4591
4592 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4593 let buffer_store = self.buffer_store.clone();
4594 if let Some(local) = self.as_local_mut() {
4595 let mut adapters = BTreeMap::default();
4596 let get_adapter = {
4597 let languages = local.languages.clone();
4598 let environment = local.environment.clone();
4599 let weak = local.weak.clone();
4600 let worktree_store = local.worktree_store.clone();
4601 let http_client = local.http_client.clone();
4602 let fs = local.fs.clone();
4603 move |worktree_id, cx: &mut App| {
4604 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4605 Some(LocalLspAdapterDelegate::new(
4606 languages.clone(),
4607 &environment,
4608 weak.clone(),
4609 &worktree,
4610 http_client.clone(),
4611 fs.clone(),
4612 cx,
4613 ))
4614 }
4615 };
4616
4617 let mut messages_to_report = Vec::new();
4618 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4619 let mut rebase = lsp_tree.rebase();
4620 for buffer_handle in buffer_store.read(cx).buffers().sorted_by_key(|buffer| {
4621 Reverse(
4622 File::from_dyn(buffer.read(cx).file())
4623 .map(|file| file.worktree.read(cx).is_visible()),
4624 )
4625 }) {
4626 let buffer = buffer_handle.read(cx);
4627 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4628 continue;
4629 }
4630 if let Some((file, language)) = File::from_dyn(buffer.file())
4631 .cloned()
4632 .zip(buffer.language().map(|l| l.name()))
4633 {
4634 let worktree_id = file.worktree_id(cx);
4635 let Some(worktree) = local
4636 .worktree_store
4637 .read(cx)
4638 .worktree_for_id(worktree_id, cx)
4639 else {
4640 continue;
4641 };
4642
4643 let Some((reused, delegate, nodes)) = local
4644 .reuse_existing_language_server(
4645 rebase.server_tree(),
4646 &worktree,
4647 &language,
4648 cx,
4649 )
4650 .map(|(delegate, servers)| (true, delegate, servers))
4651 .or_else(|| {
4652 let lsp_delegate = adapters
4653 .entry(worktree_id)
4654 .or_insert_with(|| get_adapter(worktree_id, cx))
4655 .clone()?;
4656 let delegate = Arc::new(ManifestQueryDelegate::new(
4657 worktree.read(cx).snapshot(),
4658 ));
4659 let path = file
4660 .path()
4661 .parent()
4662 .map(Arc::from)
4663 .unwrap_or_else(|| file.path().clone());
4664 let worktree_path = ProjectPath { worktree_id, path };
4665
4666 let nodes = rebase.get(
4667 worktree_path,
4668 AdapterQuery::Language(&language),
4669 delegate.clone(),
4670 cx,
4671 );
4672
4673 Some((false, lsp_delegate, nodes.collect()))
4674 })
4675 else {
4676 continue;
4677 };
4678
4679 let abs_path = file.abs_path(cx);
4680 for node in nodes {
4681 if !reused {
4682 let server_id = node.server_id_or_init(
4683 |LaunchDisposition {
4684 server_name,
4685
4686 path,
4687 settings,
4688 }|
4689 {
4690 let uri = Url::from_file_path(
4691 worktree.read(cx).abs_path().join(&path.path),
4692 );
4693 let key = (worktree_id, server_name.clone());
4694 local.language_server_ids.remove(&key);
4695
4696 let adapter = local
4697 .languages
4698 .lsp_adapters(&language)
4699 .into_iter()
4700 .find(|adapter| &adapter.name() == server_name)
4701 .expect("To find LSP adapter");
4702 let server_id = local.start_language_server(
4703 &worktree,
4704 delegate.clone(),
4705 adapter,
4706 settings,
4707 cx,
4708 );
4709 if let Some(state) =
4710 local.language_servers.get(&server_id)
4711 {
4712 if let Ok(uri) = uri {
4713 state.add_workspace_folder(uri);
4714 };
4715 }
4716 server_id
4717 }
4718 );
4719
4720 if let Some(language_server_id) = server_id {
4721 messages_to_report.push(LspStoreEvent::LanguageServerUpdate {
4722 language_server_id,
4723 name: node.name(),
4724 message:
4725 proto::update_language_server::Variant::RegisteredForBuffer(
4726 proto::RegisteredForBuffer {
4727 buffer_abs_path: abs_path.to_string_lossy().to_string(),
4728 },
4729 ),
4730 });
4731 }
4732 }
4733 }
4734 }
4735 }
4736 rebase.finish()
4737 });
4738 for message in messages_to_report {
4739 cx.emit(message);
4740 }
4741 for (id, _) in to_stop {
4742 self.stop_local_language_server(id, cx).detach();
4743 }
4744 }
4745 }
4746
4747 pub fn apply_code_action(
4748 &self,
4749 buffer_handle: Entity<Buffer>,
4750 mut action: CodeAction,
4751 push_to_history: bool,
4752 cx: &mut Context<Self>,
4753 ) -> Task<Result<ProjectTransaction>> {
4754 if let Some((upstream_client, project_id)) = self.upstream_client() {
4755 let request = proto::ApplyCodeAction {
4756 project_id,
4757 buffer_id: buffer_handle.read(cx).remote_id().into(),
4758 action: Some(Self::serialize_code_action(&action)),
4759 };
4760 let buffer_store = self.buffer_store();
4761 cx.spawn(async move |_, cx| {
4762 let response = upstream_client
4763 .request(request)
4764 .await?
4765 .transaction
4766 .context("missing transaction")?;
4767
4768 buffer_store
4769 .update(cx, |buffer_store, cx| {
4770 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4771 })?
4772 .await
4773 })
4774 } else if self.mode.is_local() {
4775 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4776 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4777 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4778 }) else {
4779 return Task::ready(Ok(ProjectTransaction::default()));
4780 };
4781 cx.spawn(async move |this, cx| {
4782 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4783 .await
4784 .context("resolving a code action")?;
4785 if let Some(edit) = action.lsp_action.edit() {
4786 if edit.changes.is_some() || edit.document_changes.is_some() {
4787 return LocalLspStore::deserialize_workspace_edit(
4788 this.upgrade().context("no app present")?,
4789 edit.clone(),
4790 push_to_history,
4791 lsp_adapter.clone(),
4792 lang_server.clone(),
4793 cx,
4794 )
4795 .await;
4796 }
4797 }
4798
4799 if let Some(command) = action.lsp_action.command() {
4800 let server_capabilities = lang_server.capabilities();
4801 let available_commands = server_capabilities
4802 .execute_command_provider
4803 .as_ref()
4804 .map(|options| options.commands.as_slice())
4805 .unwrap_or_default();
4806 if available_commands.contains(&command.command) {
4807 this.update(cx, |this, _| {
4808 this.as_local_mut()
4809 .unwrap()
4810 .last_workspace_edits_by_language_server
4811 .remove(&lang_server.server_id());
4812 })?;
4813
4814 let _result = lang_server
4815 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4816 command: command.command.clone(),
4817 arguments: command.arguments.clone().unwrap_or_default(),
4818 ..lsp::ExecuteCommandParams::default()
4819 })
4820 .await.into_response()
4821 .context("execute command")?;
4822
4823 return this.update(cx, |this, _| {
4824 this.as_local_mut()
4825 .unwrap()
4826 .last_workspace_edits_by_language_server
4827 .remove(&lang_server.server_id())
4828 .unwrap_or_default()
4829 });
4830 } else {
4831 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4832 }
4833 }
4834
4835 Ok(ProjectTransaction::default())
4836 })
4837 } else {
4838 Task::ready(Err(anyhow!("no upstream client and not local")))
4839 }
4840 }
4841
4842 pub fn apply_code_action_kind(
4843 &mut self,
4844 buffers: HashSet<Entity<Buffer>>,
4845 kind: CodeActionKind,
4846 push_to_history: bool,
4847 cx: &mut Context<Self>,
4848 ) -> Task<anyhow::Result<ProjectTransaction>> {
4849 if let Some(_) = self.as_local() {
4850 cx.spawn(async move |lsp_store, cx| {
4851 let buffers = buffers.into_iter().collect::<Vec<_>>();
4852 let result = LocalLspStore::execute_code_action_kind_locally(
4853 lsp_store.clone(),
4854 buffers,
4855 kind,
4856 push_to_history,
4857 cx,
4858 )
4859 .await;
4860 lsp_store.update(cx, |lsp_store, _| {
4861 lsp_store.update_last_formatting_failure(&result);
4862 })?;
4863 result
4864 })
4865 } else if let Some((client, project_id)) = self.upstream_client() {
4866 let buffer_store = self.buffer_store();
4867 cx.spawn(async move |lsp_store, cx| {
4868 let result = client
4869 .request(proto::ApplyCodeActionKind {
4870 project_id,
4871 kind: kind.as_str().to_owned(),
4872 buffer_ids: buffers
4873 .iter()
4874 .map(|buffer| {
4875 buffer.read_with(cx, |buffer, _| buffer.remote_id().into())
4876 })
4877 .collect::<Result<_>>()?,
4878 })
4879 .await
4880 .and_then(|result| result.transaction.context("missing transaction"));
4881 lsp_store.update(cx, |lsp_store, _| {
4882 lsp_store.update_last_formatting_failure(&result);
4883 })?;
4884
4885 let transaction_response = result?;
4886 buffer_store
4887 .update(cx, |buffer_store, cx| {
4888 buffer_store.deserialize_project_transaction(
4889 transaction_response,
4890 push_to_history,
4891 cx,
4892 )
4893 })?
4894 .await
4895 })
4896 } else {
4897 Task::ready(Ok(ProjectTransaction::default()))
4898 }
4899 }
4900
4901 pub fn resolve_inlay_hint(
4902 &self,
4903 hint: InlayHint,
4904 buffer_handle: Entity<Buffer>,
4905 server_id: LanguageServerId,
4906 cx: &mut Context<Self>,
4907 ) -> Task<anyhow::Result<InlayHint>> {
4908 if let Some((upstream_client, project_id)) = self.upstream_client() {
4909 let request = proto::ResolveInlayHint {
4910 project_id,
4911 buffer_id: buffer_handle.read(cx).remote_id().into(),
4912 language_server_id: server_id.0 as u64,
4913 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4914 };
4915 cx.background_spawn(async move {
4916 let response = upstream_client
4917 .request(request)
4918 .await
4919 .context("inlay hints proto request")?;
4920 match response.hint {
4921 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4922 .context("inlay hints proto resolve response conversion"),
4923 None => Ok(hint),
4924 }
4925 })
4926 } else {
4927 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4928 self.language_server_for_local_buffer(buffer, server_id, cx)
4929 .map(|(_, server)| server.clone())
4930 }) else {
4931 return Task::ready(Ok(hint));
4932 };
4933 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4934 return Task::ready(Ok(hint));
4935 }
4936 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4937 cx.spawn(async move |_, cx| {
4938 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4939 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4940 );
4941 let resolved_hint = resolve_task
4942 .await
4943 .into_response()
4944 .context("inlay hint resolve LSP request")?;
4945 let resolved_hint = InlayHints::lsp_to_project_hint(
4946 resolved_hint,
4947 &buffer_handle,
4948 server_id,
4949 ResolveState::Resolved,
4950 false,
4951 cx,
4952 )
4953 .await?;
4954 Ok(resolved_hint)
4955 })
4956 }
4957 }
4958
4959 pub fn resolve_color_presentation(
4960 &mut self,
4961 mut color: DocumentColor,
4962 buffer: Entity<Buffer>,
4963 server_id: LanguageServerId,
4964 cx: &mut Context<Self>,
4965 ) -> Task<Result<DocumentColor>> {
4966 if color.resolved {
4967 return Task::ready(Ok(color));
4968 }
4969
4970 if let Some((upstream_client, project_id)) = self.upstream_client() {
4971 let start = color.lsp_range.start;
4972 let end = color.lsp_range.end;
4973 let request = proto::GetColorPresentation {
4974 project_id,
4975 server_id: server_id.to_proto(),
4976 buffer_id: buffer.read(cx).remote_id().into(),
4977 color: Some(proto::ColorInformation {
4978 red: color.color.red,
4979 green: color.color.green,
4980 blue: color.color.blue,
4981 alpha: color.color.alpha,
4982 lsp_range_start: Some(proto::PointUtf16 {
4983 row: start.line,
4984 column: start.character,
4985 }),
4986 lsp_range_end: Some(proto::PointUtf16 {
4987 row: end.line,
4988 column: end.character,
4989 }),
4990 }),
4991 };
4992 cx.background_spawn(async move {
4993 let response = upstream_client
4994 .request(request)
4995 .await
4996 .context("color presentation proto request")?;
4997 color.resolved = true;
4998 color.color_presentations = response
4999 .presentations
5000 .into_iter()
5001 .map(|presentation| ColorPresentation {
5002 label: SharedString::from(presentation.label),
5003 text_edit: presentation.text_edit.and_then(deserialize_lsp_edit),
5004 additional_text_edits: presentation
5005 .additional_text_edits
5006 .into_iter()
5007 .filter_map(deserialize_lsp_edit)
5008 .collect(),
5009 })
5010 .collect();
5011 Ok(color)
5012 })
5013 } else {
5014 let path = match buffer
5015 .update(cx, |buffer, cx| {
5016 Some(File::from_dyn(buffer.file())?.abs_path(cx))
5017 })
5018 .context("buffer with the missing path")
5019 {
5020 Ok(path) => path,
5021 Err(e) => return Task::ready(Err(e)),
5022 };
5023 let Some(lang_server) = buffer.update(cx, |buffer, cx| {
5024 self.language_server_for_local_buffer(buffer, server_id, cx)
5025 .map(|(_, server)| server.clone())
5026 }) else {
5027 return Task::ready(Ok(color));
5028 };
5029 cx.background_spawn(async move {
5030 let resolve_task = lang_server.request::<lsp::request::ColorPresentationRequest>(
5031 lsp::ColorPresentationParams {
5032 text_document: make_text_document_identifier(&path)?,
5033 color: color.color,
5034 range: color.lsp_range,
5035 work_done_progress_params: Default::default(),
5036 partial_result_params: Default::default(),
5037 },
5038 );
5039 color.color_presentations = resolve_task
5040 .await
5041 .into_response()
5042 .context("color presentation resolve LSP request")?
5043 .into_iter()
5044 .map(|presentation| ColorPresentation {
5045 label: SharedString::from(presentation.label),
5046 text_edit: presentation.text_edit,
5047 additional_text_edits: presentation
5048 .additional_text_edits
5049 .unwrap_or_default(),
5050 })
5051 .collect();
5052 color.resolved = true;
5053 Ok(color)
5054 })
5055 }
5056 }
5057
5058 pub(crate) fn linked_edit(
5059 &mut self,
5060 buffer: &Entity<Buffer>,
5061 position: Anchor,
5062 cx: &mut Context<Self>,
5063 ) -> Task<Result<Vec<Range<Anchor>>>> {
5064 let snapshot = buffer.read(cx).snapshot();
5065 let scope = snapshot.language_scope_at(position);
5066 let Some(server_id) = self
5067 .as_local()
5068 .and_then(|local| {
5069 buffer.update(cx, |buffer, cx| {
5070 local
5071 .language_servers_for_buffer(buffer, cx)
5072 .filter(|(_, server)| {
5073 LinkedEditingRange::check_server_capabilities(server.capabilities())
5074 })
5075 .filter(|(adapter, _)| {
5076 scope
5077 .as_ref()
5078 .map(|scope| scope.language_allowed(&adapter.name))
5079 .unwrap_or(true)
5080 })
5081 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
5082 .next()
5083 })
5084 })
5085 .or_else(|| {
5086 self.upstream_client()
5087 .is_some()
5088 .then_some(LanguageServerToQuery::FirstCapable)
5089 })
5090 .filter(|_| {
5091 maybe!({
5092 let language = buffer.read(cx).language_at(position)?;
5093 Some(
5094 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
5095 .linked_edits,
5096 )
5097 }) == Some(true)
5098 })
5099 else {
5100 return Task::ready(Ok(vec![]));
5101 };
5102
5103 self.request_lsp(
5104 buffer.clone(),
5105 server_id,
5106 LinkedEditingRange { position },
5107 cx,
5108 )
5109 }
5110
5111 fn apply_on_type_formatting(
5112 &mut self,
5113 buffer: Entity<Buffer>,
5114 position: Anchor,
5115 trigger: String,
5116 cx: &mut Context<Self>,
5117 ) -> Task<Result<Option<Transaction>>> {
5118 if let Some((client, project_id)) = self.upstream_client() {
5119 let request = proto::OnTypeFormatting {
5120 project_id,
5121 buffer_id: buffer.read(cx).remote_id().into(),
5122 position: Some(serialize_anchor(&position)),
5123 trigger,
5124 version: serialize_version(&buffer.read(cx).version()),
5125 };
5126 cx.background_spawn(async move {
5127 client
5128 .request(request)
5129 .await?
5130 .transaction
5131 .map(language::proto::deserialize_transaction)
5132 .transpose()
5133 })
5134 } else if let Some(local) = self.as_local_mut() {
5135 let buffer_id = buffer.read(cx).remote_id();
5136 local.buffers_being_formatted.insert(buffer_id);
5137 cx.spawn(async move |this, cx| {
5138 let _cleanup = defer({
5139 let this = this.clone();
5140 let mut cx = cx.clone();
5141 move || {
5142 this.update(&mut cx, |this, _| {
5143 if let Some(local) = this.as_local_mut() {
5144 local.buffers_being_formatted.remove(&buffer_id);
5145 }
5146 })
5147 .ok();
5148 }
5149 });
5150
5151 buffer
5152 .update(cx, |buffer, _| {
5153 buffer.wait_for_edits(Some(position.timestamp))
5154 })?
5155 .await?;
5156 this.update(cx, |this, cx| {
5157 let position = position.to_point_utf16(buffer.read(cx));
5158 this.on_type_format(buffer, position, trigger, false, cx)
5159 })?
5160 .await
5161 })
5162 } else {
5163 Task::ready(Err(anyhow!("No upstream client or local language server")))
5164 }
5165 }
5166
5167 pub fn on_type_format<T: ToPointUtf16>(
5168 &mut self,
5169 buffer: Entity<Buffer>,
5170 position: T,
5171 trigger: String,
5172 push_to_history: bool,
5173 cx: &mut Context<Self>,
5174 ) -> Task<Result<Option<Transaction>>> {
5175 let position = position.to_point_utf16(buffer.read(cx));
5176 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5177 }
5178
5179 fn on_type_format_impl(
5180 &mut self,
5181 buffer: Entity<Buffer>,
5182 position: PointUtf16,
5183 trigger: String,
5184 push_to_history: bool,
5185 cx: &mut Context<Self>,
5186 ) -> Task<Result<Option<Transaction>>> {
5187 let options = buffer.update(cx, |buffer, cx| {
5188 lsp_command::lsp_formatting_options(
5189 language_settings(
5190 buffer.language_at(position).map(|l| l.name()),
5191 buffer.file(),
5192 cx,
5193 )
5194 .as_ref(),
5195 )
5196 });
5197
5198 cx.spawn(async move |this, cx| {
5199 if let Some(waiter) =
5200 buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())?
5201 {
5202 waiter.await?;
5203 }
5204 cx.update(|cx| {
5205 this.update(cx, |this, cx| {
5206 this.request_lsp(
5207 buffer.clone(),
5208 LanguageServerToQuery::FirstCapable,
5209 OnTypeFormatting {
5210 position,
5211 trigger,
5212 options,
5213 push_to_history,
5214 },
5215 cx,
5216 )
5217 })
5218 })??
5219 .await
5220 })
5221 }
5222
5223 pub fn definitions(
5224 &mut self,
5225 buffer_handle: &Entity<Buffer>,
5226 position: PointUtf16,
5227 cx: &mut Context<Self>,
5228 ) -> Task<Result<Vec<LocationLink>>> {
5229 if let Some((upstream_client, project_id)) = self.upstream_client() {
5230 let request_task = upstream_client.request(proto::MultiLspQuery {
5231 buffer_id: buffer_handle.read(cx).remote_id().into(),
5232 version: serialize_version(&buffer_handle.read(cx).version()),
5233 project_id,
5234 strategy: Some(proto::multi_lsp_query::Strategy::All(
5235 proto::AllLanguageServers {},
5236 )),
5237 request: Some(proto::multi_lsp_query::Request::GetDefinition(
5238 GetDefinitions { position }.to_proto(project_id, buffer_handle.read(cx)),
5239 )),
5240 });
5241 let buffer = buffer_handle.clone();
5242 cx.spawn(async move |weak_project, cx| {
5243 let Some(project) = weak_project.upgrade() else {
5244 return Ok(Vec::new());
5245 };
5246 let responses = request_task.await?.responses;
5247 let actions = join_all(
5248 responses
5249 .into_iter()
5250 .filter_map(|lsp_response| match lsp_response.response? {
5251 proto::lsp_response::Response::GetDefinitionResponse(response) => {
5252 Some(response)
5253 }
5254 unexpected => {
5255 debug_panic!("Unexpected response: {unexpected:?}");
5256 None
5257 }
5258 })
5259 .map(|definitions_response| {
5260 GetDefinitions { position }.response_from_proto(
5261 definitions_response,
5262 project.clone(),
5263 buffer.clone(),
5264 cx.clone(),
5265 )
5266 }),
5267 )
5268 .await;
5269
5270 Ok(actions
5271 .into_iter()
5272 .collect::<Result<Vec<Vec<_>>>>()?
5273 .into_iter()
5274 .flatten()
5275 .dedup()
5276 .collect())
5277 })
5278 } else {
5279 let definitions_task = self.request_multiple_lsp_locally(
5280 buffer_handle,
5281 Some(position),
5282 GetDefinitions { position },
5283 cx,
5284 );
5285 cx.background_spawn(async move {
5286 Ok(definitions_task
5287 .await
5288 .into_iter()
5289 .flat_map(|(_, definitions)| definitions)
5290 .dedup()
5291 .collect())
5292 })
5293 }
5294 }
5295
5296 pub fn declarations(
5297 &mut self,
5298 buffer_handle: &Entity<Buffer>,
5299 position: PointUtf16,
5300 cx: &mut Context<Self>,
5301 ) -> Task<Result<Vec<LocationLink>>> {
5302 if let Some((upstream_client, project_id)) = self.upstream_client() {
5303 let request_task = upstream_client.request(proto::MultiLspQuery {
5304 buffer_id: buffer_handle.read(cx).remote_id().into(),
5305 version: serialize_version(&buffer_handle.read(cx).version()),
5306 project_id,
5307 strategy: Some(proto::multi_lsp_query::Strategy::All(
5308 proto::AllLanguageServers {},
5309 )),
5310 request: Some(proto::multi_lsp_query::Request::GetDeclaration(
5311 GetDeclarations { position }.to_proto(project_id, buffer_handle.read(cx)),
5312 )),
5313 });
5314 let buffer = buffer_handle.clone();
5315 cx.spawn(async move |weak_project, cx| {
5316 let Some(project) = weak_project.upgrade() else {
5317 return Ok(Vec::new());
5318 };
5319 let responses = request_task.await?.responses;
5320 let actions = join_all(
5321 responses
5322 .into_iter()
5323 .filter_map(|lsp_response| match lsp_response.response? {
5324 proto::lsp_response::Response::GetDeclarationResponse(response) => {
5325 Some(response)
5326 }
5327 unexpected => {
5328 debug_panic!("Unexpected response: {unexpected:?}");
5329 None
5330 }
5331 })
5332 .map(|declarations_response| {
5333 GetDeclarations { position }.response_from_proto(
5334 declarations_response,
5335 project.clone(),
5336 buffer.clone(),
5337 cx.clone(),
5338 )
5339 }),
5340 )
5341 .await;
5342
5343 Ok(actions
5344 .into_iter()
5345 .collect::<Result<Vec<Vec<_>>>>()?
5346 .into_iter()
5347 .flatten()
5348 .dedup()
5349 .collect())
5350 })
5351 } else {
5352 let declarations_task = self.request_multiple_lsp_locally(
5353 buffer_handle,
5354 Some(position),
5355 GetDeclarations { position },
5356 cx,
5357 );
5358 cx.background_spawn(async move {
5359 Ok(declarations_task
5360 .await
5361 .into_iter()
5362 .flat_map(|(_, declarations)| declarations)
5363 .dedup()
5364 .collect())
5365 })
5366 }
5367 }
5368
5369 pub fn type_definitions(
5370 &mut self,
5371 buffer_handle: &Entity<Buffer>,
5372 position: PointUtf16,
5373 cx: &mut Context<Self>,
5374 ) -> Task<Result<Vec<LocationLink>>> {
5375 if let Some((upstream_client, project_id)) = self.upstream_client() {
5376 let request_task = upstream_client.request(proto::MultiLspQuery {
5377 buffer_id: buffer_handle.read(cx).remote_id().into(),
5378 version: serialize_version(&buffer_handle.read(cx).version()),
5379 project_id,
5380 strategy: Some(proto::multi_lsp_query::Strategy::All(
5381 proto::AllLanguageServers {},
5382 )),
5383 request: Some(proto::multi_lsp_query::Request::GetTypeDefinition(
5384 GetTypeDefinitions { position }.to_proto(project_id, buffer_handle.read(cx)),
5385 )),
5386 });
5387 let buffer = buffer_handle.clone();
5388 cx.spawn(async move |weak_project, cx| {
5389 let Some(project) = weak_project.upgrade() else {
5390 return Ok(Vec::new());
5391 };
5392 let responses = request_task.await?.responses;
5393 let actions = join_all(
5394 responses
5395 .into_iter()
5396 .filter_map(|lsp_response| match lsp_response.response? {
5397 proto::lsp_response::Response::GetTypeDefinitionResponse(response) => {
5398 Some(response)
5399 }
5400 unexpected => {
5401 debug_panic!("Unexpected response: {unexpected:?}");
5402 None
5403 }
5404 })
5405 .map(|type_definitions_response| {
5406 GetTypeDefinitions { position }.response_from_proto(
5407 type_definitions_response,
5408 project.clone(),
5409 buffer.clone(),
5410 cx.clone(),
5411 )
5412 }),
5413 )
5414 .await;
5415
5416 Ok(actions
5417 .into_iter()
5418 .collect::<Result<Vec<Vec<_>>>>()?
5419 .into_iter()
5420 .flatten()
5421 .dedup()
5422 .collect())
5423 })
5424 } else {
5425 let type_definitions_task = self.request_multiple_lsp_locally(
5426 buffer_handle,
5427 Some(position),
5428 GetTypeDefinitions { position },
5429 cx,
5430 );
5431 cx.background_spawn(async move {
5432 Ok(type_definitions_task
5433 .await
5434 .into_iter()
5435 .flat_map(|(_, type_definitions)| type_definitions)
5436 .dedup()
5437 .collect())
5438 })
5439 }
5440 }
5441
5442 pub fn implementations(
5443 &mut self,
5444 buffer_handle: &Entity<Buffer>,
5445 position: PointUtf16,
5446 cx: &mut Context<Self>,
5447 ) -> Task<Result<Vec<LocationLink>>> {
5448 if let Some((upstream_client, project_id)) = self.upstream_client() {
5449 let request_task = upstream_client.request(proto::MultiLspQuery {
5450 buffer_id: buffer_handle.read(cx).remote_id().into(),
5451 version: serialize_version(&buffer_handle.read(cx).version()),
5452 project_id,
5453 strategy: Some(proto::multi_lsp_query::Strategy::All(
5454 proto::AllLanguageServers {},
5455 )),
5456 request: Some(proto::multi_lsp_query::Request::GetImplementation(
5457 GetImplementations { position }.to_proto(project_id, buffer_handle.read(cx)),
5458 )),
5459 });
5460 let buffer = buffer_handle.clone();
5461 cx.spawn(async move |weak_project, cx| {
5462 let Some(project) = weak_project.upgrade() else {
5463 return Ok(Vec::new());
5464 };
5465 let responses = request_task.await?.responses;
5466 let actions = join_all(
5467 responses
5468 .into_iter()
5469 .filter_map(|lsp_response| match lsp_response.response? {
5470 proto::lsp_response::Response::GetImplementationResponse(response) => {
5471 Some(response)
5472 }
5473 unexpected => {
5474 debug_panic!("Unexpected response: {unexpected:?}");
5475 None
5476 }
5477 })
5478 .map(|implementations_response| {
5479 GetImplementations { position }.response_from_proto(
5480 implementations_response,
5481 project.clone(),
5482 buffer.clone(),
5483 cx.clone(),
5484 )
5485 }),
5486 )
5487 .await;
5488
5489 Ok(actions
5490 .into_iter()
5491 .collect::<Result<Vec<Vec<_>>>>()?
5492 .into_iter()
5493 .flatten()
5494 .dedup()
5495 .collect())
5496 })
5497 } else {
5498 let implementations_task = self.request_multiple_lsp_locally(
5499 buffer_handle,
5500 Some(position),
5501 GetImplementations { position },
5502 cx,
5503 );
5504 cx.background_spawn(async move {
5505 Ok(implementations_task
5506 .await
5507 .into_iter()
5508 .flat_map(|(_, implementations)| implementations)
5509 .dedup()
5510 .collect())
5511 })
5512 }
5513 }
5514
5515 pub fn references(
5516 &mut self,
5517 buffer_handle: &Entity<Buffer>,
5518 position: PointUtf16,
5519 cx: &mut Context<Self>,
5520 ) -> Task<Result<Vec<Location>>> {
5521 if let Some((upstream_client, project_id)) = self.upstream_client() {
5522 let request_task = upstream_client.request(proto::MultiLspQuery {
5523 buffer_id: buffer_handle.read(cx).remote_id().into(),
5524 version: serialize_version(&buffer_handle.read(cx).version()),
5525 project_id,
5526 strategy: Some(proto::multi_lsp_query::Strategy::All(
5527 proto::AllLanguageServers {},
5528 )),
5529 request: Some(proto::multi_lsp_query::Request::GetReferences(
5530 GetReferences { position }.to_proto(project_id, buffer_handle.read(cx)),
5531 )),
5532 });
5533 let buffer = buffer_handle.clone();
5534 cx.spawn(async move |weak_project, cx| {
5535 let Some(project) = weak_project.upgrade() else {
5536 return Ok(Vec::new());
5537 };
5538 let responses = request_task.await?.responses;
5539 let actions = join_all(
5540 responses
5541 .into_iter()
5542 .filter_map(|lsp_response| match lsp_response.response? {
5543 proto::lsp_response::Response::GetReferencesResponse(response) => {
5544 Some(response)
5545 }
5546 unexpected => {
5547 debug_panic!("Unexpected response: {unexpected:?}");
5548 None
5549 }
5550 })
5551 .map(|references_response| {
5552 GetReferences { position }.response_from_proto(
5553 references_response,
5554 project.clone(),
5555 buffer.clone(),
5556 cx.clone(),
5557 )
5558 }),
5559 )
5560 .await;
5561
5562 Ok(actions
5563 .into_iter()
5564 .collect::<Result<Vec<Vec<_>>>>()?
5565 .into_iter()
5566 .flatten()
5567 .dedup()
5568 .collect())
5569 })
5570 } else {
5571 let references_task = self.request_multiple_lsp_locally(
5572 buffer_handle,
5573 Some(position),
5574 GetReferences { position },
5575 cx,
5576 );
5577 cx.background_spawn(async move {
5578 Ok(references_task
5579 .await
5580 .into_iter()
5581 .flat_map(|(_, references)| references)
5582 .dedup()
5583 .collect())
5584 })
5585 }
5586 }
5587
5588 pub fn code_actions(
5589 &mut self,
5590 buffer_handle: &Entity<Buffer>,
5591 range: Range<Anchor>,
5592 kinds: Option<Vec<CodeActionKind>>,
5593 cx: &mut Context<Self>,
5594 ) -> Task<Result<Vec<CodeAction>>> {
5595 if let Some((upstream_client, project_id)) = self.upstream_client() {
5596 let request_task = upstream_client.request(proto::MultiLspQuery {
5597 buffer_id: buffer_handle.read(cx).remote_id().into(),
5598 version: serialize_version(&buffer_handle.read(cx).version()),
5599 project_id,
5600 strategy: Some(proto::multi_lsp_query::Strategy::All(
5601 proto::AllLanguageServers {},
5602 )),
5603 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
5604 GetCodeActions {
5605 range: range.clone(),
5606 kinds: kinds.clone(),
5607 }
5608 .to_proto(project_id, buffer_handle.read(cx)),
5609 )),
5610 });
5611 let buffer = buffer_handle.clone();
5612 cx.spawn(async move |weak_project, cx| {
5613 let Some(project) = weak_project.upgrade() else {
5614 return Ok(Vec::new());
5615 };
5616 let responses = request_task.await?.responses;
5617 let actions = join_all(
5618 responses
5619 .into_iter()
5620 .filter_map(|lsp_response| match lsp_response.response? {
5621 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
5622 Some(response)
5623 }
5624 unexpected => {
5625 debug_panic!("Unexpected response: {unexpected:?}");
5626 None
5627 }
5628 })
5629 .map(|code_actions_response| {
5630 GetCodeActions {
5631 range: range.clone(),
5632 kinds: kinds.clone(),
5633 }
5634 .response_from_proto(
5635 code_actions_response,
5636 project.clone(),
5637 buffer.clone(),
5638 cx.clone(),
5639 )
5640 }),
5641 )
5642 .await;
5643
5644 Ok(actions
5645 .into_iter()
5646 .collect::<Result<Vec<Vec<_>>>>()?
5647 .into_iter()
5648 .flatten()
5649 .collect())
5650 })
5651 } else {
5652 let all_actions_task = self.request_multiple_lsp_locally(
5653 buffer_handle,
5654 Some(range.start),
5655 GetCodeActions {
5656 range: range.clone(),
5657 kinds: kinds.clone(),
5658 },
5659 cx,
5660 );
5661 cx.background_spawn(async move {
5662 Ok(all_actions_task
5663 .await
5664 .into_iter()
5665 .flat_map(|(_, actions)| actions)
5666 .collect())
5667 })
5668 }
5669 }
5670
5671 pub fn code_lens_actions(
5672 &mut self,
5673 buffer: &Entity<Buffer>,
5674 cx: &mut Context<Self>,
5675 ) -> CodeLensTask {
5676 let version_queried_for = buffer.read(cx).version();
5677 let buffer_id = buffer.read(cx).remote_id();
5678
5679 if let Some(cached_data) = self.lsp_code_lens.get(&buffer_id) {
5680 if !version_queried_for.changed_since(&cached_data.lens_for_version) {
5681 let has_different_servers = self.as_local().is_some_and(|local| {
5682 local
5683 .buffers_opened_in_servers
5684 .get(&buffer_id)
5685 .cloned()
5686 .unwrap_or_default()
5687 != cached_data.lens.keys().copied().collect()
5688 });
5689 if !has_different_servers {
5690 return Task::ready(Ok(cached_data.lens.values().flatten().cloned().collect()))
5691 .shared();
5692 }
5693 }
5694 }
5695
5696 let lsp_data = self.lsp_code_lens.entry(buffer_id).or_default();
5697 if let Some((updating_for, running_update)) = &lsp_data.update {
5698 if !version_queried_for.changed_since(&updating_for) {
5699 return running_update.clone();
5700 }
5701 }
5702 let buffer = buffer.clone();
5703 let query_version_queried_for = version_queried_for.clone();
5704 let new_task = cx
5705 .spawn(async move |lsp_store, cx| {
5706 cx.background_executor()
5707 .timer(Duration::from_millis(30))
5708 .await;
5709 let fetched_lens = lsp_store
5710 .update(cx, |lsp_store, cx| lsp_store.fetch_code_lens(&buffer, cx))
5711 .map_err(Arc::new)?
5712 .await
5713 .context("fetching code lens")
5714 .map_err(Arc::new);
5715 let fetched_lens = match fetched_lens {
5716 Ok(fetched_lens) => fetched_lens,
5717 Err(e) => {
5718 lsp_store
5719 .update(cx, |lsp_store, _| {
5720 lsp_store.lsp_code_lens.entry(buffer_id).or_default().update = None;
5721 })
5722 .ok();
5723 return Err(e);
5724 }
5725 };
5726
5727 lsp_store
5728 .update(cx, |lsp_store, _| {
5729 let lsp_data = lsp_store.lsp_code_lens.entry(buffer_id).or_default();
5730 if lsp_data.lens_for_version == query_version_queried_for {
5731 lsp_data.lens.extend(fetched_lens.clone());
5732 } else if !lsp_data
5733 .lens_for_version
5734 .changed_since(&query_version_queried_for)
5735 {
5736 lsp_data.lens_for_version = query_version_queried_for;
5737 lsp_data.lens = fetched_lens.clone();
5738 }
5739 lsp_data.update = None;
5740 lsp_data.lens.values().flatten().cloned().collect()
5741 })
5742 .map_err(Arc::new)
5743 })
5744 .shared();
5745 lsp_data.update = Some((version_queried_for, new_task.clone()));
5746 new_task
5747 }
5748
5749 fn fetch_code_lens(
5750 &mut self,
5751 buffer: &Entity<Buffer>,
5752 cx: &mut Context<Self>,
5753 ) -> Task<Result<HashMap<LanguageServerId, Vec<CodeAction>>>> {
5754 if let Some((upstream_client, project_id)) = self.upstream_client() {
5755 let request_task = upstream_client.request(proto::MultiLspQuery {
5756 buffer_id: buffer.read(cx).remote_id().into(),
5757 version: serialize_version(&buffer.read(cx).version()),
5758 project_id,
5759 strategy: Some(proto::multi_lsp_query::Strategy::All(
5760 proto::AllLanguageServers {},
5761 )),
5762 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
5763 GetCodeLens.to_proto(project_id, buffer.read(cx)),
5764 )),
5765 });
5766 let buffer = buffer.clone();
5767 cx.spawn(async move |weak_lsp_store, cx| {
5768 let Some(lsp_store) = weak_lsp_store.upgrade() else {
5769 return Ok(HashMap::default());
5770 };
5771 let responses = request_task.await?.responses;
5772 let code_lens_actions = join_all(
5773 responses
5774 .into_iter()
5775 .filter_map(|lsp_response| {
5776 let response = match lsp_response.response? {
5777 proto::lsp_response::Response::GetCodeLensResponse(response) => {
5778 Some(response)
5779 }
5780 unexpected => {
5781 debug_panic!("Unexpected response: {unexpected:?}");
5782 None
5783 }
5784 }?;
5785 let server_id = LanguageServerId::from_proto(lsp_response.server_id);
5786 Some((server_id, response))
5787 })
5788 .map(|(server_id, code_lens_response)| {
5789 let lsp_store = lsp_store.clone();
5790 let buffer = buffer.clone();
5791 let cx = cx.clone();
5792 async move {
5793 (
5794 server_id,
5795 GetCodeLens
5796 .response_from_proto(
5797 code_lens_response,
5798 lsp_store,
5799 buffer,
5800 cx,
5801 )
5802 .await,
5803 )
5804 }
5805 }),
5806 )
5807 .await;
5808
5809 let mut has_errors = false;
5810 let code_lens_actions = code_lens_actions
5811 .into_iter()
5812 .filter_map(|(server_id, code_lens)| match code_lens {
5813 Ok(code_lens) => Some((server_id, code_lens)),
5814 Err(e) => {
5815 has_errors = true;
5816 log::error!("{e:#}");
5817 None
5818 }
5819 })
5820 .collect::<HashMap<_, _>>();
5821 anyhow::ensure!(
5822 !has_errors || !code_lens_actions.is_empty(),
5823 "Failed to fetch code lens"
5824 );
5825 Ok(code_lens_actions)
5826 })
5827 } else {
5828 let code_lens_actions_task =
5829 self.request_multiple_lsp_locally(buffer, None::<usize>, GetCodeLens, cx);
5830 cx.background_spawn(
5831 async move { Ok(code_lens_actions_task.await.into_iter().collect()) },
5832 )
5833 }
5834 }
5835
5836 #[inline(never)]
5837 pub fn completions(
5838 &self,
5839 buffer: &Entity<Buffer>,
5840 position: PointUtf16,
5841 context: CompletionContext,
5842 cx: &mut Context<Self>,
5843 ) -> Task<Result<Vec<CompletionResponse>>> {
5844 let language_registry = self.languages.clone();
5845
5846 if let Some((upstream_client, project_id)) = self.upstream_client() {
5847 let task = self.send_lsp_proto_request(
5848 buffer.clone(),
5849 upstream_client,
5850 project_id,
5851 GetCompletions { position, context },
5852 cx,
5853 );
5854 let language = buffer.read(cx).language().cloned();
5855
5856 // In the future, we should provide project guests with the names of LSP adapters,
5857 // so that they can use the correct LSP adapter when computing labels. For now,
5858 // guests just use the first LSP adapter associated with the buffer's language.
5859 let lsp_adapter = language.as_ref().and_then(|language| {
5860 language_registry
5861 .lsp_adapters(&language.name())
5862 .first()
5863 .cloned()
5864 });
5865
5866 cx.foreground_executor().spawn(async move {
5867 let completion_response = task.await?;
5868 let completions = populate_labels_for_completions(
5869 completion_response.completions,
5870 language,
5871 lsp_adapter,
5872 )
5873 .await;
5874 Ok(vec![CompletionResponse {
5875 completions,
5876 is_incomplete: completion_response.is_incomplete,
5877 }])
5878 })
5879 } else if let Some(local) = self.as_local() {
5880 let snapshot = buffer.read(cx).snapshot();
5881 let offset = position.to_offset(&snapshot);
5882 let scope = snapshot.language_scope_at(offset);
5883 let language = snapshot.language().cloned();
5884 let completion_settings = language_settings(
5885 language.as_ref().map(|language| language.name()),
5886 buffer.read(cx).file(),
5887 cx,
5888 )
5889 .completions;
5890 if !completion_settings.lsp {
5891 return Task::ready(Ok(Vec::new()));
5892 }
5893
5894 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5895 local
5896 .language_servers_for_buffer(buffer, cx)
5897 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5898 .filter(|(adapter, _)| {
5899 scope
5900 .as_ref()
5901 .map(|scope| scope.language_allowed(&adapter.name))
5902 .unwrap_or(true)
5903 })
5904 .map(|(_, server)| server.server_id())
5905 .collect()
5906 });
5907
5908 let buffer = buffer.clone();
5909 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5910 let lsp_timeout = if lsp_timeout > 0 {
5911 Some(Duration::from_millis(lsp_timeout))
5912 } else {
5913 None
5914 };
5915 cx.spawn(async move |this, cx| {
5916 let mut tasks = Vec::with_capacity(server_ids.len());
5917 this.update(cx, |lsp_store, cx| {
5918 for server_id in server_ids {
5919 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5920 let lsp_timeout = lsp_timeout
5921 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5922 let mut timeout = cx.background_spawn(async move {
5923 match lsp_timeout {
5924 Some(lsp_timeout) => {
5925 lsp_timeout.await;
5926 true
5927 },
5928 None => false,
5929 }
5930 }).fuse();
5931 let mut lsp_request = lsp_store.request_lsp(
5932 buffer.clone(),
5933 LanguageServerToQuery::Other(server_id),
5934 GetCompletions {
5935 position,
5936 context: context.clone(),
5937 },
5938 cx,
5939 ).fuse();
5940 let new_task = cx.background_spawn(async move {
5941 select_biased! {
5942 response = lsp_request => anyhow::Ok(Some(response?)),
5943 timeout_happened = timeout => {
5944 if timeout_happened {
5945 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5946 Ok(None)
5947 } else {
5948 let completions = lsp_request.await?;
5949 Ok(Some(completions))
5950 }
5951 },
5952 }
5953 });
5954 tasks.push((lsp_adapter, new_task));
5955 }
5956 })?;
5957
5958 let futures = tasks.into_iter().map(async |(lsp_adapter, task)| {
5959 let completion_response = task.await.ok()??;
5960 let completions = populate_labels_for_completions(
5961 completion_response.completions,
5962 language.clone(),
5963 lsp_adapter,
5964 )
5965 .await;
5966 Some(CompletionResponse {
5967 completions,
5968 is_incomplete: completion_response.is_incomplete,
5969 })
5970 });
5971
5972 let responses: Vec<Option<CompletionResponse>> = join_all(futures).await;
5973
5974 Ok(responses.into_iter().flatten().collect())
5975 })
5976 } else {
5977 Task::ready(Err(anyhow!("No upstream client or local language server")))
5978 }
5979 }
5980
5981 pub fn resolve_completions(
5982 &self,
5983 buffer: Entity<Buffer>,
5984 completion_indices: Vec<usize>,
5985 completions: Rc<RefCell<Box<[Completion]>>>,
5986 cx: &mut Context<Self>,
5987 ) -> Task<Result<bool>> {
5988 let client = self.upstream_client();
5989
5990 let buffer_id = buffer.read(cx).remote_id();
5991 let buffer_snapshot = buffer.read(cx).snapshot();
5992
5993 cx.spawn(async move |this, cx| {
5994 let mut did_resolve = false;
5995 if let Some((client, project_id)) = client {
5996 for completion_index in completion_indices {
5997 let server_id = {
5998 let completion = &completions.borrow()[completion_index];
5999 completion.source.server_id()
6000 };
6001 if let Some(server_id) = server_id {
6002 if Self::resolve_completion_remote(
6003 project_id,
6004 server_id,
6005 buffer_id,
6006 completions.clone(),
6007 completion_index,
6008 client.clone(),
6009 )
6010 .await
6011 .log_err()
6012 .is_some()
6013 {
6014 did_resolve = true;
6015 }
6016 } else {
6017 resolve_word_completion(
6018 &buffer_snapshot,
6019 &mut completions.borrow_mut()[completion_index],
6020 );
6021 }
6022 }
6023 } else {
6024 for completion_index in completion_indices {
6025 let server_id = {
6026 let completion = &completions.borrow()[completion_index];
6027 completion.source.server_id()
6028 };
6029 if let Some(server_id) = server_id {
6030 let server_and_adapter = this
6031 .read_with(cx, |lsp_store, _| {
6032 let server = lsp_store.language_server_for_id(server_id)?;
6033 let adapter =
6034 lsp_store.language_server_adapter_for_id(server.server_id())?;
6035 Some((server, adapter))
6036 })
6037 .ok()
6038 .flatten();
6039 let Some((server, adapter)) = server_and_adapter else {
6040 continue;
6041 };
6042
6043 let resolved = Self::resolve_completion_local(
6044 server,
6045 completions.clone(),
6046 completion_index,
6047 )
6048 .await
6049 .log_err()
6050 .is_some();
6051 if resolved {
6052 Self::regenerate_completion_labels(
6053 adapter,
6054 &buffer_snapshot,
6055 completions.clone(),
6056 completion_index,
6057 )
6058 .await
6059 .log_err();
6060 did_resolve = true;
6061 }
6062 } else {
6063 resolve_word_completion(
6064 &buffer_snapshot,
6065 &mut completions.borrow_mut()[completion_index],
6066 );
6067 }
6068 }
6069 }
6070
6071 Ok(did_resolve)
6072 })
6073 }
6074
6075 async fn resolve_completion_local(
6076 server: Arc<lsp::LanguageServer>,
6077 completions: Rc<RefCell<Box<[Completion]>>>,
6078 completion_index: usize,
6079 ) -> Result<()> {
6080 let server_id = server.server_id();
6081 let can_resolve = server
6082 .capabilities()
6083 .completion_provider
6084 .as_ref()
6085 .and_then(|options| options.resolve_provider)
6086 .unwrap_or(false);
6087 if !can_resolve {
6088 return Ok(());
6089 }
6090
6091 let request = {
6092 let completion = &completions.borrow()[completion_index];
6093 match &completion.source {
6094 CompletionSource::Lsp {
6095 lsp_completion,
6096 resolved,
6097 server_id: completion_server_id,
6098 ..
6099 } => {
6100 if *resolved {
6101 return Ok(());
6102 }
6103 anyhow::ensure!(
6104 server_id == *completion_server_id,
6105 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
6106 );
6107 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
6108 }
6109 CompletionSource::BufferWord { .. }
6110 | CompletionSource::Dap { .. }
6111 | CompletionSource::Custom => {
6112 return Ok(());
6113 }
6114 }
6115 };
6116 let resolved_completion = request
6117 .await
6118 .into_response()
6119 .context("resolve completion")?;
6120
6121 // We must not use any data such as sortText, filterText, insertText and textEdit to edit `Completion` since they are not suppose change during resolve.
6122 // Refer: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
6123
6124 let mut completions = completions.borrow_mut();
6125 let completion = &mut completions[completion_index];
6126 if let CompletionSource::Lsp {
6127 lsp_completion,
6128 resolved,
6129 server_id: completion_server_id,
6130 ..
6131 } = &mut completion.source
6132 {
6133 if *resolved {
6134 return Ok(());
6135 }
6136 anyhow::ensure!(
6137 server_id == *completion_server_id,
6138 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
6139 );
6140 *lsp_completion = Box::new(resolved_completion);
6141 *resolved = true;
6142 }
6143 Ok(())
6144 }
6145
6146 async fn regenerate_completion_labels(
6147 adapter: Arc<CachedLspAdapter>,
6148 snapshot: &BufferSnapshot,
6149 completions: Rc<RefCell<Box<[Completion]>>>,
6150 completion_index: usize,
6151 ) -> Result<()> {
6152 let completion_item = completions.borrow()[completion_index]
6153 .source
6154 .lsp_completion(true)
6155 .map(Cow::into_owned);
6156 if let Some(lsp_documentation) = completion_item
6157 .as_ref()
6158 .and_then(|completion_item| completion_item.documentation.clone())
6159 {
6160 let mut completions = completions.borrow_mut();
6161 let completion = &mut completions[completion_index];
6162 completion.documentation = Some(lsp_documentation.into());
6163 } else {
6164 let mut completions = completions.borrow_mut();
6165 let completion = &mut completions[completion_index];
6166 completion.documentation = Some(CompletionDocumentation::Undocumented);
6167 }
6168
6169 let mut new_label = match completion_item {
6170 Some(completion_item) => {
6171 // 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
6172 // So we have to update the label here anyway...
6173 let language = snapshot.language();
6174 match language {
6175 Some(language) => {
6176 adapter
6177 .labels_for_completions(
6178 std::slice::from_ref(&completion_item),
6179 language,
6180 )
6181 .await?
6182 }
6183 None => Vec::new(),
6184 }
6185 .pop()
6186 .flatten()
6187 .unwrap_or_else(|| {
6188 CodeLabel::fallback_for_completion(
6189 &completion_item,
6190 language.map(|language| language.as_ref()),
6191 )
6192 })
6193 }
6194 None => CodeLabel::plain(
6195 completions.borrow()[completion_index].new_text.clone(),
6196 None,
6197 ),
6198 };
6199 ensure_uniform_list_compatible_label(&mut new_label);
6200
6201 let mut completions = completions.borrow_mut();
6202 let completion = &mut completions[completion_index];
6203 if completion.label.filter_text() == new_label.filter_text() {
6204 completion.label = new_label;
6205 } else {
6206 log::error!(
6207 "Resolved completion changed display label from {} to {}. \
6208 Refusing to apply this because it changes the fuzzy match text from {} to {}",
6209 completion.label.text(),
6210 new_label.text(),
6211 completion.label.filter_text(),
6212 new_label.filter_text()
6213 );
6214 }
6215
6216 Ok(())
6217 }
6218
6219 async fn resolve_completion_remote(
6220 project_id: u64,
6221 server_id: LanguageServerId,
6222 buffer_id: BufferId,
6223 completions: Rc<RefCell<Box<[Completion]>>>,
6224 completion_index: usize,
6225 client: AnyProtoClient,
6226 ) -> Result<()> {
6227 let lsp_completion = {
6228 let completion = &completions.borrow()[completion_index];
6229 match &completion.source {
6230 CompletionSource::Lsp {
6231 lsp_completion,
6232 resolved,
6233 server_id: completion_server_id,
6234 ..
6235 } => {
6236 anyhow::ensure!(
6237 server_id == *completion_server_id,
6238 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
6239 );
6240 if *resolved {
6241 return Ok(());
6242 }
6243 serde_json::to_string(lsp_completion).unwrap().into_bytes()
6244 }
6245 CompletionSource::Custom
6246 | CompletionSource::Dap { .. }
6247 | CompletionSource::BufferWord { .. } => {
6248 return Ok(());
6249 }
6250 }
6251 };
6252 let request = proto::ResolveCompletionDocumentation {
6253 project_id,
6254 language_server_id: server_id.0 as u64,
6255 lsp_completion,
6256 buffer_id: buffer_id.into(),
6257 };
6258
6259 let response = client
6260 .request(request)
6261 .await
6262 .context("completion documentation resolve proto request")?;
6263 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
6264
6265 let documentation = if response.documentation.is_empty() {
6266 CompletionDocumentation::Undocumented
6267 } else if response.documentation_is_markdown {
6268 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
6269 } else if response.documentation.lines().count() <= 1 {
6270 CompletionDocumentation::SingleLine(response.documentation.into())
6271 } else {
6272 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
6273 };
6274
6275 let mut completions = completions.borrow_mut();
6276 let completion = &mut completions[completion_index];
6277 completion.documentation = Some(documentation);
6278 if let CompletionSource::Lsp {
6279 insert_range,
6280 lsp_completion,
6281 resolved,
6282 server_id: completion_server_id,
6283 lsp_defaults: _,
6284 } = &mut completion.source
6285 {
6286 let completion_insert_range = response
6287 .old_insert_start
6288 .and_then(deserialize_anchor)
6289 .zip(response.old_insert_end.and_then(deserialize_anchor));
6290 *insert_range = completion_insert_range.map(|(start, end)| start..end);
6291
6292 if *resolved {
6293 return Ok(());
6294 }
6295 anyhow::ensure!(
6296 server_id == *completion_server_id,
6297 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
6298 );
6299 *lsp_completion = Box::new(resolved_lsp_completion);
6300 *resolved = true;
6301 }
6302
6303 let replace_range = response
6304 .old_replace_start
6305 .and_then(deserialize_anchor)
6306 .zip(response.old_replace_end.and_then(deserialize_anchor));
6307 if let Some((old_replace_start, old_replace_end)) = replace_range {
6308 if !response.new_text.is_empty() {
6309 completion.new_text = response.new_text;
6310 completion.replace_range = old_replace_start..old_replace_end;
6311 }
6312 }
6313
6314 Ok(())
6315 }
6316
6317 pub fn apply_additional_edits_for_completion(
6318 &self,
6319 buffer_handle: Entity<Buffer>,
6320 completions: Rc<RefCell<Box<[Completion]>>>,
6321 completion_index: usize,
6322 push_to_history: bool,
6323 cx: &mut Context<Self>,
6324 ) -> Task<Result<Option<Transaction>>> {
6325 if let Some((client, project_id)) = self.upstream_client() {
6326 let buffer = buffer_handle.read(cx);
6327 let buffer_id = buffer.remote_id();
6328 cx.spawn(async move |_, cx| {
6329 let request = {
6330 let completion = completions.borrow()[completion_index].clone();
6331 proto::ApplyCompletionAdditionalEdits {
6332 project_id,
6333 buffer_id: buffer_id.into(),
6334 completion: Some(Self::serialize_completion(&CoreCompletion {
6335 replace_range: completion.replace_range,
6336 new_text: completion.new_text,
6337 source: completion.source,
6338 })),
6339 }
6340 };
6341
6342 if let Some(transaction) = client.request(request).await?.transaction {
6343 let transaction = language::proto::deserialize_transaction(transaction)?;
6344 buffer_handle
6345 .update(cx, |buffer, _| {
6346 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6347 })?
6348 .await?;
6349 if push_to_history {
6350 buffer_handle.update(cx, |buffer, _| {
6351 buffer.push_transaction(transaction.clone(), Instant::now());
6352 buffer.finalize_last_transaction();
6353 })?;
6354 }
6355 Ok(Some(transaction))
6356 } else {
6357 Ok(None)
6358 }
6359 })
6360 } else {
6361 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
6362 let completion = &completions.borrow()[completion_index];
6363 let server_id = completion.source.server_id()?;
6364 Some(
6365 self.language_server_for_local_buffer(buffer, server_id, cx)?
6366 .1
6367 .clone(),
6368 )
6369 }) else {
6370 return Task::ready(Ok(None));
6371 };
6372
6373 cx.spawn(async move |this, cx| {
6374 Self::resolve_completion_local(
6375 server.clone(),
6376 completions.clone(),
6377 completion_index,
6378 )
6379 .await
6380 .context("resolving completion")?;
6381 let completion = completions.borrow()[completion_index].clone();
6382 let additional_text_edits = completion
6383 .source
6384 .lsp_completion(true)
6385 .as_ref()
6386 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
6387 if let Some(edits) = additional_text_edits {
6388 let edits = this
6389 .update(cx, |this, cx| {
6390 this.as_local_mut().unwrap().edits_from_lsp(
6391 &buffer_handle,
6392 edits,
6393 server.server_id(),
6394 None,
6395 cx,
6396 )
6397 })?
6398 .await?;
6399
6400 buffer_handle.update(cx, |buffer, cx| {
6401 buffer.finalize_last_transaction();
6402 buffer.start_transaction();
6403
6404 for (range, text) in edits {
6405 let primary = &completion.replace_range;
6406 let start_within = primary.start.cmp(&range.start, buffer).is_le()
6407 && primary.end.cmp(&range.start, buffer).is_ge();
6408 let end_within = range.start.cmp(&primary.end, buffer).is_le()
6409 && range.end.cmp(&primary.end, buffer).is_ge();
6410
6411 //Skip additional edits which overlap with the primary completion edit
6412 //https://github.com/zed-industries/zed/pull/1871
6413 if !start_within && !end_within {
6414 buffer.edit([(range, text)], None, cx);
6415 }
6416 }
6417
6418 let transaction = if buffer.end_transaction(cx).is_some() {
6419 let transaction = buffer.finalize_last_transaction().unwrap().clone();
6420 if !push_to_history {
6421 buffer.forget_transaction(transaction.id);
6422 }
6423 Some(transaction)
6424 } else {
6425 None
6426 };
6427 Ok(transaction)
6428 })?
6429 } else {
6430 Ok(None)
6431 }
6432 })
6433 }
6434 }
6435
6436 pub fn pull_diagnostics(
6437 &mut self,
6438 buffer_handle: Entity<Buffer>,
6439 cx: &mut Context<Self>,
6440 ) -> Task<Result<Vec<LspPullDiagnostics>>> {
6441 let buffer = buffer_handle.read(cx);
6442 let buffer_id = buffer.remote_id();
6443
6444 if let Some((client, upstream_project_id)) = self.upstream_client() {
6445 let request_task = client.request(proto::MultiLspQuery {
6446 buffer_id: buffer_id.to_proto(),
6447 version: serialize_version(&buffer_handle.read(cx).version()),
6448 project_id: upstream_project_id,
6449 strategy: Some(proto::multi_lsp_query::Strategy::All(
6450 proto::AllLanguageServers {},
6451 )),
6452 request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
6453 proto::GetDocumentDiagnostics {
6454 project_id: upstream_project_id,
6455 buffer_id: buffer_id.to_proto(),
6456 version: serialize_version(&buffer_handle.read(cx).version()),
6457 },
6458 )),
6459 });
6460 cx.background_spawn(async move {
6461 Ok(request_task
6462 .await?
6463 .responses
6464 .into_iter()
6465 .filter_map(|lsp_response| match lsp_response.response? {
6466 proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
6467 Some(response)
6468 }
6469 unexpected => {
6470 debug_panic!("Unexpected response: {unexpected:?}");
6471 None
6472 }
6473 })
6474 .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
6475 .collect())
6476 })
6477 } else {
6478 let server_ids = buffer_handle.update(cx, |buffer, cx| {
6479 self.language_servers_for_local_buffer(buffer, cx)
6480 .map(|(_, server)| server.server_id())
6481 .collect::<Vec<_>>()
6482 });
6483 let pull_diagnostics = server_ids
6484 .into_iter()
6485 .map(|server_id| {
6486 let result_id = self.result_id(server_id, buffer_id, cx);
6487 self.request_lsp(
6488 buffer_handle.clone(),
6489 LanguageServerToQuery::Other(server_id),
6490 GetDocumentDiagnostics {
6491 previous_result_id: result_id,
6492 },
6493 cx,
6494 )
6495 })
6496 .collect::<Vec<_>>();
6497
6498 cx.background_spawn(async move {
6499 let mut responses = Vec::new();
6500 for diagnostics in join_all(pull_diagnostics).await {
6501 responses.extend(diagnostics?);
6502 }
6503 Ok(responses)
6504 })
6505 }
6506 }
6507
6508 pub fn inlay_hints(
6509 &mut self,
6510 buffer_handle: Entity<Buffer>,
6511 range: Range<Anchor>,
6512 cx: &mut Context<Self>,
6513 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6514 let buffer = buffer_handle.read(cx);
6515 let range_start = range.start;
6516 let range_end = range.end;
6517 let buffer_id = buffer.remote_id().into();
6518 let lsp_request = InlayHints { range };
6519
6520 if let Some((client, project_id)) = self.upstream_client() {
6521 let request = proto::InlayHints {
6522 project_id,
6523 buffer_id,
6524 start: Some(serialize_anchor(&range_start)),
6525 end: Some(serialize_anchor(&range_end)),
6526 version: serialize_version(&buffer_handle.read(cx).version()),
6527 };
6528 cx.spawn(async move |project, cx| {
6529 let response = client
6530 .request(request)
6531 .await
6532 .context("inlay hints proto request")?;
6533 LspCommand::response_from_proto(
6534 lsp_request,
6535 response,
6536 project.upgrade().context("No project")?,
6537 buffer_handle.clone(),
6538 cx.clone(),
6539 )
6540 .await
6541 .context("inlay hints proto response conversion")
6542 })
6543 } else {
6544 let lsp_request_task = self.request_lsp(
6545 buffer_handle.clone(),
6546 LanguageServerToQuery::FirstCapable,
6547 lsp_request,
6548 cx,
6549 );
6550 cx.spawn(async move |_, cx| {
6551 buffer_handle
6552 .update(cx, |buffer, _| {
6553 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6554 })?
6555 .await
6556 .context("waiting for inlay hint request range edits")?;
6557 lsp_request_task.await.context("inlay hints LSP request")
6558 })
6559 }
6560 }
6561
6562 pub fn pull_diagnostics_for_buffer(
6563 &mut self,
6564 buffer: Entity<Buffer>,
6565 cx: &mut Context<Self>,
6566 ) -> Task<anyhow::Result<()>> {
6567 let buffer_id = buffer.read(cx).remote_id();
6568 let diagnostics = self.pull_diagnostics(buffer, cx);
6569 cx.spawn(async move |lsp_store, cx| {
6570 let diagnostics = diagnostics.await.context("pulling diagnostics")?;
6571 lsp_store.update(cx, |lsp_store, cx| {
6572 if lsp_store.as_local().is_none() {
6573 return;
6574 }
6575
6576 for diagnostics_set in diagnostics {
6577 let LspPullDiagnostics::Response {
6578 server_id,
6579 uri,
6580 diagnostics,
6581 } = diagnostics_set
6582 else {
6583 continue;
6584 };
6585
6586 let adapter = lsp_store.language_server_adapter_for_id(server_id);
6587 let disk_based_sources = adapter
6588 .as_ref()
6589 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
6590 .unwrap_or(&[]);
6591 match diagnostics {
6592 PulledDiagnostics::Unchanged { result_id } => {
6593 lsp_store
6594 .merge_diagnostics(
6595 server_id,
6596 lsp::PublishDiagnosticsParams {
6597 uri: uri.clone(),
6598 diagnostics: Vec::new(),
6599 version: None,
6600 },
6601 Some(result_id),
6602 DiagnosticSourceKind::Pulled,
6603 disk_based_sources,
6604 |_, _, _| true,
6605 cx,
6606 )
6607 .log_err();
6608 }
6609 PulledDiagnostics::Changed {
6610 diagnostics,
6611 result_id,
6612 } => {
6613 lsp_store
6614 .merge_diagnostics(
6615 server_id,
6616 lsp::PublishDiagnosticsParams {
6617 uri: uri.clone(),
6618 diagnostics,
6619 version: None,
6620 },
6621 result_id,
6622 DiagnosticSourceKind::Pulled,
6623 disk_based_sources,
6624 |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
6625 DiagnosticSourceKind::Pulled => {
6626 buffer.remote_id() != buffer_id
6627 }
6628 DiagnosticSourceKind::Other
6629 | DiagnosticSourceKind::Pushed => true,
6630 },
6631 cx,
6632 )
6633 .log_err();
6634 }
6635 }
6636 }
6637 })
6638 })
6639 }
6640
6641 pub fn document_colors(
6642 &mut self,
6643 fetch_strategy: LspFetchStrategy,
6644 buffer: Entity<Buffer>,
6645 cx: &mut Context<Self>,
6646 ) -> Option<DocumentColorTask> {
6647 let version_queried_for = buffer.read(cx).version();
6648 let buffer_id = buffer.read(cx).remote_id();
6649
6650 match fetch_strategy {
6651 LspFetchStrategy::IgnoreCache => {}
6652 LspFetchStrategy::UseCache {
6653 known_cache_version,
6654 } => {
6655 if let Some(cached_data) = self.lsp_document_colors.get(&buffer_id) {
6656 if !version_queried_for.changed_since(&cached_data.colors_for_version) {
6657 let has_different_servers = self.as_local().is_some_and(|local| {
6658 local
6659 .buffers_opened_in_servers
6660 .get(&buffer_id)
6661 .cloned()
6662 .unwrap_or_default()
6663 != cached_data.colors.keys().copied().collect()
6664 });
6665 if !has_different_servers {
6666 if Some(cached_data.cache_version) == known_cache_version {
6667 return None;
6668 } else {
6669 return Some(
6670 Task::ready(Ok(DocumentColors {
6671 colors: cached_data
6672 .colors
6673 .values()
6674 .flatten()
6675 .cloned()
6676 .collect(),
6677 cache_version: Some(cached_data.cache_version),
6678 }))
6679 .shared(),
6680 );
6681 }
6682 }
6683 }
6684 }
6685 }
6686 }
6687
6688 let lsp_data = self.lsp_document_colors.entry(buffer_id).or_default();
6689 if let Some((updating_for, running_update)) = &lsp_data.colors_update {
6690 if !version_queried_for.changed_since(&updating_for) {
6691 return Some(running_update.clone());
6692 }
6693 }
6694 let query_version_queried_for = version_queried_for.clone();
6695 let new_task = cx
6696 .spawn(async move |lsp_store, cx| {
6697 cx.background_executor()
6698 .timer(Duration::from_millis(30))
6699 .await;
6700 let fetched_colors = lsp_store
6701 .update(cx, |lsp_store, cx| {
6702 lsp_store.fetch_document_colors_for_buffer(&buffer, cx)
6703 })?
6704 .await
6705 .context("fetching document colors")
6706 .map_err(Arc::new);
6707 let fetched_colors = match fetched_colors {
6708 Ok(fetched_colors) => {
6709 if fetch_strategy != LspFetchStrategy::IgnoreCache
6710 && Some(true)
6711 == buffer
6712 .update(cx, |buffer, _| {
6713 buffer.version() != query_version_queried_for
6714 })
6715 .ok()
6716 {
6717 return Ok(DocumentColors::default());
6718 }
6719 fetched_colors
6720 }
6721 Err(e) => {
6722 lsp_store
6723 .update(cx, |lsp_store, _| {
6724 lsp_store
6725 .lsp_document_colors
6726 .entry(buffer_id)
6727 .or_default()
6728 .colors_update = None;
6729 })
6730 .ok();
6731 return Err(e);
6732 }
6733 };
6734
6735 lsp_store
6736 .update(cx, |lsp_store, _| {
6737 let lsp_data = lsp_store.lsp_document_colors.entry(buffer_id).or_default();
6738
6739 if lsp_data.colors_for_version == query_version_queried_for {
6740 lsp_data.colors.extend(fetched_colors.clone());
6741 lsp_data.cache_version += 1;
6742 } else if !lsp_data
6743 .colors_for_version
6744 .changed_since(&query_version_queried_for)
6745 {
6746 lsp_data.colors_for_version = query_version_queried_for;
6747 lsp_data.colors = fetched_colors.clone();
6748 lsp_data.cache_version += 1;
6749 }
6750 lsp_data.colors_update = None;
6751 let colors = lsp_data
6752 .colors
6753 .values()
6754 .flatten()
6755 .cloned()
6756 .collect::<HashSet<_>>();
6757 DocumentColors {
6758 colors,
6759 cache_version: Some(lsp_data.cache_version),
6760 }
6761 })
6762 .map_err(Arc::new)
6763 })
6764 .shared();
6765 lsp_data.colors_update = Some((version_queried_for, new_task.clone()));
6766 Some(new_task)
6767 }
6768
6769 fn fetch_document_colors_for_buffer(
6770 &mut self,
6771 buffer: &Entity<Buffer>,
6772 cx: &mut Context<Self>,
6773 ) -> Task<anyhow::Result<HashMap<LanguageServerId, HashSet<DocumentColor>>>> {
6774 if let Some((client, project_id)) = self.upstream_client() {
6775 let request_task = client.request(proto::MultiLspQuery {
6776 project_id,
6777 buffer_id: buffer.read(cx).remote_id().to_proto(),
6778 version: serialize_version(&buffer.read(cx).version()),
6779 strategy: Some(proto::multi_lsp_query::Strategy::All(
6780 proto::AllLanguageServers {},
6781 )),
6782 request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
6783 GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
6784 )),
6785 });
6786 let buffer = buffer.clone();
6787 cx.spawn(async move |project, cx| {
6788 let Some(project) = project.upgrade() else {
6789 return Ok(HashMap::default());
6790 };
6791 let colors = join_all(
6792 request_task
6793 .await
6794 .log_err()
6795 .map(|response| response.responses)
6796 .unwrap_or_default()
6797 .into_iter()
6798 .filter_map(|lsp_response| match lsp_response.response? {
6799 proto::lsp_response::Response::GetDocumentColorResponse(response) => {
6800 Some((
6801 LanguageServerId::from_proto(lsp_response.server_id),
6802 response,
6803 ))
6804 }
6805 unexpected => {
6806 debug_panic!("Unexpected response: {unexpected:?}");
6807 None
6808 }
6809 })
6810 .map(|(server_id, color_response)| {
6811 let response = GetDocumentColor {}.response_from_proto(
6812 color_response,
6813 project.clone(),
6814 buffer.clone(),
6815 cx.clone(),
6816 );
6817 async move { (server_id, response.await.log_err().unwrap_or_default()) }
6818 }),
6819 )
6820 .await
6821 .into_iter()
6822 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6823 acc.entry(server_id)
6824 .or_insert_with(HashSet::default)
6825 .extend(colors);
6826 acc
6827 });
6828 Ok(colors)
6829 })
6830 } else {
6831 let document_colors_task =
6832 self.request_multiple_lsp_locally(buffer, None::<usize>, GetDocumentColor, cx);
6833 cx.background_spawn(async move {
6834 Ok(document_colors_task
6835 .await
6836 .into_iter()
6837 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6838 acc.entry(server_id)
6839 .or_insert_with(HashSet::default)
6840 .extend(colors);
6841 acc
6842 })
6843 .into_iter()
6844 .collect())
6845 })
6846 }
6847 }
6848
6849 pub fn signature_help<T: ToPointUtf16>(
6850 &mut self,
6851 buffer: &Entity<Buffer>,
6852 position: T,
6853 cx: &mut Context<Self>,
6854 ) -> Task<Vec<SignatureHelp>> {
6855 let position = position.to_point_utf16(buffer.read(cx));
6856
6857 if let Some((client, upstream_project_id)) = self.upstream_client() {
6858 let request_task = client.request(proto::MultiLspQuery {
6859 buffer_id: buffer.read(cx).remote_id().into(),
6860 version: serialize_version(&buffer.read(cx).version()),
6861 project_id: upstream_project_id,
6862 strategy: Some(proto::multi_lsp_query::Strategy::All(
6863 proto::AllLanguageServers {},
6864 )),
6865 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
6866 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
6867 )),
6868 });
6869 let buffer = buffer.clone();
6870 cx.spawn(async move |weak_project, cx| {
6871 let Some(project) = weak_project.upgrade() else {
6872 return Vec::new();
6873 };
6874 join_all(
6875 request_task
6876 .await
6877 .log_err()
6878 .map(|response| response.responses)
6879 .unwrap_or_default()
6880 .into_iter()
6881 .filter_map(|lsp_response| match lsp_response.response? {
6882 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
6883 Some(response)
6884 }
6885 unexpected => {
6886 debug_panic!("Unexpected response: {unexpected:?}");
6887 None
6888 }
6889 })
6890 .map(|signature_response| {
6891 let response = GetSignatureHelp { position }.response_from_proto(
6892 signature_response,
6893 project.clone(),
6894 buffer.clone(),
6895 cx.clone(),
6896 );
6897 async move { response.await.log_err().flatten() }
6898 }),
6899 )
6900 .await
6901 .into_iter()
6902 .flatten()
6903 .collect()
6904 })
6905 } else {
6906 let all_actions_task = self.request_multiple_lsp_locally(
6907 buffer,
6908 Some(position),
6909 GetSignatureHelp { position },
6910 cx,
6911 );
6912 cx.background_spawn(async move {
6913 all_actions_task
6914 .await
6915 .into_iter()
6916 .flat_map(|(_, actions)| actions)
6917 .collect::<Vec<_>>()
6918 })
6919 }
6920 }
6921
6922 pub fn hover(
6923 &mut self,
6924 buffer: &Entity<Buffer>,
6925 position: PointUtf16,
6926 cx: &mut Context<Self>,
6927 ) -> Task<Vec<Hover>> {
6928 if let Some((client, upstream_project_id)) = self.upstream_client() {
6929 let request_task = client.request(proto::MultiLspQuery {
6930 buffer_id: buffer.read(cx).remote_id().into(),
6931 version: serialize_version(&buffer.read(cx).version()),
6932 project_id: upstream_project_id,
6933 strategy: Some(proto::multi_lsp_query::Strategy::All(
6934 proto::AllLanguageServers {},
6935 )),
6936 request: Some(proto::multi_lsp_query::Request::GetHover(
6937 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
6938 )),
6939 });
6940 let buffer = buffer.clone();
6941 cx.spawn(async move |weak_project, cx| {
6942 let Some(project) = weak_project.upgrade() else {
6943 return Vec::new();
6944 };
6945 join_all(
6946 request_task
6947 .await
6948 .log_err()
6949 .map(|response| response.responses)
6950 .unwrap_or_default()
6951 .into_iter()
6952 .filter_map(|lsp_response| match lsp_response.response? {
6953 proto::lsp_response::Response::GetHoverResponse(response) => {
6954 Some(response)
6955 }
6956 unexpected => {
6957 debug_panic!("Unexpected response: {unexpected:?}");
6958 None
6959 }
6960 })
6961 .map(|hover_response| {
6962 let response = GetHover { position }.response_from_proto(
6963 hover_response,
6964 project.clone(),
6965 buffer.clone(),
6966 cx.clone(),
6967 );
6968 async move {
6969 response
6970 .await
6971 .log_err()
6972 .flatten()
6973 .and_then(remove_empty_hover_blocks)
6974 }
6975 }),
6976 )
6977 .await
6978 .into_iter()
6979 .flatten()
6980 .collect()
6981 })
6982 } else {
6983 let all_actions_task = self.request_multiple_lsp_locally(
6984 buffer,
6985 Some(position),
6986 GetHover { position },
6987 cx,
6988 );
6989 cx.background_spawn(async move {
6990 all_actions_task
6991 .await
6992 .into_iter()
6993 .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
6994 .collect::<Vec<Hover>>()
6995 })
6996 }
6997 }
6998
6999 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
7000 let language_registry = self.languages.clone();
7001
7002 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
7003 let request = upstream_client.request(proto::GetProjectSymbols {
7004 project_id: *project_id,
7005 query: query.to_string(),
7006 });
7007 cx.foreground_executor().spawn(async move {
7008 let response = request.await?;
7009 let mut symbols = Vec::new();
7010 let core_symbols = response
7011 .symbols
7012 .into_iter()
7013 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
7014 .collect::<Vec<_>>();
7015 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
7016 .await;
7017 Ok(symbols)
7018 })
7019 } else if let Some(local) = self.as_local() {
7020 struct WorkspaceSymbolsResult {
7021 server_id: LanguageServerId,
7022 lsp_adapter: Arc<CachedLspAdapter>,
7023 worktree: WeakEntity<Worktree>,
7024 worktree_abs_path: Arc<Path>,
7025 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
7026 }
7027
7028 let mut requests = Vec::new();
7029 let mut requested_servers = BTreeSet::new();
7030 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
7031 let Some(worktree_handle) = self
7032 .worktree_store
7033 .read(cx)
7034 .worktree_for_id(*worktree_id, cx)
7035 else {
7036 continue;
7037 };
7038 let worktree = worktree_handle.read(cx);
7039 if !worktree.is_visible() {
7040 continue;
7041 }
7042
7043 let mut servers_to_query = server_ids
7044 .difference(&requested_servers)
7045 .cloned()
7046 .collect::<BTreeSet<_>>();
7047 for server_id in &servers_to_query {
7048 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
7049 Some(LanguageServerState::Running {
7050 adapter, server, ..
7051 }) => (adapter.clone(), server),
7052
7053 _ => continue 'next_server,
7054 };
7055 let supports_workspace_symbol_request =
7056 match server.capabilities().workspace_symbol_provider {
7057 Some(OneOf::Left(supported)) => supported,
7058 Some(OneOf::Right(_)) => true,
7059 None => false,
7060 };
7061 if !supports_workspace_symbol_request {
7062 continue 'next_server;
7063 }
7064 let worktree_abs_path = worktree.abs_path().clone();
7065 let worktree_handle = worktree_handle.clone();
7066 let server_id = server.server_id();
7067 requests.push(
7068 server
7069 .request::<lsp::request::WorkspaceSymbolRequest>(
7070 lsp::WorkspaceSymbolParams {
7071 query: query.to_string(),
7072 ..Default::default()
7073 },
7074 )
7075 .map(move |response| {
7076 let lsp_symbols = response.into_response()
7077 .context("workspace symbols request")
7078 .log_err()
7079 .flatten()
7080 .map(|symbol_response| match symbol_response {
7081 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
7082 flat_responses.into_iter().map(|lsp_symbol| {
7083 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
7084 }).collect::<Vec<_>>()
7085 }
7086 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
7087 nested_responses.into_iter().filter_map(|lsp_symbol| {
7088 let location = match lsp_symbol.location {
7089 OneOf::Left(location) => location,
7090 OneOf::Right(_) => {
7091 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
7092 return None
7093 }
7094 };
7095 Some((lsp_symbol.name, lsp_symbol.kind, location))
7096 }).collect::<Vec<_>>()
7097 }
7098 }).unwrap_or_default();
7099
7100 WorkspaceSymbolsResult {
7101 server_id,
7102 lsp_adapter,
7103 worktree: worktree_handle.downgrade(),
7104 worktree_abs_path,
7105 lsp_symbols,
7106 }
7107 }),
7108 );
7109 }
7110 requested_servers.append(&mut servers_to_query);
7111 }
7112
7113 cx.spawn(async move |this, cx| {
7114 let responses = futures::future::join_all(requests).await;
7115 let this = match this.upgrade() {
7116 Some(this) => this,
7117 None => return Ok(Vec::new()),
7118 };
7119
7120 let mut symbols = Vec::new();
7121 for result in responses {
7122 let core_symbols = this.update(cx, |this, cx| {
7123 result
7124 .lsp_symbols
7125 .into_iter()
7126 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
7127 let abs_path = symbol_location.uri.to_file_path().ok()?;
7128 let source_worktree = result.worktree.upgrade()?;
7129 let source_worktree_id = source_worktree.read(cx).id();
7130
7131 let path;
7132 let worktree;
7133 if let Some((tree, rel_path)) =
7134 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
7135 {
7136 worktree = tree;
7137 path = rel_path;
7138 } else {
7139 worktree = source_worktree.clone();
7140 path = relativize_path(&result.worktree_abs_path, &abs_path);
7141 }
7142
7143 let worktree_id = worktree.read(cx).id();
7144 let project_path = ProjectPath {
7145 worktree_id,
7146 path: path.into(),
7147 };
7148 let signature = this.symbol_signature(&project_path);
7149 Some(CoreSymbol {
7150 source_language_server_id: result.server_id,
7151 language_server_name: result.lsp_adapter.name.clone(),
7152 source_worktree_id,
7153 path: project_path,
7154 kind: symbol_kind,
7155 name: symbol_name,
7156 range: range_from_lsp(symbol_location.range),
7157 signature,
7158 })
7159 })
7160 .collect()
7161 })?;
7162
7163 populate_labels_for_symbols(
7164 core_symbols,
7165 &language_registry,
7166 Some(result.lsp_adapter),
7167 &mut symbols,
7168 )
7169 .await;
7170 }
7171
7172 Ok(symbols)
7173 })
7174 } else {
7175 Task::ready(Err(anyhow!("No upstream client or local language server")))
7176 }
7177 }
7178
7179 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
7180 let mut summary = DiagnosticSummary::default();
7181 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
7182 summary.error_count += path_summary.error_count;
7183 summary.warning_count += path_summary.warning_count;
7184 }
7185 summary
7186 }
7187
7188 pub fn diagnostic_summaries<'a>(
7189 &'a self,
7190 include_ignored: bool,
7191 cx: &'a App,
7192 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7193 self.worktree_store
7194 .read(cx)
7195 .visible_worktrees(cx)
7196 .filter_map(|worktree| {
7197 let worktree = worktree.read(cx);
7198 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
7199 })
7200 .flat_map(move |(worktree, summaries)| {
7201 let worktree_id = worktree.id();
7202 summaries
7203 .iter()
7204 .filter(move |(path, _)| {
7205 include_ignored
7206 || worktree
7207 .entry_for_path(path.as_ref())
7208 .map_or(false, |entry| !entry.is_ignored)
7209 })
7210 .flat_map(move |(path, summaries)| {
7211 summaries.iter().map(move |(server_id, summary)| {
7212 (
7213 ProjectPath {
7214 worktree_id,
7215 path: path.clone(),
7216 },
7217 *server_id,
7218 *summary,
7219 )
7220 })
7221 })
7222 })
7223 }
7224
7225 pub fn on_buffer_edited(
7226 &mut self,
7227 buffer: Entity<Buffer>,
7228 cx: &mut Context<Self>,
7229 ) -> Option<()> {
7230 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
7231 Some(
7232 self.as_local()?
7233 .language_servers_for_buffer(buffer, cx)
7234 .map(|i| i.1.clone())
7235 .collect(),
7236 )
7237 })?;
7238
7239 let buffer = buffer.read(cx);
7240 let file = File::from_dyn(buffer.file())?;
7241 let abs_path = file.as_local()?.abs_path(cx);
7242 let uri = lsp::Url::from_file_path(abs_path).unwrap();
7243 let next_snapshot = buffer.text_snapshot();
7244 for language_server in language_servers {
7245 let language_server = language_server.clone();
7246
7247 let buffer_snapshots = self
7248 .as_local_mut()
7249 .unwrap()
7250 .buffer_snapshots
7251 .get_mut(&buffer.remote_id())
7252 .and_then(|m| m.get_mut(&language_server.server_id()))?;
7253 let previous_snapshot = buffer_snapshots.last()?;
7254
7255 let build_incremental_change = || {
7256 buffer
7257 .edits_since::<Dimensions<PointUtf16, usize>>(
7258 previous_snapshot.snapshot.version(),
7259 )
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}