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