1pub mod clangd_ext;
2pub mod json_language_server_ext;
3pub mod lsp_ext_command;
4pub mod rust_analyzer_ext;
5
6use crate::{
7 CodeAction, ColorPresentation, Completion, CompletionResponse, CompletionSource,
8 CoreCompletion, DocumentColor, Hover, InlayHint, LocationLink, LspAction, LspPullDiagnostics,
9 ProjectItem, ProjectPath, ProjectTransaction, PulledDiagnostics, ResolveState, Symbol,
10 ToolchainStore,
11 buffer_store::{BufferStore, BufferStoreEvent},
12 environment::ProjectEnvironment,
13 lsp_command::{self, *},
14 lsp_store,
15 manifest_tree::{
16 AdapterQuery, LanguageServerTree, LanguageServerTreeNode, LaunchDisposition,
17 ManifestQueryDelegate, ManifestTree,
18 },
19 prettier_store::{self, PrettierStore, PrettierStoreEvent},
20 project_settings::{LspSettings, ProjectSettings},
21 relativize_path, resolve_path,
22 toolchain_store::{EmptyToolchainStore, ToolchainStoreEvent},
23 worktree_store::{WorktreeStore, WorktreeStoreEvent},
24 yarn::YarnPathStore,
25};
26use anyhow::{Context as _, Result, anyhow};
27use async_trait::async_trait;
28use client::{TypedEnvelope, proto};
29use clock::Global;
30use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
31use futures::{
32 AsyncWriteExt, Future, FutureExt, StreamExt,
33 future::{Either, Shared, join_all, pending, select},
34 select, select_biased,
35 stream::FuturesUnordered,
36};
37use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
38use gpui::{
39 App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString, Task,
40 WeakEntity,
41};
42use http_client::HttpClient;
43use itertools::Itertools as _;
44use language::{
45 Bias, BinaryStatus, Buffer, BufferSnapshot, CachedLspAdapter, CodeLabel, Diagnostic,
46 DiagnosticEntry, DiagnosticSet, DiagnosticSourceKind, Diff, File as _, Language, LanguageName,
47 LanguageRegistry, LanguageToolchainStore, LocalFile, LspAdapter, LspAdapterDelegate, Patch,
48 PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
49 language_settings::{
50 FormatOnSave, Formatter, LanguageSettings, SelectedFormatter, language_settings,
51 },
52 point_to_lsp,
53 proto::{
54 deserialize_anchor, deserialize_lsp_edit, deserialize_version, serialize_anchor,
55 serialize_lsp_edit, serialize_version,
56 },
57 range_from_lsp, range_to_lsp,
58};
59use lsp::{
60 CodeActionKind, CompletionContext, DiagnosticSeverity, DiagnosticTag,
61 DidChangeWatchedFilesRegistrationOptions, Edit, FileOperationFilter, FileOperationPatternKind,
62 FileOperationRegistrationOptions, FileRename, FileSystemWatcher, LanguageServer,
63 LanguageServerBinary, LanguageServerBinaryOptions, LanguageServerId, LanguageServerName,
64 LanguageServerSelector, LspRequestFuture, MessageActionItem, MessageType, OneOf,
65 RenameFilesParams, SymbolKind, TextEdit, WillRenameFiles, WorkDoneProgressCancelParams,
66 WorkspaceFolder, notification::DidRenameFiles,
67};
68use node_runtime::read_package_installed_version;
69use parking_lot::Mutex;
70use postage::{mpsc, sink::Sink, stream::Stream, watch};
71use rand::prelude::*;
72
73use rpc::{
74 AnyProtoClient,
75 proto::{FromProto, ToProto},
76};
77use serde::Serialize;
78use settings::{Settings, SettingsLocation, SettingsStore};
79use sha2::{Digest, Sha256};
80use smol::channel::Sender;
81use snippet::Snippet;
82use std::{
83 any::Any,
84 borrow::Cow,
85 cell::RefCell,
86 cmp::{Ordering, Reverse},
87 convert::TryInto,
88 ffi::OsStr,
89 future::ready,
90 iter, mem,
91 ops::{ControlFlow, Range},
92 path::{self, Path, PathBuf},
93 pin::pin,
94 rc::Rc,
95 sync::Arc,
96 time::{Duration, Instant},
97};
98use text::{Anchor, BufferId, LineEnding, OffsetRangeExt};
99use url::Url;
100use util::{
101 ConnectionResult, ResultExt as _, debug_panic, defer, maybe, merge_json_value_into,
102 paths::{PathExt, SanitizedPath},
103 post_inc,
104};
105
106pub use fs::*;
107pub use language::Location;
108#[cfg(any(test, feature = "test-support"))]
109pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
110pub use worktree::{
111 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
112 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
113};
114
115const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
116pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum FormatTrigger {
120 Save,
121 Manual,
122}
123
124pub enum LspFormatTarget {
125 Buffers,
126 Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
127}
128
129pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
130
131impl FormatTrigger {
132 fn from_proto(value: i32) -> FormatTrigger {
133 match value {
134 0 => FormatTrigger::Save,
135 1 => FormatTrigger::Manual,
136 _ => FormatTrigger::Save,
137 }
138 }
139}
140
141pub struct LocalLspStore {
142 weak: WeakEntity<LspStore>,
143 worktree_store: Entity<WorktreeStore>,
144 toolchain_store: Entity<ToolchainStore>,
145 http_client: Arc<dyn HttpClient>,
146 environment: Entity<ProjectEnvironment>,
147 fs: Arc<dyn Fs>,
148 languages: Arc<LanguageRegistry>,
149 language_server_ids: HashMap<(WorktreeId, LanguageServerName), BTreeSet<LanguageServerId>>,
150 yarn: Entity<YarnPathStore>,
151 pub language_servers: HashMap<LanguageServerId, LanguageServerState>,
152 buffers_being_formatted: HashSet<BufferId>,
153 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
154 language_server_watched_paths: HashMap<LanguageServerId, LanguageServerWatchedPaths>,
155 language_server_paths_watched_for_rename:
156 HashMap<LanguageServerId, RenamePathsWatchedForServer>,
157 language_server_watcher_registrations:
158 HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
159 supplementary_language_servers:
160 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
161 prettier_store: Entity<PrettierStore>,
162 next_diagnostic_group_id: usize,
163 diagnostics: HashMap<
164 WorktreeId,
165 HashMap<
166 Arc<Path>,
167 Vec<(
168 LanguageServerId,
169 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
170 )>,
171 >,
172 >,
173 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
174 _subscription: gpui::Subscription,
175 lsp_tree: Entity<LanguageServerTree>,
176 registered_buffers: HashMap<BufferId, usize>,
177 buffers_opened_in_servers: HashMap<BufferId, HashSet<LanguageServerId>>,
178 buffer_pull_diagnostics_result_ids: HashMap<LanguageServerId, HashMap<PathBuf, Option<String>>>,
179}
180
181impl LocalLspStore {
182 /// Returns the running language server for the given ID. Note if the language server is starting, it will not be returned.
183 pub fn running_language_server_for_id(
184 &self,
185 id: LanguageServerId,
186 ) -> Option<&Arc<LanguageServer>> {
187 let language_server_state = self.language_servers.get(&id)?;
188
189 match language_server_state {
190 LanguageServerState::Running { server, .. } => Some(server),
191 LanguageServerState::Starting { .. } => None,
192 }
193 }
194
195 fn start_language_server(
196 &mut self,
197 worktree_handle: &Entity<Worktree>,
198 delegate: Arc<LocalLspAdapterDelegate>,
199 adapter: Arc<CachedLspAdapter>,
200 settings: Arc<LspSettings>,
201 cx: &mut App,
202 ) -> LanguageServerId {
203 let worktree = worktree_handle.read(cx);
204 let worktree_id = worktree.id();
205 let root_path = worktree.abs_path();
206 let key = (worktree_id, adapter.name.clone());
207
208 let override_options = settings.initialization_options.clone();
209
210 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
211
212 let server_id = self.languages.next_language_server_id();
213 log::info!(
214 "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
215 adapter.name.0
216 );
217
218 let binary = self.get_language_server_binary(adapter.clone(), delegate.clone(), true, cx);
219 let pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
220 let pending_server = cx.spawn({
221 let adapter = adapter.clone();
222 let server_name = adapter.name.clone();
223 let stderr_capture = stderr_capture.clone();
224 #[cfg(any(test, feature = "test-support"))]
225 let lsp_store = self.weak.clone();
226 let pending_workspace_folders = pending_workspace_folders.clone();
227 async move |cx| {
228 let binary = binary.await?;
229 #[cfg(any(test, feature = "test-support"))]
230 if let Some(server) = lsp_store
231 .update(&mut cx.clone(), |this, cx| {
232 this.languages.create_fake_language_server(
233 server_id,
234 &server_name,
235 binary.clone(),
236 &mut cx.to_async(),
237 )
238 })
239 .ok()
240 .flatten()
241 {
242 return Ok(server);
243 }
244
245 lsp::LanguageServer::new(
246 stderr_capture,
247 server_id,
248 server_name,
249 binary,
250 &root_path,
251 adapter.code_action_kinds(),
252 pending_workspace_folders,
253 cx,
254 )
255 }
256 });
257
258 let startup = {
259 let server_name = adapter.name.0.clone();
260 let delegate = delegate as Arc<dyn LspAdapterDelegate>;
261 let key = key.clone();
262 let adapter = adapter.clone();
263 let lsp_store = self.weak.clone();
264 let pending_workspace_folders = pending_workspace_folders.clone();
265 let fs = self.fs.clone();
266 let pull_diagnostics = ProjectSettings::get_global(cx)
267 .diagnostics
268 .lsp_pull_diagnostics
269 .enabled;
270 cx.spawn(async move |cx| {
271 let result = async {
272 let toolchains =
273 lsp_store.update(cx, |lsp_store, cx| lsp_store.toolchain_store(cx))?;
274 let language_server = pending_server.await?;
275
276 let workspace_config = Self::workspace_configuration_for_adapter(
277 adapter.adapter.clone(),
278 fs.as_ref(),
279 &delegate,
280 toolchains.clone(),
281 cx,
282 )
283 .await?;
284
285 let mut initialization_options = Self::initialization_options_for_adapter(
286 adapter.adapter.clone(),
287 fs.as_ref(),
288 &delegate,
289 )
290 .await?;
291
292 match (&mut initialization_options, override_options) {
293 (Some(initialization_options), Some(override_options)) => {
294 merge_json_value_into(override_options, initialization_options);
295 }
296 (None, override_options) => initialization_options = override_options,
297 _ => {}
298 }
299
300 let initialization_params = cx.update(|cx| {
301 let mut params =
302 language_server.default_initialize_params(pull_diagnostics, cx);
303 params.initialization_options = initialization_options;
304 adapter.adapter.prepare_initialize_params(params, cx)
305 })??;
306
307 Self::setup_lsp_messages(
308 lsp_store.clone(),
309 fs,
310 &language_server,
311 delegate.clone(),
312 adapter.clone(),
313 );
314
315 let did_change_configuration_params =
316 Arc::new(lsp::DidChangeConfigurationParams {
317 settings: workspace_config,
318 });
319 let language_server = cx
320 .update(|cx| {
321 language_server.initialize(
322 initialization_params,
323 did_change_configuration_params.clone(),
324 cx,
325 )
326 })?
327 .await
328 .inspect_err(|_| {
329 if let Some(lsp_store) = lsp_store.upgrade() {
330 lsp_store
331 .update(cx, |lsp_store, cx| {
332 lsp_store.cleanup_lsp_data(server_id);
333 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id))
334 })
335 .ok();
336 }
337 })?;
338
339 language_server
340 .notify::<lsp::notification::DidChangeConfiguration>(
341 &did_change_configuration_params,
342 )
343 .ok();
344
345 anyhow::Ok(language_server)
346 }
347 .await;
348
349 match result {
350 Ok(server) => {
351 lsp_store
352 .update(cx, |lsp_store, mut cx| {
353 lsp_store.insert_newly_running_language_server(
354 adapter,
355 server.clone(),
356 server_id,
357 key,
358 pending_workspace_folders,
359 &mut cx,
360 );
361 })
362 .ok();
363 stderr_capture.lock().take();
364 Some(server)
365 }
366
367 Err(err) => {
368 let log = stderr_capture.lock().take().unwrap_or_default();
369 delegate.update_status(
370 adapter.name(),
371 BinaryStatus::Failed {
372 error: format!("{err}\n-- stderr--\n{log}"),
373 },
374 );
375 let message =
376 format!("Failed to start language server {server_name:?}: {err:#?}");
377 log::error!("{message}");
378 log::error!("server stderr: {log}");
379 None
380 }
381 }
382 })
383 };
384 let state = LanguageServerState::Starting {
385 startup,
386 pending_workspace_folders,
387 };
388
389 self.languages
390 .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
391
392 self.language_servers.insert(server_id, state);
393 self.language_server_ids
394 .entry(key)
395 .or_default()
396 .insert(server_id);
397 server_id
398 }
399
400 fn get_language_server_binary(
401 &self,
402 adapter: Arc<CachedLspAdapter>,
403 delegate: Arc<dyn LspAdapterDelegate>,
404 allow_binary_download: bool,
405 cx: &mut App,
406 ) -> Task<Result<LanguageServerBinary>> {
407 let settings = ProjectSettings::get(
408 Some(SettingsLocation {
409 worktree_id: delegate.worktree_id(),
410 path: Path::new(""),
411 }),
412 cx,
413 )
414 .lsp
415 .get(&adapter.name)
416 .and_then(|s| s.binary.clone());
417
418 if settings.as_ref().is_some_and(|b| b.path.is_some()) {
419 let settings = settings.unwrap();
420
421 return cx.spawn(async move |_| {
422 let mut env = delegate.shell_env().await;
423 env.extend(settings.env.unwrap_or_default());
424
425 Ok(LanguageServerBinary {
426 path: PathBuf::from(&settings.path.unwrap()),
427 env: Some(env),
428 arguments: settings
429 .arguments
430 .unwrap_or_default()
431 .iter()
432 .map(Into::into)
433 .collect(),
434 })
435 });
436 }
437 let lsp_binary_options = LanguageServerBinaryOptions {
438 allow_path_lookup: !settings
439 .as_ref()
440 .and_then(|b| b.ignore_system_version)
441 .unwrap_or_default(),
442 allow_binary_download,
443 };
444 let toolchains = self.toolchain_store.read(cx).as_language_toolchain_store();
445 cx.spawn(async move |cx| {
446 let binary_result = adapter
447 .clone()
448 .get_language_server_command(delegate.clone(), toolchains, lsp_binary_options, cx)
449 .await;
450
451 delegate.update_status(adapter.name.clone(), BinaryStatus::None);
452
453 let mut binary = binary_result?;
454 let mut shell_env = delegate.shell_env().await;
455
456 shell_env.extend(binary.env.unwrap_or_default());
457
458 if let Some(settings) = settings {
459 if let Some(arguments) = settings.arguments {
460 binary.arguments = arguments.into_iter().map(Into::into).collect();
461 }
462 if let Some(env) = settings.env {
463 shell_env.extend(env);
464 }
465 }
466
467 binary.env = Some(shell_env);
468 Ok(binary)
469 })
470 }
471
472 fn setup_lsp_messages(
473 this: WeakEntity<LspStore>,
474 fs: Arc<dyn Fs>,
475 language_server: &LanguageServer,
476 delegate: Arc<dyn LspAdapterDelegate>,
477 adapter: Arc<CachedLspAdapter>,
478 ) {
479 let name = language_server.name();
480 let server_id = language_server.server_id();
481 language_server
482 .on_notification::<lsp::notification::PublishDiagnostics, _>({
483 let adapter = adapter.clone();
484 let this = this.clone();
485 move |mut params, cx| {
486 let adapter = adapter.clone();
487 if let Some(this) = this.upgrade() {
488 this.update(cx, |this, cx| {
489 {
490 let buffer = params
491 .uri
492 .to_file_path()
493 .map(|file_path| this.get_buffer(&file_path, cx))
494 .ok()
495 .flatten();
496 adapter.process_diagnostics(&mut params, server_id, buffer);
497 }
498
499 this.merge_diagnostics(
500 server_id,
501 params,
502 None,
503 DiagnosticSourceKind::Pushed,
504 &adapter.disk_based_diagnostic_sources,
505 |_, diagnostic, cx| match diagnostic.source_kind {
506 DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => {
507 adapter.retain_old_diagnostic(diagnostic, cx)
508 }
509 DiagnosticSourceKind::Pulled => true,
510 },
511 cx,
512 )
513 .log_err();
514 })
515 .ok();
516 }
517 }
518 })
519 .detach();
520 language_server
521 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
522 let adapter = adapter.adapter.clone();
523 let delegate = delegate.clone();
524 let this = this.clone();
525 let fs = fs.clone();
526 move |params, cx| {
527 let adapter = adapter.clone();
528 let delegate = delegate.clone();
529 let this = this.clone();
530 let fs = fs.clone();
531 let mut cx = cx.clone();
532 async move {
533 let toolchains =
534 this.update(&mut cx, |this, cx| this.toolchain_store(cx))?;
535
536 let workspace_config = Self::workspace_configuration_for_adapter(
537 adapter.clone(),
538 fs.as_ref(),
539 &delegate,
540 toolchains.clone(),
541 &mut cx,
542 )
543 .await?;
544
545 Ok(params
546 .items
547 .into_iter()
548 .map(|item| {
549 if let Some(section) = &item.section {
550 workspace_config
551 .get(section)
552 .cloned()
553 .unwrap_or(serde_json::Value::Null)
554 } else {
555 workspace_config.clone()
556 }
557 })
558 .collect())
559 }
560 }
561 })
562 .detach();
563
564 language_server
565 .on_request::<lsp::request::WorkspaceFoldersRequest, _, _>({
566 let this = this.clone();
567 move |_, cx| {
568 let this = this.clone();
569 let mut cx = cx.clone();
570 async move {
571 let Some(server) = this
572 .read_with(&mut cx, |this, _| this.language_server_for_id(server_id))?
573 else {
574 return Ok(None);
575 };
576 let root = server.workspace_folders();
577 Ok(Some(
578 root.iter()
579 .cloned()
580 .map(|uri| WorkspaceFolder {
581 uri,
582 name: Default::default(),
583 })
584 .collect(),
585 ))
586 }
587 }
588 })
589 .detach();
590 // Even though we don't have handling for these requests, respond to them to
591 // avoid stalling any language server like `gopls` which waits for a response
592 // to these requests when initializing.
593 language_server
594 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
595 let this = this.clone();
596 move |params, cx| {
597 let this = this.clone();
598 let mut cx = cx.clone();
599 async move {
600 this.update(&mut cx, |this, _| {
601 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
602 {
603 if let lsp::NumberOrString::String(token) = params.token {
604 status.progress_tokens.insert(token);
605 }
606 }
607 })?;
608
609 Ok(())
610 }
611 }
612 })
613 .detach();
614
615 language_server
616 .on_request::<lsp::request::RegisterCapability, _, _>({
617 let this = this.clone();
618 move |params, cx| {
619 let this = this.clone();
620 let mut cx = cx.clone();
621 async move {
622 for reg in params.registrations {
623 match reg.method.as_str() {
624 "workspace/didChangeWatchedFiles" => {
625 if let Some(options) = reg.register_options {
626 let options = serde_json::from_value(options)?;
627 this.update(&mut cx, |this, cx| {
628 this.as_local_mut()?.on_lsp_did_change_watched_files(
629 server_id, ®.id, options, cx,
630 );
631 Some(())
632 })?;
633 }
634 }
635 "textDocument/rangeFormatting" => {
636 this.read_with(&mut cx, |this, _| {
637 if let Some(server) = this.language_server_for_id(server_id)
638 {
639 let options = reg
640 .register_options
641 .map(|options| {
642 serde_json::from_value::<
643 lsp::DocumentRangeFormattingOptions,
644 >(
645 options
646 )
647 })
648 .transpose()?;
649 let provider = match options {
650 None => OneOf::Left(true),
651 Some(options) => OneOf::Right(options),
652 };
653 server.update_capabilities(|capabilities| {
654 capabilities.document_range_formatting_provider =
655 Some(provider);
656 })
657 }
658 anyhow::Ok(())
659 })??;
660 }
661 "textDocument/onTypeFormatting" => {
662 this.read_with(&mut cx, |this, _| {
663 if let Some(server) = this.language_server_for_id(server_id)
664 {
665 let options = reg
666 .register_options
667 .map(|options| {
668 serde_json::from_value::<
669 lsp::DocumentOnTypeFormattingOptions,
670 >(
671 options
672 )
673 })
674 .transpose()?;
675 if let Some(options) = options {
676 server.update_capabilities(|capabilities| {
677 capabilities
678 .document_on_type_formatting_provider =
679 Some(options);
680 })
681 }
682 }
683 anyhow::Ok(())
684 })??;
685 }
686 "textDocument/formatting" => {
687 this.read_with(&mut cx, |this, _| {
688 if let Some(server) = this.language_server_for_id(server_id)
689 {
690 let options = reg
691 .register_options
692 .map(|options| {
693 serde_json::from_value::<
694 lsp::DocumentFormattingOptions,
695 >(
696 options
697 )
698 })
699 .transpose()?;
700 let provider = match options {
701 None => OneOf::Left(true),
702 Some(options) => OneOf::Right(options),
703 };
704 server.update_capabilities(|capabilities| {
705 capabilities.document_formatting_provider =
706 Some(provider);
707 })
708 }
709 anyhow::Ok(())
710 })??;
711 }
712 "workspace/didChangeConfiguration" => {
713 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
714 }
715 "textDocument/rename" => {
716 this.read_with(&mut cx, |this, _| {
717 if let Some(server) = this.language_server_for_id(server_id)
718 {
719 let options = reg
720 .register_options
721 .map(|options| {
722 serde_json::from_value::<lsp::RenameOptions>(
723 options,
724 )
725 })
726 .transpose()?;
727 let options = match options {
728 None => OneOf::Left(true),
729 Some(options) => OneOf::Right(options),
730 };
731
732 server.update_capabilities(|capabilities| {
733 capabilities.rename_provider = Some(options);
734 })
735 }
736 anyhow::Ok(())
737 })??;
738 }
739 _ => log::warn!("unhandled capability registration: {reg:?}"),
740 }
741 }
742 Ok(())
743 }
744 }
745 })
746 .detach();
747
748 language_server
749 .on_request::<lsp::request::UnregisterCapability, _, _>({
750 let this = this.clone();
751 move |params, cx| {
752 let this = this.clone();
753 let mut cx = cx.clone();
754 async move {
755 for unreg in params.unregisterations.iter() {
756 match unreg.method.as_str() {
757 "workspace/didChangeWatchedFiles" => {
758 this.update(&mut cx, |this, cx| {
759 this.as_local_mut()?
760 .on_lsp_unregister_did_change_watched_files(
761 server_id, &unreg.id, cx,
762 );
763 Some(())
764 })?;
765 }
766 "workspace/didChangeConfiguration" => {
767 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
768 }
769 "textDocument/rename" => {
770 this.read_with(&mut cx, |this, _| {
771 if let Some(server) = this.language_server_for_id(server_id)
772 {
773 server.update_capabilities(|capabilities| {
774 capabilities.rename_provider = None
775 })
776 }
777 })?;
778 }
779 "textDocument/rangeFormatting" => {
780 this.read_with(&mut cx, |this, _| {
781 if let Some(server) = this.language_server_for_id(server_id)
782 {
783 server.update_capabilities(|capabilities| {
784 capabilities.document_range_formatting_provider =
785 None
786 })
787 }
788 })?;
789 }
790 "textDocument/onTypeFormatting" => {
791 this.read_with(&mut cx, |this, _| {
792 if let Some(server) = this.language_server_for_id(server_id)
793 {
794 server.update_capabilities(|capabilities| {
795 capabilities.document_on_type_formatting_provider =
796 None;
797 })
798 }
799 })?;
800 }
801 "textDocument/formatting" => {
802 this.read_with(&mut cx, |this, _| {
803 if let Some(server) = this.language_server_for_id(server_id)
804 {
805 server.update_capabilities(|capabilities| {
806 capabilities.document_formatting_provider = None;
807 })
808 }
809 })?;
810 }
811 _ => log::warn!("unhandled capability unregistration: {unreg:?}"),
812 }
813 }
814 Ok(())
815 }
816 }
817 })
818 .detach();
819
820 language_server
821 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
822 let adapter = adapter.clone();
823 let this = this.clone();
824 move |params, cx| {
825 let mut cx = cx.clone();
826 let this = this.clone();
827 let adapter = adapter.clone();
828 async move {
829 LocalLspStore::on_lsp_workspace_edit(
830 this.clone(),
831 params,
832 server_id,
833 adapter.clone(),
834 &mut cx,
835 )
836 .await
837 }
838 }
839 })
840 .detach();
841
842 language_server
843 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
844 let this = this.clone();
845 move |(), cx| {
846 let this = this.clone();
847 let mut cx = cx.clone();
848 async move {
849 this.update(&mut cx, |this, cx| {
850 cx.emit(LspStoreEvent::RefreshInlayHints);
851 this.downstream_client.as_ref().map(|(client, project_id)| {
852 client.send(proto::RefreshInlayHints {
853 project_id: *project_id,
854 })
855 })
856 })?
857 .transpose()?;
858 Ok(())
859 }
860 }
861 })
862 .detach();
863
864 language_server
865 .on_request::<lsp::request::CodeLensRefresh, _, _>({
866 let this = this.clone();
867 move |(), cx| {
868 let this = this.clone();
869 let mut cx = cx.clone();
870 async move {
871 this.update(&mut cx, |this, cx| {
872 cx.emit(LspStoreEvent::RefreshCodeLens);
873 this.downstream_client.as_ref().map(|(client, project_id)| {
874 client.send(proto::RefreshCodeLens {
875 project_id: *project_id,
876 })
877 })
878 })?
879 .transpose()?;
880 Ok(())
881 }
882 }
883 })
884 .detach();
885
886 language_server
887 .on_request::<lsp::request::WorkspaceDiagnosticRefresh, _, _>({
888 let this = this.clone();
889 move |(), cx| {
890 let this = this.clone();
891 let mut cx = cx.clone();
892 async move {
893 this.update(&mut cx, |lsp_store, _| {
894 lsp_store.pull_workspace_diagnostics(server_id);
895 lsp_store
896 .downstream_client
897 .as_ref()
898 .map(|(client, project_id)| {
899 client.send(proto::PullWorkspaceDiagnostics {
900 project_id: *project_id,
901 server_id: server_id.to_proto(),
902 })
903 })
904 })?
905 .transpose()?;
906 Ok(())
907 }
908 }
909 })
910 .detach();
911
912 language_server
913 .on_request::<lsp::request::ShowMessageRequest, _, _>({
914 let this = this.clone();
915 let name = name.to_string();
916 move |params, cx| {
917 let this = this.clone();
918 let name = name.to_string();
919 let mut cx = cx.clone();
920 async move {
921 let actions = params.actions.unwrap_or_default();
922 let (tx, rx) = smol::channel::bounded(1);
923 let request = LanguageServerPromptRequest {
924 level: match params.typ {
925 lsp::MessageType::ERROR => PromptLevel::Critical,
926 lsp::MessageType::WARNING => PromptLevel::Warning,
927 _ => PromptLevel::Info,
928 },
929 message: params.message,
930 actions,
931 response_channel: tx,
932 lsp_name: name.clone(),
933 };
934
935 let did_update = this
936 .update(&mut cx, |_, cx| {
937 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
938 })
939 .is_ok();
940 if did_update {
941 let response = rx.recv().await.ok();
942 Ok(response)
943 } else {
944 Ok(None)
945 }
946 }
947 }
948 })
949 .detach();
950 language_server
951 .on_notification::<lsp::notification::ShowMessage, _>({
952 let this = this.clone();
953 let name = name.to_string();
954 move |params, cx| {
955 let this = this.clone();
956 let name = name.to_string();
957 let mut cx = cx.clone();
958
959 let (tx, _) = smol::channel::bounded(1);
960 let request = LanguageServerPromptRequest {
961 level: match params.typ {
962 lsp::MessageType::ERROR => PromptLevel::Critical,
963 lsp::MessageType::WARNING => PromptLevel::Warning,
964 _ => PromptLevel::Info,
965 },
966 message: params.message,
967 actions: vec![],
968 response_channel: tx,
969 lsp_name: name.clone(),
970 };
971
972 let _ = this.update(&mut cx, |_, cx| {
973 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
974 });
975 }
976 })
977 .detach();
978
979 let disk_based_diagnostics_progress_token =
980 adapter.disk_based_diagnostics_progress_token.clone();
981
982 language_server
983 .on_notification::<lsp::notification::Progress, _>({
984 let this = this.clone();
985 move |params, cx| {
986 if let Some(this) = this.upgrade() {
987 this.update(cx, |this, cx| {
988 this.on_lsp_progress(
989 params,
990 server_id,
991 disk_based_diagnostics_progress_token.clone(),
992 cx,
993 );
994 })
995 .ok();
996 }
997 }
998 })
999 .detach();
1000
1001 language_server
1002 .on_notification::<lsp::notification::LogMessage, _>({
1003 let this = this.clone();
1004 move |params, cx| {
1005 if let Some(this) = this.upgrade() {
1006 this.update(cx, |_, cx| {
1007 cx.emit(LspStoreEvent::LanguageServerLog(
1008 server_id,
1009 LanguageServerLogType::Log(params.typ),
1010 params.message,
1011 ));
1012 })
1013 .ok();
1014 }
1015 }
1016 })
1017 .detach();
1018
1019 language_server
1020 .on_notification::<lsp::notification::LogTrace, _>({
1021 let this = this.clone();
1022 move |params, cx| {
1023 let mut cx = cx.clone();
1024 if let Some(this) = this.upgrade() {
1025 this.update(&mut cx, |_, cx| {
1026 cx.emit(LspStoreEvent::LanguageServerLog(
1027 server_id,
1028 LanguageServerLogType::Trace(params.verbose),
1029 params.message,
1030 ));
1031 })
1032 .ok();
1033 }
1034 }
1035 })
1036 .detach();
1037
1038 json_language_server_ext::register_requests(this.clone(), language_server);
1039 rust_analyzer_ext::register_notifications(this.clone(), language_server);
1040 clangd_ext::register_notifications(this, language_server, adapter);
1041 }
1042
1043 fn shutdown_language_servers_on_quit(
1044 &mut self,
1045 _: &mut Context<LspStore>,
1046 ) -> impl Future<Output = ()> + use<> {
1047 let shutdown_futures = self
1048 .language_servers
1049 .drain()
1050 .map(|(_, server_state)| Self::shutdown_server(server_state))
1051 .collect::<Vec<_>>();
1052
1053 async move {
1054 join_all(shutdown_futures).await;
1055 }
1056 }
1057
1058 async fn shutdown_server(server_state: LanguageServerState) -> anyhow::Result<()> {
1059 match server_state {
1060 LanguageServerState::Running { server, .. } => {
1061 if let Some(shutdown) = server.shutdown() {
1062 shutdown.await;
1063 }
1064 }
1065 LanguageServerState::Starting { startup, .. } => {
1066 if let Some(server) = startup.await {
1067 if let Some(shutdown) = server.shutdown() {
1068 shutdown.await;
1069 }
1070 }
1071 }
1072 }
1073 Ok(())
1074 }
1075
1076 fn language_servers_for_worktree(
1077 &self,
1078 worktree_id: WorktreeId,
1079 ) -> impl Iterator<Item = &Arc<LanguageServer>> {
1080 self.language_server_ids
1081 .iter()
1082 .flat_map(move |((language_server_path, _), ids)| {
1083 ids.iter().filter_map(move |id| {
1084 if *language_server_path != worktree_id {
1085 return None;
1086 }
1087 if let Some(LanguageServerState::Running { server, .. }) =
1088 self.language_servers.get(id)
1089 {
1090 return Some(server);
1091 } else {
1092 None
1093 }
1094 })
1095 })
1096 }
1097
1098 fn language_server_ids_for_project_path(
1099 &self,
1100 project_path: ProjectPath,
1101 language: &Language,
1102 cx: &mut App,
1103 ) -> Vec<LanguageServerId> {
1104 let Some(worktree) = self
1105 .worktree_store
1106 .read(cx)
1107 .worktree_for_id(project_path.worktree_id, cx)
1108 else {
1109 return Vec::new();
1110 };
1111 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
1112 let root = self.lsp_tree.update(cx, |this, cx| {
1113 this.get(
1114 project_path,
1115 AdapterQuery::Language(&language.name()),
1116 delegate,
1117 cx,
1118 )
1119 .filter_map(|node| node.server_id())
1120 .collect::<Vec<_>>()
1121 });
1122
1123 root
1124 }
1125
1126 fn language_server_ids_for_buffer(
1127 &self,
1128 buffer: &Buffer,
1129 cx: &mut App,
1130 ) -> Vec<LanguageServerId> {
1131 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
1132 let worktree_id = file.worktree_id(cx);
1133
1134 let path: Arc<Path> = file
1135 .path()
1136 .parent()
1137 .map(Arc::from)
1138 .unwrap_or_else(|| file.path().clone());
1139 let worktree_path = ProjectPath { worktree_id, path };
1140 self.language_server_ids_for_project_path(worktree_path, language, cx)
1141 } else {
1142 Vec::new()
1143 }
1144 }
1145
1146 fn language_servers_for_buffer<'a>(
1147 &'a self,
1148 buffer: &'a Buffer,
1149 cx: &'a mut App,
1150 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1151 self.language_server_ids_for_buffer(buffer, cx)
1152 .into_iter()
1153 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
1154 LanguageServerState::Running {
1155 adapter, server, ..
1156 } => Some((adapter, server)),
1157 _ => None,
1158 })
1159 }
1160
1161 async fn execute_code_action_kind_locally(
1162 lsp_store: WeakEntity<LspStore>,
1163 mut buffers: Vec<Entity<Buffer>>,
1164 kind: CodeActionKind,
1165 push_to_history: bool,
1166 cx: &mut AsyncApp,
1167 ) -> anyhow::Result<ProjectTransaction> {
1168 // Do not allow multiple concurrent code actions requests for the
1169 // same buffer.
1170 lsp_store.update(cx, |this, cx| {
1171 let this = this.as_local_mut().unwrap();
1172 buffers.retain(|buffer| {
1173 this.buffers_being_formatted
1174 .insert(buffer.read(cx).remote_id())
1175 });
1176 })?;
1177 let _cleanup = defer({
1178 let this = lsp_store.clone();
1179 let mut cx = cx.clone();
1180 let buffers = &buffers;
1181 move || {
1182 this.update(&mut cx, |this, cx| {
1183 let this = this.as_local_mut().unwrap();
1184 for buffer in buffers {
1185 this.buffers_being_formatted
1186 .remove(&buffer.read(cx).remote_id());
1187 }
1188 })
1189 .ok();
1190 }
1191 });
1192 let mut project_transaction = ProjectTransaction::default();
1193
1194 for buffer in &buffers {
1195 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1196 buffer.update(cx, |buffer, cx| {
1197 lsp_store
1198 .as_local()
1199 .unwrap()
1200 .language_servers_for_buffer(buffer, cx)
1201 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1202 .collect::<Vec<_>>()
1203 })
1204 })?;
1205 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
1206 let actions = Self::get_server_code_actions_from_action_kinds(
1207 &lsp_store,
1208 language_server.server_id(),
1209 vec![kind.clone()],
1210 buffer,
1211 cx,
1212 )
1213 .await?;
1214 Self::execute_code_actions_on_server(
1215 &lsp_store,
1216 language_server,
1217 lsp_adapter,
1218 actions,
1219 push_to_history,
1220 &mut project_transaction,
1221 cx,
1222 )
1223 .await?;
1224 }
1225 }
1226 Ok(project_transaction)
1227 }
1228
1229 async fn format_locally(
1230 lsp_store: WeakEntity<LspStore>,
1231 mut buffers: Vec<FormattableBuffer>,
1232 push_to_history: bool,
1233 trigger: FormatTrigger,
1234 logger: zlog::Logger,
1235 cx: &mut AsyncApp,
1236 ) -> anyhow::Result<ProjectTransaction> {
1237 // Do not allow multiple concurrent formatting requests for the
1238 // same buffer.
1239 lsp_store.update(cx, |this, cx| {
1240 let this = this.as_local_mut().unwrap();
1241 buffers.retain(|buffer| {
1242 this.buffers_being_formatted
1243 .insert(buffer.handle.read(cx).remote_id())
1244 });
1245 })?;
1246
1247 let _cleanup = defer({
1248 let this = lsp_store.clone();
1249 let mut cx = cx.clone();
1250 let buffers = &buffers;
1251 move || {
1252 this.update(&mut cx, |this, cx| {
1253 let this = this.as_local_mut().unwrap();
1254 for buffer in buffers {
1255 this.buffers_being_formatted
1256 .remove(&buffer.handle.read(cx).remote_id());
1257 }
1258 })
1259 .ok();
1260 }
1261 });
1262
1263 let mut project_transaction = ProjectTransaction::default();
1264
1265 for buffer in &buffers {
1266 zlog::debug!(
1267 logger =>
1268 "formatting buffer '{:?}'",
1269 buffer.abs_path.as_ref().unwrap_or(&PathBuf::from("unknown")).display()
1270 );
1271 // Create an empty transaction to hold all of the formatting edits.
1272 let formatting_transaction_id = buffer.handle.update(cx, |buffer, cx| {
1273 // ensure no transactions created while formatting are
1274 // grouped with the previous transaction in the history
1275 // based on the transaction group interval
1276 buffer.finalize_last_transaction();
1277 buffer
1278 .start_transaction()
1279 .context("transaction already open")?;
1280 buffer.end_transaction(cx);
1281 let transaction_id = buffer.push_empty_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 { .. }
6047 | CompletionSource::Dap { .. }
6048 | CompletionSource::Custom => {
6049 return Ok(());
6050 }
6051 }
6052 };
6053 let resolved_completion = request
6054 .await
6055 .into_response()
6056 .context("resolve completion")?;
6057
6058 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
6059 // Technically we don't have to parse the whole `text_edit`, since the only
6060 // language server we currently use that does update `text_edit` in `completionItem/resolve`
6061 // is `typescript-language-server` and they only update `text_edit.new_text`.
6062 // But we should not rely on that.
6063 let edit = parse_completion_text_edit(text_edit, snapshot);
6064
6065 if let Some(mut parsed_edit) = edit {
6066 LineEnding::normalize(&mut parsed_edit.new_text);
6067
6068 let mut completions = completions.borrow_mut();
6069 let completion = &mut completions[completion_index];
6070
6071 completion.new_text = parsed_edit.new_text;
6072 completion.replace_range = parsed_edit.replace_range;
6073 if let CompletionSource::Lsp { insert_range, .. } = &mut completion.source {
6074 *insert_range = parsed_edit.insert_range;
6075 }
6076 }
6077 }
6078
6079 let mut completions = completions.borrow_mut();
6080 let completion = &mut completions[completion_index];
6081 if let CompletionSource::Lsp {
6082 lsp_completion,
6083 resolved,
6084 server_id: completion_server_id,
6085 ..
6086 } = &mut completion.source
6087 {
6088 if *resolved {
6089 return Ok(());
6090 }
6091 anyhow::ensure!(
6092 server_id == *completion_server_id,
6093 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
6094 );
6095 *lsp_completion = Box::new(resolved_completion);
6096 *resolved = true;
6097 }
6098 Ok(())
6099 }
6100
6101 async fn regenerate_completion_labels(
6102 adapter: Arc<CachedLspAdapter>,
6103 snapshot: &BufferSnapshot,
6104 completions: Rc<RefCell<Box<[Completion]>>>,
6105 completion_index: usize,
6106 ) -> Result<()> {
6107 let completion_item = completions.borrow()[completion_index]
6108 .source
6109 .lsp_completion(true)
6110 .map(Cow::into_owned);
6111 if let Some(lsp_documentation) = completion_item
6112 .as_ref()
6113 .and_then(|completion_item| completion_item.documentation.clone())
6114 {
6115 let mut completions = completions.borrow_mut();
6116 let completion = &mut completions[completion_index];
6117 completion.documentation = Some(lsp_documentation.into());
6118 } else {
6119 let mut completions = completions.borrow_mut();
6120 let completion = &mut completions[completion_index];
6121 completion.documentation = Some(CompletionDocumentation::Undocumented);
6122 }
6123
6124 let mut new_label = match completion_item {
6125 Some(completion_item) => {
6126 // 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
6127 // So we have to update the label here anyway...
6128 let language = snapshot.language();
6129 match language {
6130 Some(language) => {
6131 adapter
6132 .labels_for_completions(
6133 std::slice::from_ref(&completion_item),
6134 language,
6135 )
6136 .await?
6137 }
6138 None => Vec::new(),
6139 }
6140 .pop()
6141 .flatten()
6142 .unwrap_or_else(|| {
6143 CodeLabel::fallback_for_completion(
6144 &completion_item,
6145 language.map(|language| language.as_ref()),
6146 )
6147 })
6148 }
6149 None => CodeLabel::plain(
6150 completions.borrow()[completion_index].new_text.clone(),
6151 None,
6152 ),
6153 };
6154 ensure_uniform_list_compatible_label(&mut new_label);
6155
6156 let mut completions = completions.borrow_mut();
6157 let completion = &mut completions[completion_index];
6158 if completion.label.filter_text() == new_label.filter_text() {
6159 completion.label = new_label;
6160 } else {
6161 log::error!(
6162 "Resolved completion changed display label from {} to {}. \
6163 Refusing to apply this because it changes the fuzzy match text from {} to {}",
6164 completion.label.text(),
6165 new_label.text(),
6166 completion.label.filter_text(),
6167 new_label.filter_text()
6168 );
6169 }
6170
6171 Ok(())
6172 }
6173
6174 async fn resolve_completion_remote(
6175 project_id: u64,
6176 server_id: LanguageServerId,
6177 buffer_id: BufferId,
6178 completions: Rc<RefCell<Box<[Completion]>>>,
6179 completion_index: usize,
6180 client: AnyProtoClient,
6181 ) -> Result<()> {
6182 let lsp_completion = {
6183 let completion = &completions.borrow()[completion_index];
6184 match &completion.source {
6185 CompletionSource::Lsp {
6186 lsp_completion,
6187 resolved,
6188 server_id: completion_server_id,
6189 ..
6190 } => {
6191 anyhow::ensure!(
6192 server_id == *completion_server_id,
6193 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
6194 );
6195 if *resolved {
6196 return Ok(());
6197 }
6198 serde_json::to_string(lsp_completion).unwrap().into_bytes()
6199 }
6200 CompletionSource::Custom
6201 | CompletionSource::Dap { .. }
6202 | CompletionSource::BufferWord { .. } => {
6203 return Ok(());
6204 }
6205 }
6206 };
6207 let request = proto::ResolveCompletionDocumentation {
6208 project_id,
6209 language_server_id: server_id.0 as u64,
6210 lsp_completion,
6211 buffer_id: buffer_id.into(),
6212 };
6213
6214 let response = client
6215 .request(request)
6216 .await
6217 .context("completion documentation resolve proto request")?;
6218 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
6219
6220 let documentation = if response.documentation.is_empty() {
6221 CompletionDocumentation::Undocumented
6222 } else if response.documentation_is_markdown {
6223 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
6224 } else if response.documentation.lines().count() <= 1 {
6225 CompletionDocumentation::SingleLine(response.documentation.into())
6226 } else {
6227 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
6228 };
6229
6230 let mut completions = completions.borrow_mut();
6231 let completion = &mut completions[completion_index];
6232 completion.documentation = Some(documentation);
6233 if let CompletionSource::Lsp {
6234 insert_range,
6235 lsp_completion,
6236 resolved,
6237 server_id: completion_server_id,
6238 lsp_defaults: _,
6239 } = &mut completion.source
6240 {
6241 let completion_insert_range = response
6242 .old_insert_start
6243 .and_then(deserialize_anchor)
6244 .zip(response.old_insert_end.and_then(deserialize_anchor));
6245 *insert_range = completion_insert_range.map(|(start, end)| start..end);
6246
6247 if *resolved {
6248 return Ok(());
6249 }
6250 anyhow::ensure!(
6251 server_id == *completion_server_id,
6252 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
6253 );
6254 *lsp_completion = Box::new(resolved_lsp_completion);
6255 *resolved = true;
6256 }
6257
6258 let replace_range = response
6259 .old_replace_start
6260 .and_then(deserialize_anchor)
6261 .zip(response.old_replace_end.and_then(deserialize_anchor));
6262 if let Some((old_replace_start, old_replace_end)) = replace_range {
6263 if !response.new_text.is_empty() {
6264 completion.new_text = response.new_text;
6265 completion.replace_range = old_replace_start..old_replace_end;
6266 }
6267 }
6268
6269 Ok(())
6270 }
6271
6272 pub fn apply_additional_edits_for_completion(
6273 &self,
6274 buffer_handle: Entity<Buffer>,
6275 completions: Rc<RefCell<Box<[Completion]>>>,
6276 completion_index: usize,
6277 push_to_history: bool,
6278 cx: &mut Context<Self>,
6279 ) -> Task<Result<Option<Transaction>>> {
6280 if let Some((client, project_id)) = self.upstream_client() {
6281 let buffer = buffer_handle.read(cx);
6282 let buffer_id = buffer.remote_id();
6283 cx.spawn(async move |_, cx| {
6284 let request = {
6285 let completion = completions.borrow()[completion_index].clone();
6286 proto::ApplyCompletionAdditionalEdits {
6287 project_id,
6288 buffer_id: buffer_id.into(),
6289 completion: Some(Self::serialize_completion(&CoreCompletion {
6290 replace_range: completion.replace_range,
6291 new_text: completion.new_text,
6292 source: completion.source,
6293 })),
6294 }
6295 };
6296
6297 if let Some(transaction) = client.request(request).await?.transaction {
6298 let transaction = language::proto::deserialize_transaction(transaction)?;
6299 buffer_handle
6300 .update(cx, |buffer, _| {
6301 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6302 })?
6303 .await?;
6304 if push_to_history {
6305 buffer_handle.update(cx, |buffer, _| {
6306 buffer.push_transaction(transaction.clone(), Instant::now());
6307 buffer.finalize_last_transaction();
6308 })?;
6309 }
6310 Ok(Some(transaction))
6311 } else {
6312 Ok(None)
6313 }
6314 })
6315 } else {
6316 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
6317 let completion = &completions.borrow()[completion_index];
6318 let server_id = completion.source.server_id()?;
6319 Some(
6320 self.language_server_for_local_buffer(buffer, server_id, cx)?
6321 .1
6322 .clone(),
6323 )
6324 }) else {
6325 return Task::ready(Ok(None));
6326 };
6327 let snapshot = buffer_handle.read(&cx).snapshot();
6328
6329 cx.spawn(async move |this, cx| {
6330 Self::resolve_completion_local(
6331 server.clone(),
6332 &snapshot,
6333 completions.clone(),
6334 completion_index,
6335 )
6336 .await
6337 .context("resolving completion")?;
6338 let completion = completions.borrow()[completion_index].clone();
6339 let additional_text_edits = completion
6340 .source
6341 .lsp_completion(true)
6342 .as_ref()
6343 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
6344 if let Some(edits) = additional_text_edits {
6345 let edits = this
6346 .update(cx, |this, cx| {
6347 this.as_local_mut().unwrap().edits_from_lsp(
6348 &buffer_handle,
6349 edits,
6350 server.server_id(),
6351 None,
6352 cx,
6353 )
6354 })?
6355 .await?;
6356
6357 buffer_handle.update(cx, |buffer, cx| {
6358 buffer.finalize_last_transaction();
6359 buffer.start_transaction();
6360
6361 for (range, text) in edits {
6362 let primary = &completion.replace_range;
6363 let start_within = primary.start.cmp(&range.start, buffer).is_le()
6364 && primary.end.cmp(&range.start, buffer).is_ge();
6365 let end_within = range.start.cmp(&primary.end, buffer).is_le()
6366 && range.end.cmp(&primary.end, buffer).is_ge();
6367
6368 //Skip additional edits which overlap with the primary completion edit
6369 //https://github.com/zed-industries/zed/pull/1871
6370 if !start_within && !end_within {
6371 buffer.edit([(range, text)], None, cx);
6372 }
6373 }
6374
6375 let transaction = if buffer.end_transaction(cx).is_some() {
6376 let transaction = buffer.finalize_last_transaction().unwrap().clone();
6377 if !push_to_history {
6378 buffer.forget_transaction(transaction.id);
6379 }
6380 Some(transaction)
6381 } else {
6382 None
6383 };
6384 Ok(transaction)
6385 })?
6386 } else {
6387 Ok(None)
6388 }
6389 })
6390 }
6391 }
6392
6393 pub fn pull_diagnostics(
6394 &mut self,
6395 buffer_handle: Entity<Buffer>,
6396 cx: &mut Context<Self>,
6397 ) -> Task<Result<Vec<LspPullDiagnostics>>> {
6398 let buffer = buffer_handle.read(cx);
6399 let buffer_id = buffer.remote_id();
6400
6401 if let Some((client, upstream_project_id)) = self.upstream_client() {
6402 let request_task = client.request(proto::MultiLspQuery {
6403 buffer_id: buffer_id.to_proto(),
6404 version: serialize_version(&buffer_handle.read(cx).version()),
6405 project_id: upstream_project_id,
6406 strategy: Some(proto::multi_lsp_query::Strategy::All(
6407 proto::AllLanguageServers {},
6408 )),
6409 request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
6410 proto::GetDocumentDiagnostics {
6411 project_id: upstream_project_id,
6412 buffer_id: buffer_id.to_proto(),
6413 version: serialize_version(&buffer_handle.read(cx).version()),
6414 },
6415 )),
6416 });
6417 cx.background_spawn(async move {
6418 Ok(request_task
6419 .await?
6420 .responses
6421 .into_iter()
6422 .filter_map(|lsp_response| match lsp_response.response? {
6423 proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
6424 Some(response)
6425 }
6426 unexpected => {
6427 debug_panic!("Unexpected response: {unexpected:?}");
6428 None
6429 }
6430 })
6431 .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
6432 .collect())
6433 })
6434 } else {
6435 let server_ids = buffer_handle.update(cx, |buffer, cx| {
6436 self.language_servers_for_local_buffer(buffer, cx)
6437 .map(|(_, server)| server.server_id())
6438 .collect::<Vec<_>>()
6439 });
6440 let pull_diagnostics = server_ids
6441 .into_iter()
6442 .map(|server_id| {
6443 let result_id = self.result_id(server_id, buffer_id, cx);
6444 self.request_lsp(
6445 buffer_handle.clone(),
6446 LanguageServerToQuery::Other(server_id),
6447 GetDocumentDiagnostics {
6448 previous_result_id: result_id,
6449 },
6450 cx,
6451 )
6452 })
6453 .collect::<Vec<_>>();
6454
6455 cx.background_spawn(async move {
6456 let mut responses = Vec::new();
6457 for diagnostics in join_all(pull_diagnostics).await {
6458 responses.extend(diagnostics?);
6459 }
6460 Ok(responses)
6461 })
6462 }
6463 }
6464
6465 pub fn inlay_hints(
6466 &mut self,
6467 buffer_handle: Entity<Buffer>,
6468 range: Range<Anchor>,
6469 cx: &mut Context<Self>,
6470 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6471 let buffer = buffer_handle.read(cx);
6472 let range_start = range.start;
6473 let range_end = range.end;
6474 let buffer_id = buffer.remote_id().into();
6475 let lsp_request = InlayHints { range };
6476
6477 if let Some((client, project_id)) = self.upstream_client() {
6478 let request = proto::InlayHints {
6479 project_id,
6480 buffer_id,
6481 start: Some(serialize_anchor(&range_start)),
6482 end: Some(serialize_anchor(&range_end)),
6483 version: serialize_version(&buffer_handle.read(cx).version()),
6484 };
6485 cx.spawn(async move |project, cx| {
6486 let response = client
6487 .request(request)
6488 .await
6489 .context("inlay hints proto request")?;
6490 LspCommand::response_from_proto(
6491 lsp_request,
6492 response,
6493 project.upgrade().context("No project")?,
6494 buffer_handle.clone(),
6495 cx.clone(),
6496 )
6497 .await
6498 .context("inlay hints proto response conversion")
6499 })
6500 } else {
6501 let lsp_request_task = self.request_lsp(
6502 buffer_handle.clone(),
6503 LanguageServerToQuery::FirstCapable,
6504 lsp_request,
6505 cx,
6506 );
6507 cx.spawn(async move |_, cx| {
6508 buffer_handle
6509 .update(cx, |buffer, _| {
6510 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6511 })?
6512 .await
6513 .context("waiting for inlay hint request range edits")?;
6514 lsp_request_task.await.context("inlay hints LSP request")
6515 })
6516 }
6517 }
6518
6519 pub fn pull_diagnostics_for_buffer(
6520 &mut self,
6521 buffer: Entity<Buffer>,
6522 cx: &mut Context<Self>,
6523 ) -> Task<anyhow::Result<()>> {
6524 let buffer_id = buffer.read(cx).remote_id();
6525 let diagnostics = self.pull_diagnostics(buffer, cx);
6526 cx.spawn(async move |lsp_store, cx| {
6527 let diagnostics = diagnostics.await.context("pulling diagnostics")?;
6528 lsp_store.update(cx, |lsp_store, cx| {
6529 if lsp_store.as_local().is_none() {
6530 return;
6531 }
6532
6533 for diagnostics_set in diagnostics {
6534 let LspPullDiagnostics::Response {
6535 server_id,
6536 uri,
6537 diagnostics,
6538 } = diagnostics_set
6539 else {
6540 continue;
6541 };
6542
6543 let adapter = lsp_store.language_server_adapter_for_id(server_id);
6544 let disk_based_sources = adapter
6545 .as_ref()
6546 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
6547 .unwrap_or(&[]);
6548 match diagnostics {
6549 PulledDiagnostics::Unchanged { result_id } => {
6550 lsp_store
6551 .merge_diagnostics(
6552 server_id,
6553 lsp::PublishDiagnosticsParams {
6554 uri: uri.clone(),
6555 diagnostics: Vec::new(),
6556 version: None,
6557 },
6558 Some(result_id),
6559 DiagnosticSourceKind::Pulled,
6560 disk_based_sources,
6561 |_, _, _| true,
6562 cx,
6563 )
6564 .log_err();
6565 }
6566 PulledDiagnostics::Changed {
6567 diagnostics,
6568 result_id,
6569 } => {
6570 lsp_store
6571 .merge_diagnostics(
6572 server_id,
6573 lsp::PublishDiagnosticsParams {
6574 uri: uri.clone(),
6575 diagnostics,
6576 version: None,
6577 },
6578 result_id,
6579 DiagnosticSourceKind::Pulled,
6580 disk_based_sources,
6581 |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
6582 DiagnosticSourceKind::Pulled => {
6583 buffer.remote_id() != buffer_id
6584 }
6585 DiagnosticSourceKind::Other
6586 | DiagnosticSourceKind::Pushed => true,
6587 },
6588 cx,
6589 )
6590 .log_err();
6591 }
6592 }
6593 }
6594 })
6595 })
6596 }
6597
6598 pub fn document_colors(
6599 &mut self,
6600 fetch_strategy: ColorFetchStrategy,
6601 buffer: Entity<Buffer>,
6602 cx: &mut Context<Self>,
6603 ) -> Option<DocumentColorTask> {
6604 let version_queried_for = buffer.read(cx).version();
6605 let buffer_id = buffer.read(cx).remote_id();
6606
6607 match fetch_strategy {
6608 ColorFetchStrategy::IgnoreCache => {}
6609 ColorFetchStrategy::UseCache {
6610 known_cache_version,
6611 } => {
6612 if let Some(cached_data) = self.lsp_data.get(&buffer_id) {
6613 if !version_queried_for.changed_since(&cached_data.colors_for_version) {
6614 let has_different_servers = self.as_local().is_some_and(|local| {
6615 local
6616 .buffers_opened_in_servers
6617 .get(&buffer_id)
6618 .cloned()
6619 .unwrap_or_default()
6620 != cached_data.colors.keys().copied().collect()
6621 });
6622 if !has_different_servers {
6623 if Some(cached_data.cache_version) == known_cache_version {
6624 return None;
6625 } else {
6626 return Some(
6627 Task::ready(Ok(DocumentColors {
6628 colors: cached_data
6629 .colors
6630 .values()
6631 .flatten()
6632 .cloned()
6633 .collect(),
6634 cache_version: Some(cached_data.cache_version),
6635 }))
6636 .shared(),
6637 );
6638 }
6639 }
6640 }
6641 }
6642 }
6643 }
6644
6645 let lsp_data = self.lsp_data.entry(buffer_id).or_default();
6646 if let Some((updating_for, running_update)) = &lsp_data.colors_update {
6647 if !version_queried_for.changed_since(&updating_for) {
6648 return Some(running_update.clone());
6649 }
6650 }
6651 let query_version_queried_for = version_queried_for.clone();
6652 let new_task = cx
6653 .spawn(async move |lsp_store, cx| {
6654 cx.background_executor()
6655 .timer(Duration::from_millis(30))
6656 .await;
6657 let fetched_colors = lsp_store
6658 .update(cx, |lsp_store, cx| {
6659 lsp_store.fetch_document_colors_for_buffer(buffer.clone(), cx)
6660 })?
6661 .await
6662 .context("fetching document colors")
6663 .map_err(Arc::new);
6664 let fetched_colors = match fetched_colors {
6665 Ok(fetched_colors) => {
6666 if fetch_strategy != ColorFetchStrategy::IgnoreCache
6667 && Some(true)
6668 == buffer
6669 .update(cx, |buffer, _| {
6670 buffer.version() != query_version_queried_for
6671 })
6672 .ok()
6673 {
6674 return Ok(DocumentColors::default());
6675 }
6676 fetched_colors
6677 }
6678 Err(e) => {
6679 lsp_store
6680 .update(cx, |lsp_store, _| {
6681 lsp_store
6682 .lsp_data
6683 .entry(buffer_id)
6684 .or_default()
6685 .colors_update = None;
6686 })
6687 .ok();
6688 return Err(e);
6689 }
6690 };
6691
6692 lsp_store
6693 .update(cx, |lsp_store, _| {
6694 let lsp_data = lsp_store.lsp_data.entry(buffer_id).or_default();
6695
6696 if lsp_data.colors_for_version == query_version_queried_for {
6697 lsp_data.colors.extend(fetched_colors.clone());
6698 lsp_data.cache_version += 1;
6699 } else if !lsp_data
6700 .colors_for_version
6701 .changed_since(&query_version_queried_for)
6702 {
6703 lsp_data.colors_for_version = query_version_queried_for;
6704 lsp_data.colors = fetched_colors.clone();
6705 lsp_data.cache_version += 1;
6706 }
6707 lsp_data.colors_update = None;
6708 let colors = lsp_data
6709 .colors
6710 .values()
6711 .flatten()
6712 .cloned()
6713 .collect::<HashSet<_>>();
6714 DocumentColors {
6715 colors,
6716 cache_version: Some(lsp_data.cache_version),
6717 }
6718 })
6719 .map_err(Arc::new)
6720 })
6721 .shared();
6722 lsp_data.colors_update = Some((version_queried_for, new_task.clone()));
6723 Some(new_task)
6724 }
6725
6726 fn fetch_document_colors_for_buffer(
6727 &mut self,
6728 buffer: Entity<Buffer>,
6729 cx: &mut Context<Self>,
6730 ) -> Task<anyhow::Result<HashMap<LanguageServerId, HashSet<DocumentColor>>>> {
6731 if let Some((client, project_id)) = self.upstream_client() {
6732 let request_task = client.request(proto::MultiLspQuery {
6733 project_id,
6734 buffer_id: buffer.read(cx).remote_id().to_proto(),
6735 version: serialize_version(&buffer.read(cx).version()),
6736 strategy: Some(proto::multi_lsp_query::Strategy::All(
6737 proto::AllLanguageServers {},
6738 )),
6739 request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
6740 GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
6741 )),
6742 });
6743 cx.spawn(async move |project, cx| {
6744 let Some(project) = project.upgrade() else {
6745 return Ok(HashMap::default());
6746 };
6747 let colors = join_all(
6748 request_task
6749 .await
6750 .log_err()
6751 .map(|response| response.responses)
6752 .unwrap_or_default()
6753 .into_iter()
6754 .filter_map(|lsp_response| match lsp_response.response? {
6755 proto::lsp_response::Response::GetDocumentColorResponse(response) => {
6756 Some((
6757 LanguageServerId::from_proto(lsp_response.server_id),
6758 response,
6759 ))
6760 }
6761 unexpected => {
6762 debug_panic!("Unexpected response: {unexpected:?}");
6763 None
6764 }
6765 })
6766 .map(|(server_id, color_response)| {
6767 let response = GetDocumentColor {}.response_from_proto(
6768 color_response,
6769 project.clone(),
6770 buffer.clone(),
6771 cx.clone(),
6772 );
6773 async move { (server_id, response.await.log_err().unwrap_or_default()) }
6774 }),
6775 )
6776 .await
6777 .into_iter()
6778 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6779 acc.entry(server_id)
6780 .or_insert_with(HashSet::default)
6781 .extend(colors);
6782 acc
6783 });
6784 Ok(colors)
6785 })
6786 } else {
6787 let document_colors_task =
6788 self.request_multiple_lsp_locally(&buffer, None::<usize>, GetDocumentColor, cx);
6789 cx.spawn(async move |_, _| {
6790 Ok(document_colors_task
6791 .await
6792 .into_iter()
6793 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6794 acc.entry(server_id)
6795 .or_insert_with(HashSet::default)
6796 .extend(colors);
6797 acc
6798 })
6799 .into_iter()
6800 .collect())
6801 })
6802 }
6803 }
6804
6805 pub fn signature_help<T: ToPointUtf16>(
6806 &mut self,
6807 buffer: &Entity<Buffer>,
6808 position: T,
6809 cx: &mut Context<Self>,
6810 ) -> Task<Vec<SignatureHelp>> {
6811 let position = position.to_point_utf16(buffer.read(cx));
6812
6813 if let Some((client, upstream_project_id)) = self.upstream_client() {
6814 let request_task = client.request(proto::MultiLspQuery {
6815 buffer_id: buffer.read(cx).remote_id().into(),
6816 version: serialize_version(&buffer.read(cx).version()),
6817 project_id: upstream_project_id,
6818 strategy: Some(proto::multi_lsp_query::Strategy::All(
6819 proto::AllLanguageServers {},
6820 )),
6821 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
6822 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
6823 )),
6824 });
6825 let buffer = buffer.clone();
6826 cx.spawn(async move |weak_project, cx| {
6827 let Some(project) = weak_project.upgrade() else {
6828 return Vec::new();
6829 };
6830 join_all(
6831 request_task
6832 .await
6833 .log_err()
6834 .map(|response| response.responses)
6835 .unwrap_or_default()
6836 .into_iter()
6837 .filter_map(|lsp_response| match lsp_response.response? {
6838 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
6839 Some(response)
6840 }
6841 unexpected => {
6842 debug_panic!("Unexpected response: {unexpected:?}");
6843 None
6844 }
6845 })
6846 .map(|signature_response| {
6847 let response = GetSignatureHelp { position }.response_from_proto(
6848 signature_response,
6849 project.clone(),
6850 buffer.clone(),
6851 cx.clone(),
6852 );
6853 async move { response.await.log_err().flatten() }
6854 }),
6855 )
6856 .await
6857 .into_iter()
6858 .flatten()
6859 .collect()
6860 })
6861 } else {
6862 let all_actions_task = self.request_multiple_lsp_locally(
6863 buffer,
6864 Some(position),
6865 GetSignatureHelp { position },
6866 cx,
6867 );
6868 cx.spawn(async move |_, _| {
6869 all_actions_task
6870 .await
6871 .into_iter()
6872 .flat_map(|(_, actions)| actions)
6873 .collect::<Vec<_>>()
6874 })
6875 }
6876 }
6877
6878 pub fn hover(
6879 &mut self,
6880 buffer: &Entity<Buffer>,
6881 position: PointUtf16,
6882 cx: &mut Context<Self>,
6883 ) -> Task<Vec<Hover>> {
6884 if let Some((client, upstream_project_id)) = self.upstream_client() {
6885 let request_task = client.request(proto::MultiLspQuery {
6886 buffer_id: buffer.read(cx).remote_id().into(),
6887 version: serialize_version(&buffer.read(cx).version()),
6888 project_id: upstream_project_id,
6889 strategy: Some(proto::multi_lsp_query::Strategy::All(
6890 proto::AllLanguageServers {},
6891 )),
6892 request: Some(proto::multi_lsp_query::Request::GetHover(
6893 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
6894 )),
6895 });
6896 let buffer = buffer.clone();
6897 cx.spawn(async move |weak_project, cx| {
6898 let Some(project) = weak_project.upgrade() else {
6899 return Vec::new();
6900 };
6901 join_all(
6902 request_task
6903 .await
6904 .log_err()
6905 .map(|response| response.responses)
6906 .unwrap_or_default()
6907 .into_iter()
6908 .filter_map(|lsp_response| match lsp_response.response? {
6909 proto::lsp_response::Response::GetHoverResponse(response) => {
6910 Some(response)
6911 }
6912 unexpected => {
6913 debug_panic!("Unexpected response: {unexpected:?}");
6914 None
6915 }
6916 })
6917 .map(|hover_response| {
6918 let response = GetHover { position }.response_from_proto(
6919 hover_response,
6920 project.clone(),
6921 buffer.clone(),
6922 cx.clone(),
6923 );
6924 async move {
6925 response
6926 .await
6927 .log_err()
6928 .flatten()
6929 .and_then(remove_empty_hover_blocks)
6930 }
6931 }),
6932 )
6933 .await
6934 .into_iter()
6935 .flatten()
6936 .collect()
6937 })
6938 } else {
6939 let all_actions_task = self.request_multiple_lsp_locally(
6940 buffer,
6941 Some(position),
6942 GetHover { position },
6943 cx,
6944 );
6945 cx.spawn(async move |_, _| {
6946 all_actions_task
6947 .await
6948 .into_iter()
6949 .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
6950 .collect::<Vec<Hover>>()
6951 })
6952 }
6953 }
6954
6955 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
6956 let language_registry = self.languages.clone();
6957
6958 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
6959 let request = upstream_client.request(proto::GetProjectSymbols {
6960 project_id: *project_id,
6961 query: query.to_string(),
6962 });
6963 cx.foreground_executor().spawn(async move {
6964 let response = request.await?;
6965 let mut symbols = Vec::new();
6966 let core_symbols = response
6967 .symbols
6968 .into_iter()
6969 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
6970 .collect::<Vec<_>>();
6971 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
6972 .await;
6973 Ok(symbols)
6974 })
6975 } else if let Some(local) = self.as_local() {
6976 struct WorkspaceSymbolsResult {
6977 server_id: LanguageServerId,
6978 lsp_adapter: Arc<CachedLspAdapter>,
6979 worktree: WeakEntity<Worktree>,
6980 worktree_abs_path: Arc<Path>,
6981 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
6982 }
6983
6984 let mut requests = Vec::new();
6985 let mut requested_servers = BTreeSet::new();
6986 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
6987 let Some(worktree_handle) = self
6988 .worktree_store
6989 .read(cx)
6990 .worktree_for_id(*worktree_id, cx)
6991 else {
6992 continue;
6993 };
6994 let worktree = worktree_handle.read(cx);
6995 if !worktree.is_visible() {
6996 continue;
6997 }
6998
6999 let mut servers_to_query = server_ids
7000 .difference(&requested_servers)
7001 .cloned()
7002 .collect::<BTreeSet<_>>();
7003 for server_id in &servers_to_query {
7004 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
7005 Some(LanguageServerState::Running {
7006 adapter, server, ..
7007 }) => (adapter.clone(), server),
7008
7009 _ => continue 'next_server,
7010 };
7011 let supports_workspace_symbol_request =
7012 match server.capabilities().workspace_symbol_provider {
7013 Some(OneOf::Left(supported)) => supported,
7014 Some(OneOf::Right(_)) => true,
7015 None => false,
7016 };
7017 if !supports_workspace_symbol_request {
7018 continue 'next_server;
7019 }
7020 let worktree_abs_path = worktree.abs_path().clone();
7021 let worktree_handle = worktree_handle.clone();
7022 let server_id = server.server_id();
7023 requests.push(
7024 server
7025 .request::<lsp::request::WorkspaceSymbolRequest>(
7026 lsp::WorkspaceSymbolParams {
7027 query: query.to_string(),
7028 ..Default::default()
7029 },
7030 )
7031 .map(move |response| {
7032 let lsp_symbols = response.into_response()
7033 .context("workspace symbols request")
7034 .log_err()
7035 .flatten()
7036 .map(|symbol_response| match symbol_response {
7037 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
7038 flat_responses.into_iter().map(|lsp_symbol| {
7039 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
7040 }).collect::<Vec<_>>()
7041 }
7042 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
7043 nested_responses.into_iter().filter_map(|lsp_symbol| {
7044 let location = match lsp_symbol.location {
7045 OneOf::Left(location) => location,
7046 OneOf::Right(_) => {
7047 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
7048 return None
7049 }
7050 };
7051 Some((lsp_symbol.name, lsp_symbol.kind, location))
7052 }).collect::<Vec<_>>()
7053 }
7054 }).unwrap_or_default();
7055
7056 WorkspaceSymbolsResult {
7057 server_id,
7058 lsp_adapter,
7059 worktree: worktree_handle.downgrade(),
7060 worktree_abs_path,
7061 lsp_symbols,
7062 }
7063 }),
7064 );
7065 }
7066 requested_servers.append(&mut servers_to_query);
7067 }
7068
7069 cx.spawn(async move |this, cx| {
7070 let responses = futures::future::join_all(requests).await;
7071 let this = match this.upgrade() {
7072 Some(this) => this,
7073 None => return Ok(Vec::new()),
7074 };
7075
7076 let mut symbols = Vec::new();
7077 for result in responses {
7078 let core_symbols = this.update(cx, |this, cx| {
7079 result
7080 .lsp_symbols
7081 .into_iter()
7082 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
7083 let abs_path = symbol_location.uri.to_file_path().ok()?;
7084 let source_worktree = result.worktree.upgrade()?;
7085 let source_worktree_id = source_worktree.read(cx).id();
7086
7087 let path;
7088 let worktree;
7089 if let Some((tree, rel_path)) =
7090 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
7091 {
7092 worktree = tree;
7093 path = rel_path;
7094 } else {
7095 worktree = source_worktree.clone();
7096 path = relativize_path(&result.worktree_abs_path, &abs_path);
7097 }
7098
7099 let worktree_id = worktree.read(cx).id();
7100 let project_path = ProjectPath {
7101 worktree_id,
7102 path: path.into(),
7103 };
7104 let signature = this.symbol_signature(&project_path);
7105 Some(CoreSymbol {
7106 source_language_server_id: result.server_id,
7107 language_server_name: result.lsp_adapter.name.clone(),
7108 source_worktree_id,
7109 path: project_path,
7110 kind: symbol_kind,
7111 name: symbol_name,
7112 range: range_from_lsp(symbol_location.range),
7113 signature,
7114 })
7115 })
7116 .collect()
7117 })?;
7118
7119 populate_labels_for_symbols(
7120 core_symbols,
7121 &language_registry,
7122 Some(result.lsp_adapter),
7123 &mut symbols,
7124 )
7125 .await;
7126 }
7127
7128 Ok(symbols)
7129 })
7130 } else {
7131 Task::ready(Err(anyhow!("No upstream client or local language server")))
7132 }
7133 }
7134
7135 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
7136 let mut summary = DiagnosticSummary::default();
7137 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
7138 summary.error_count += path_summary.error_count;
7139 summary.warning_count += path_summary.warning_count;
7140 }
7141 summary
7142 }
7143
7144 pub fn diagnostic_summaries<'a>(
7145 &'a self,
7146 include_ignored: bool,
7147 cx: &'a App,
7148 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7149 self.worktree_store
7150 .read(cx)
7151 .visible_worktrees(cx)
7152 .filter_map(|worktree| {
7153 let worktree = worktree.read(cx);
7154 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
7155 })
7156 .flat_map(move |(worktree, summaries)| {
7157 let worktree_id = worktree.id();
7158 summaries
7159 .iter()
7160 .filter(move |(path, _)| {
7161 include_ignored
7162 || worktree
7163 .entry_for_path(path.as_ref())
7164 .map_or(false, |entry| !entry.is_ignored)
7165 })
7166 .flat_map(move |(path, summaries)| {
7167 summaries.iter().map(move |(server_id, summary)| {
7168 (
7169 ProjectPath {
7170 worktree_id,
7171 path: path.clone(),
7172 },
7173 *server_id,
7174 *summary,
7175 )
7176 })
7177 })
7178 })
7179 }
7180
7181 pub fn on_buffer_edited(
7182 &mut self,
7183 buffer: Entity<Buffer>,
7184 cx: &mut Context<Self>,
7185 ) -> Option<()> {
7186 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
7187 Some(
7188 self.as_local()?
7189 .language_servers_for_buffer(buffer, cx)
7190 .map(|i| i.1.clone())
7191 .collect(),
7192 )
7193 })?;
7194
7195 let buffer = buffer.read(cx);
7196 let file = File::from_dyn(buffer.file())?;
7197 let abs_path = file.as_local()?.abs_path(cx);
7198 let uri = lsp::Url::from_file_path(abs_path).unwrap();
7199 let next_snapshot = buffer.text_snapshot();
7200 for language_server in language_servers {
7201 let language_server = language_server.clone();
7202
7203 let buffer_snapshots = self
7204 .as_local_mut()
7205 .unwrap()
7206 .buffer_snapshots
7207 .get_mut(&buffer.remote_id())
7208 .and_then(|m| m.get_mut(&language_server.server_id()))?;
7209 let previous_snapshot = buffer_snapshots.last()?;
7210
7211 let build_incremental_change = || {
7212 buffer
7213 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
7214 .map(|edit| {
7215 let edit_start = edit.new.start.0;
7216 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
7217 let new_text = next_snapshot
7218 .text_for_range(edit.new.start.1..edit.new.end.1)
7219 .collect();
7220 lsp::TextDocumentContentChangeEvent {
7221 range: Some(lsp::Range::new(
7222 point_to_lsp(edit_start),
7223 point_to_lsp(edit_end),
7224 )),
7225 range_length: None,
7226 text: new_text,
7227 }
7228 })
7229 .collect()
7230 };
7231
7232 let document_sync_kind = language_server
7233 .capabilities()
7234 .text_document_sync
7235 .as_ref()
7236 .and_then(|sync| match sync {
7237 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
7238 lsp::TextDocumentSyncCapability::Options(options) => options.change,
7239 });
7240
7241 let content_changes: Vec<_> = match document_sync_kind {
7242 Some(lsp::TextDocumentSyncKind::FULL) => {
7243 vec![lsp::TextDocumentContentChangeEvent {
7244 range: None,
7245 range_length: None,
7246 text: next_snapshot.text(),
7247 }]
7248 }
7249 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
7250 _ => {
7251 #[cfg(any(test, feature = "test-support"))]
7252 {
7253 build_incremental_change()
7254 }
7255
7256 #[cfg(not(any(test, feature = "test-support")))]
7257 {
7258 continue;
7259 }
7260 }
7261 };
7262
7263 let next_version = previous_snapshot.version + 1;
7264 buffer_snapshots.push(LspBufferSnapshot {
7265 version: next_version,
7266 snapshot: next_snapshot.clone(),
7267 });
7268
7269 language_server
7270 .notify::<lsp::notification::DidChangeTextDocument>(
7271 &lsp::DidChangeTextDocumentParams {
7272 text_document: lsp::VersionedTextDocumentIdentifier::new(
7273 uri.clone(),
7274 next_version,
7275 ),
7276 content_changes,
7277 },
7278 )
7279 .ok();
7280 self.pull_workspace_diagnostics(language_server.server_id());
7281 }
7282
7283 None
7284 }
7285
7286 pub fn on_buffer_saved(
7287 &mut self,
7288 buffer: Entity<Buffer>,
7289 cx: &mut Context<Self>,
7290 ) -> Option<()> {
7291 let file = File::from_dyn(buffer.read(cx).file())?;
7292 let worktree_id = file.worktree_id(cx);
7293 let abs_path = file.as_local()?.abs_path(cx);
7294 let text_document = lsp::TextDocumentIdentifier {
7295 uri: file_path_to_lsp_url(&abs_path).log_err()?,
7296 };
7297 let local = self.as_local()?;
7298
7299 for server in local.language_servers_for_worktree(worktree_id) {
7300 if let Some(include_text) = include_text(server.as_ref()) {
7301 let text = if include_text {
7302 Some(buffer.read(cx).text())
7303 } else {
7304 None
7305 };
7306 server
7307 .notify::<lsp::notification::DidSaveTextDocument>(
7308 &lsp::DidSaveTextDocumentParams {
7309 text_document: text_document.clone(),
7310 text,
7311 },
7312 )
7313 .ok();
7314 }
7315 }
7316
7317 let language_servers = buffer.update(cx, |buffer, cx| {
7318 local.language_server_ids_for_buffer(buffer, cx)
7319 });
7320 for language_server_id in language_servers {
7321 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
7322 }
7323
7324 None
7325 }
7326
7327 pub(crate) async fn refresh_workspace_configurations(
7328 this: &WeakEntity<Self>,
7329 fs: Arc<dyn Fs>,
7330 cx: &mut AsyncApp,
7331 ) {
7332 maybe!(async move {
7333 let servers = this
7334 .update(cx, |this, cx| {
7335 let Some(local) = this.as_local() else {
7336 return Vec::default();
7337 };
7338 local
7339 .language_server_ids
7340 .iter()
7341 .flat_map(|((worktree_id, _), server_ids)| {
7342 let worktree = this
7343 .worktree_store
7344 .read(cx)
7345 .worktree_for_id(*worktree_id, cx);
7346 let delegate = worktree.map(|worktree| {
7347 LocalLspAdapterDelegate::new(
7348 local.languages.clone(),
7349 &local.environment,
7350 cx.weak_entity(),
7351 &worktree,
7352 local.http_client.clone(),
7353 local.fs.clone(),
7354 cx,
7355 )
7356 });
7357
7358 server_ids.iter().filter_map(move |server_id| {
7359 let states = local.language_servers.get(server_id)?;
7360
7361 match states {
7362 LanguageServerState::Starting { .. } => None,
7363 LanguageServerState::Running {
7364 adapter, server, ..
7365 } => Some((
7366 adapter.adapter.clone(),
7367 server.clone(),
7368 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
7369 )),
7370 }
7371 })
7372 })
7373 .collect::<Vec<_>>()
7374 })
7375 .ok()?;
7376
7377 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
7378 for (adapter, server, delegate) in servers {
7379 let settings = LocalLspStore::workspace_configuration_for_adapter(
7380 adapter,
7381 fs.as_ref(),
7382 &delegate,
7383 toolchain_store.clone(),
7384 cx,
7385 )
7386 .await
7387 .ok()?;
7388
7389 server
7390 .notify::<lsp::notification::DidChangeConfiguration>(
7391 &lsp::DidChangeConfigurationParams { settings },
7392 )
7393 .ok();
7394 }
7395 Some(())
7396 })
7397 .await;
7398 }
7399
7400 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
7401 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
7402 toolchain_store.read(cx).as_language_toolchain_store()
7403 } else {
7404 Arc::new(EmptyToolchainStore)
7405 }
7406 }
7407 fn maintain_workspace_config(
7408 fs: Arc<dyn Fs>,
7409 external_refresh_requests: watch::Receiver<()>,
7410 cx: &mut Context<Self>,
7411 ) -> Task<Result<()>> {
7412 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
7413 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
7414
7415 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
7416 *settings_changed_tx.borrow_mut() = ();
7417 });
7418
7419 let mut joint_future =
7420 futures::stream::select(settings_changed_rx, external_refresh_requests);
7421 cx.spawn(async move |this, cx| {
7422 while let Some(()) = joint_future.next().await {
7423 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
7424 }
7425
7426 drop(settings_observation);
7427 anyhow::Ok(())
7428 })
7429 }
7430
7431 pub fn language_servers_for_local_buffer<'a>(
7432 &'a self,
7433 buffer: &Buffer,
7434 cx: &mut App,
7435 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7436 let local = self.as_local();
7437 let language_server_ids = local
7438 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
7439 .unwrap_or_default();
7440
7441 language_server_ids
7442 .into_iter()
7443 .filter_map(
7444 move |server_id| match local?.language_servers.get(&server_id)? {
7445 LanguageServerState::Running {
7446 adapter, server, ..
7447 } => Some((adapter, server)),
7448 _ => None,
7449 },
7450 )
7451 }
7452
7453 pub fn language_server_for_local_buffer<'a>(
7454 &'a self,
7455 buffer: &'a Buffer,
7456 server_id: LanguageServerId,
7457 cx: &'a mut App,
7458 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7459 self.as_local()?
7460 .language_servers_for_buffer(buffer, cx)
7461 .find(|(_, s)| s.server_id() == server_id)
7462 }
7463
7464 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
7465 self.diagnostic_summaries.remove(&id_to_remove);
7466 if let Some(local) = self.as_local_mut() {
7467 let to_remove = local.remove_worktree(id_to_remove, cx);
7468 for server in to_remove {
7469 self.language_server_statuses.remove(&server);
7470 }
7471 }
7472 }
7473
7474 pub fn shared(
7475 &mut self,
7476 project_id: u64,
7477 downstream_client: AnyProtoClient,
7478 _: &mut Context<Self>,
7479 ) {
7480 self.downstream_client = Some((downstream_client.clone(), project_id));
7481
7482 for (server_id, status) in &self.language_server_statuses {
7483 downstream_client
7484 .send(proto::StartLanguageServer {
7485 project_id,
7486 server: Some(proto::LanguageServer {
7487 id: server_id.0 as u64,
7488 name: status.name.clone(),
7489 worktree_id: None,
7490 }),
7491 })
7492 .log_err();
7493 }
7494 }
7495
7496 pub fn disconnected_from_host(&mut self) {
7497 self.downstream_client.take();
7498 }
7499
7500 pub fn disconnected_from_ssh_remote(&mut self) {
7501 if let LspStoreMode::Remote(RemoteLspStore {
7502 upstream_client, ..
7503 }) = &mut self.mode
7504 {
7505 upstream_client.take();
7506 }
7507 }
7508
7509 pub(crate) fn set_language_server_statuses_from_proto(
7510 &mut self,
7511 language_servers: Vec<proto::LanguageServer>,
7512 ) {
7513 self.language_server_statuses = language_servers
7514 .into_iter()
7515 .map(|server| {
7516 (
7517 LanguageServerId(server.id as usize),
7518 LanguageServerStatus {
7519 name: server.name,
7520 pending_work: Default::default(),
7521 has_pending_diagnostic_updates: false,
7522 progress_tokens: Default::default(),
7523 },
7524 )
7525 })
7526 .collect();
7527 }
7528
7529 fn register_local_language_server(
7530 &mut self,
7531 worktree: Entity<Worktree>,
7532 language_server_name: LanguageServerName,
7533 language_server_id: LanguageServerId,
7534 cx: &mut App,
7535 ) {
7536 let Some(local) = self.as_local_mut() else {
7537 return;
7538 };
7539
7540 let worktree_id = worktree.read(cx).id();
7541 if worktree.read(cx).is_visible() {
7542 let path = ProjectPath {
7543 worktree_id,
7544 path: Arc::from("".as_ref()),
7545 };
7546 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
7547 local.lsp_tree.update(cx, |language_server_tree, cx| {
7548 for node in language_server_tree.get(
7549 path,
7550 AdapterQuery::Adapter(&language_server_name),
7551 delegate,
7552 cx,
7553 ) {
7554 node.server_id_or_init(|disposition| {
7555 assert_eq!(disposition.server_name, &language_server_name);
7556
7557 language_server_id
7558 });
7559 }
7560 });
7561 }
7562
7563 local
7564 .language_server_ids
7565 .entry((worktree_id, language_server_name))
7566 .or_default()
7567 .insert(language_server_id);
7568 }
7569
7570 #[cfg(test)]
7571 pub fn update_diagnostic_entries(
7572 &mut self,
7573 server_id: LanguageServerId,
7574 abs_path: PathBuf,
7575 result_id: Option<String>,
7576 version: Option<i32>,
7577 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7578 cx: &mut Context<Self>,
7579 ) -> anyhow::Result<()> {
7580 self.merge_diagnostic_entries(
7581 server_id,
7582 abs_path,
7583 result_id,
7584 version,
7585 diagnostics,
7586 |_, _, _| false,
7587 cx,
7588 )?;
7589 Ok(())
7590 }
7591
7592 pub fn merge_diagnostic_entries(
7593 &mut self,
7594 server_id: LanguageServerId,
7595 abs_path: PathBuf,
7596 result_id: Option<String>,
7597 version: Option<i32>,
7598 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7599 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
7600 cx: &mut Context<Self>,
7601 ) -> anyhow::Result<()> {
7602 let Some((worktree, relative_path)) =
7603 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
7604 else {
7605 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
7606 return Ok(());
7607 };
7608
7609 let project_path = ProjectPath {
7610 worktree_id: worktree.read(cx).id(),
7611 path: relative_path.into(),
7612 };
7613
7614 if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path) {
7615 let snapshot = buffer_handle.read(cx).snapshot();
7616 let buffer = buffer_handle.read(cx);
7617 let reused_diagnostics = buffer
7618 .get_diagnostics(server_id)
7619 .into_iter()
7620 .flat_map(|diag| {
7621 diag.iter()
7622 .filter(|v| filter(buffer, &v.diagnostic, cx))
7623 .map(|v| {
7624 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
7625 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
7626 DiagnosticEntry {
7627 range: start..end,
7628 diagnostic: v.diagnostic.clone(),
7629 }
7630 })
7631 })
7632 .collect::<Vec<_>>();
7633
7634 self.as_local_mut()
7635 .context("cannot merge diagnostics on a remote LspStore")?
7636 .update_buffer_diagnostics(
7637 &buffer_handle,
7638 server_id,
7639 result_id,
7640 version,
7641 diagnostics.clone(),
7642 reused_diagnostics.clone(),
7643 cx,
7644 )?;
7645
7646 diagnostics.extend(reused_diagnostics);
7647 }
7648
7649 let updated = worktree.update(cx, |worktree, cx| {
7650 self.update_worktree_diagnostics(
7651 worktree.id(),
7652 server_id,
7653 project_path.path.clone(),
7654 diagnostics,
7655 cx,
7656 )
7657 })?;
7658 if updated {
7659 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7660 language_server_id: server_id,
7661 path: project_path,
7662 })
7663 }
7664 Ok(())
7665 }
7666
7667 fn update_worktree_diagnostics(
7668 &mut self,
7669 worktree_id: WorktreeId,
7670 server_id: LanguageServerId,
7671 worktree_path: Arc<Path>,
7672 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7673 _: &mut Context<Worktree>,
7674 ) -> Result<bool> {
7675 let local = match &mut self.mode {
7676 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
7677 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
7678 };
7679
7680 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
7681 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
7682 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
7683
7684 let old_summary = summaries_by_server_id
7685 .remove(&server_id)
7686 .unwrap_or_default();
7687
7688 let new_summary = DiagnosticSummary::new(&diagnostics);
7689 if new_summary.is_empty() {
7690 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
7691 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7692 diagnostics_by_server_id.remove(ix);
7693 }
7694 if diagnostics_by_server_id.is_empty() {
7695 diagnostics_for_tree.remove(&worktree_path);
7696 }
7697 }
7698 } else {
7699 summaries_by_server_id.insert(server_id, new_summary);
7700 let diagnostics_by_server_id = diagnostics_for_tree
7701 .entry(worktree_path.clone())
7702 .or_default();
7703 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7704 Ok(ix) => {
7705 diagnostics_by_server_id[ix] = (server_id, diagnostics);
7706 }
7707 Err(ix) => {
7708 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
7709 }
7710 }
7711 }
7712
7713 if !old_summary.is_empty() || !new_summary.is_empty() {
7714 if let Some((downstream_client, project_id)) = &self.downstream_client {
7715 downstream_client
7716 .send(proto::UpdateDiagnosticSummary {
7717 project_id: *project_id,
7718 worktree_id: worktree_id.to_proto(),
7719 summary: Some(proto::DiagnosticSummary {
7720 path: worktree_path.to_proto(),
7721 language_server_id: server_id.0 as u64,
7722 error_count: new_summary.error_count as u32,
7723 warning_count: new_summary.warning_count as u32,
7724 }),
7725 })
7726 .log_err();
7727 }
7728 }
7729
7730 Ok(!old_summary.is_empty() || !new_summary.is_empty())
7731 }
7732
7733 pub fn open_buffer_for_symbol(
7734 &mut self,
7735 symbol: &Symbol,
7736 cx: &mut Context<Self>,
7737 ) -> Task<Result<Entity<Buffer>>> {
7738 if let Some((client, project_id)) = self.upstream_client() {
7739 let request = client.request(proto::OpenBufferForSymbol {
7740 project_id,
7741 symbol: Some(Self::serialize_symbol(symbol)),
7742 });
7743 cx.spawn(async move |this, cx| {
7744 let response = request.await?;
7745 let buffer_id = BufferId::new(response.buffer_id)?;
7746 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
7747 .await
7748 })
7749 } else if let Some(local) = self.as_local() {
7750 let Some(language_server_id) = local
7751 .language_server_ids
7752 .get(&(
7753 symbol.source_worktree_id,
7754 symbol.language_server_name.clone(),
7755 ))
7756 .and_then(|ids| {
7757 ids.contains(&symbol.source_language_server_id)
7758 .then_some(symbol.source_language_server_id)
7759 })
7760 else {
7761 return Task::ready(Err(anyhow!(
7762 "language server for worktree and language not found"
7763 )));
7764 };
7765
7766 let worktree_abs_path = if let Some(worktree_abs_path) = self
7767 .worktree_store
7768 .read(cx)
7769 .worktree_for_id(symbol.path.worktree_id, cx)
7770 .map(|worktree| worktree.read(cx).abs_path())
7771 {
7772 worktree_abs_path
7773 } else {
7774 return Task::ready(Err(anyhow!("worktree not found for symbol")));
7775 };
7776
7777 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
7778 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
7779 uri
7780 } else {
7781 return Task::ready(Err(anyhow!("invalid symbol path")));
7782 };
7783
7784 self.open_local_buffer_via_lsp(
7785 symbol_uri,
7786 language_server_id,
7787 symbol.language_server_name.clone(),
7788 cx,
7789 )
7790 } else {
7791 Task::ready(Err(anyhow!("no upstream client or local store")))
7792 }
7793 }
7794
7795 pub fn open_local_buffer_via_lsp(
7796 &mut self,
7797 mut abs_path: lsp::Url,
7798 language_server_id: LanguageServerId,
7799 language_server_name: LanguageServerName,
7800 cx: &mut Context<Self>,
7801 ) -> Task<Result<Entity<Buffer>>> {
7802 cx.spawn(async move |lsp_store, cx| {
7803 // Escape percent-encoded string.
7804 let current_scheme = abs_path.scheme().to_owned();
7805 let _ = abs_path.set_scheme("file");
7806
7807 let abs_path = abs_path
7808 .to_file_path()
7809 .map_err(|()| anyhow!("can't convert URI to path"))?;
7810 let p = abs_path.clone();
7811 let yarn_worktree = lsp_store
7812 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
7813 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
7814 cx.spawn(async move |this, cx| {
7815 let t = this
7816 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
7817 .ok()?;
7818 t.await
7819 })
7820 }),
7821 None => Task::ready(None),
7822 })?
7823 .await;
7824 let (worktree_root_target, known_relative_path) =
7825 if let Some((zip_root, relative_path)) = yarn_worktree {
7826 (zip_root, Some(relative_path))
7827 } else {
7828 (Arc::<Path>::from(abs_path.as_path()), None)
7829 };
7830 let (worktree, relative_path) = if let Some(result) =
7831 lsp_store.update(cx, |lsp_store, cx| {
7832 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7833 worktree_store.find_worktree(&worktree_root_target, cx)
7834 })
7835 })? {
7836 let relative_path =
7837 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
7838 (result.0, relative_path)
7839 } else {
7840 let worktree = lsp_store
7841 .update(cx, |lsp_store, cx| {
7842 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7843 worktree_store.create_worktree(&worktree_root_target, false, cx)
7844 })
7845 })?
7846 .await?;
7847 if worktree.read_with(cx, |worktree, _| worktree.is_local())? {
7848 lsp_store
7849 .update(cx, |lsp_store, cx| {
7850 lsp_store.register_local_language_server(
7851 worktree.clone(),
7852 language_server_name,
7853 language_server_id,
7854 cx,
7855 )
7856 })
7857 .ok();
7858 }
7859 let worktree_root = worktree.read_with(cx, |worktree, _| worktree.abs_path())?;
7860 let relative_path = if let Some(known_path) = known_relative_path {
7861 known_path
7862 } else {
7863 abs_path.strip_prefix(worktree_root)?.into()
7864 };
7865 (worktree, relative_path)
7866 };
7867 let project_path = ProjectPath {
7868 worktree_id: worktree.read_with(cx, |worktree, _| worktree.id())?,
7869 path: relative_path,
7870 };
7871 lsp_store
7872 .update(cx, |lsp_store, cx| {
7873 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
7874 buffer_store.open_buffer(project_path, cx)
7875 })
7876 })?
7877 .await
7878 })
7879 }
7880
7881 fn request_multiple_lsp_locally<P, R>(
7882 &mut self,
7883 buffer: &Entity<Buffer>,
7884 position: Option<P>,
7885 request: R,
7886 cx: &mut Context<Self>,
7887 ) -> Task<Vec<(LanguageServerId, R::Response)>>
7888 where
7889 P: ToOffset,
7890 R: LspCommand + Clone,
7891 <R::LspRequest as lsp::request::Request>::Result: Send,
7892 <R::LspRequest as lsp::request::Request>::Params: Send,
7893 {
7894 let Some(local) = self.as_local() else {
7895 return Task::ready(Vec::new());
7896 };
7897
7898 let snapshot = buffer.read(cx).snapshot();
7899 let scope = position.and_then(|position| snapshot.language_scope_at(position));
7900
7901 let server_ids = buffer.update(cx, |buffer, cx| {
7902 local
7903 .language_servers_for_buffer(buffer, cx)
7904 .filter(|(adapter, _)| {
7905 scope
7906 .as_ref()
7907 .map(|scope| scope.language_allowed(&adapter.name))
7908 .unwrap_or(true)
7909 })
7910 .map(|(_, server)| server.server_id())
7911 .filter(|server_id| {
7912 self.as_local().is_none_or(|local| {
7913 local
7914 .buffers_opened_in_servers
7915 .get(&snapshot.remote_id())
7916 .is_some_and(|servers| servers.contains(server_id))
7917 })
7918 })
7919 .collect::<Vec<_>>()
7920 });
7921
7922 let mut response_results = server_ids
7923 .into_iter()
7924 .map(|server_id| {
7925 let task = self.request_lsp(
7926 buffer.clone(),
7927 LanguageServerToQuery::Other(server_id),
7928 request.clone(),
7929 cx,
7930 );
7931 async move { (server_id, task.await) }
7932 })
7933 .collect::<FuturesUnordered<_>>();
7934
7935 cx.spawn(async move |_, _| {
7936 let mut responses = Vec::with_capacity(response_results.len());
7937 while let Some((server_id, response_result)) = response_results.next().await {
7938 if let Some(response) = response_result.log_err() {
7939 responses.push((server_id, response));
7940 }
7941 }
7942 responses
7943 })
7944 }
7945
7946 async fn handle_lsp_command<T: LspCommand>(
7947 this: Entity<Self>,
7948 envelope: TypedEnvelope<T::ProtoRequest>,
7949 mut cx: AsyncApp,
7950 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7951 where
7952 <T::LspRequest as lsp::request::Request>::Params: Send,
7953 <T::LspRequest as lsp::request::Request>::Result: Send,
7954 {
7955 let sender_id = envelope.original_sender_id().unwrap_or_default();
7956 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
7957 let buffer_handle = this.update(&mut cx, |this, cx| {
7958 this.buffer_store.read(cx).get_existing(buffer_id)
7959 })??;
7960 let request = T::from_proto(
7961 envelope.payload,
7962 this.clone(),
7963 buffer_handle.clone(),
7964 cx.clone(),
7965 )
7966 .await?;
7967 let response = this
7968 .update(&mut cx, |this, cx| {
7969 this.request_lsp(
7970 buffer_handle.clone(),
7971 LanguageServerToQuery::FirstCapable,
7972 request,
7973 cx,
7974 )
7975 })?
7976 .await?;
7977 this.update(&mut cx, |this, cx| {
7978 Ok(T::response_to_proto(
7979 response,
7980 this,
7981 sender_id,
7982 &buffer_handle.read(cx).version(),
7983 cx,
7984 ))
7985 })?
7986 }
7987
7988 async fn handle_multi_lsp_query(
7989 lsp_store: Entity<Self>,
7990 envelope: TypedEnvelope<proto::MultiLspQuery>,
7991 mut cx: AsyncApp,
7992 ) -> Result<proto::MultiLspQueryResponse> {
7993 let response_from_ssh = lsp_store.read_with(&mut cx, |this, _| {
7994 let (upstream_client, project_id) = this.upstream_client()?;
7995 let mut payload = envelope.payload.clone();
7996 payload.project_id = project_id;
7997
7998 Some(upstream_client.request(payload))
7999 })?;
8000 if let Some(response_from_ssh) = response_from_ssh {
8001 return response_from_ssh.await;
8002 }
8003
8004 let sender_id = envelope.original_sender_id().unwrap_or_default();
8005 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8006 let version = deserialize_version(&envelope.payload.version);
8007 let buffer = lsp_store.update(&mut cx, |this, cx| {
8008 this.buffer_store.read(cx).get_existing(buffer_id)
8009 })??;
8010 buffer
8011 .update(&mut cx, |buffer, _| {
8012 buffer.wait_for_version(version.clone())
8013 })?
8014 .await?;
8015 let buffer_version = buffer.read_with(&mut cx, |buffer, _| buffer.version())?;
8016 match envelope
8017 .payload
8018 .strategy
8019 .context("invalid request without the strategy")?
8020 {
8021 proto::multi_lsp_query::Strategy::All(_) => {
8022 // currently, there's only one multiple language servers query strategy,
8023 // so just ensure it's specified correctly
8024 }
8025 }
8026 match envelope.payload.request {
8027 Some(proto::multi_lsp_query::Request::GetHover(message)) => {
8028 buffer
8029 .update(&mut cx, |buffer, _| {
8030 buffer.wait_for_version(deserialize_version(&message.version))
8031 })?
8032 .await?;
8033 let get_hover =
8034 GetHover::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
8035 .await?;
8036 let all_hovers = lsp_store
8037 .update(&mut cx, |this, cx| {
8038 this.request_multiple_lsp_locally(
8039 &buffer,
8040 Some(get_hover.position),
8041 get_hover,
8042 cx,
8043 )
8044 })?
8045 .await
8046 .into_iter()
8047 .filter_map(|(server_id, hover)| {
8048 Some((server_id, remove_empty_hover_blocks(hover?)?))
8049 });
8050 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8051 responses: all_hovers
8052 .map(|(server_id, hover)| proto::LspResponse {
8053 server_id: server_id.to_proto(),
8054 response: Some(proto::lsp_response::Response::GetHoverResponse(
8055 GetHover::response_to_proto(
8056 Some(hover),
8057 project,
8058 sender_id,
8059 &buffer_version,
8060 cx,
8061 ),
8062 )),
8063 })
8064 .collect(),
8065 })
8066 }
8067 Some(proto::multi_lsp_query::Request::GetCodeActions(message)) => {
8068 buffer
8069 .update(&mut cx, |buffer, _| {
8070 buffer.wait_for_version(deserialize_version(&message.version))
8071 })?
8072 .await?;
8073 let get_code_actions = GetCodeActions::from_proto(
8074 message,
8075 lsp_store.clone(),
8076 buffer.clone(),
8077 cx.clone(),
8078 )
8079 .await?;
8080
8081 let all_actions = lsp_store
8082 .update(&mut cx, |project, cx| {
8083 project.request_multiple_lsp_locally(
8084 &buffer,
8085 Some(get_code_actions.range.start),
8086 get_code_actions,
8087 cx,
8088 )
8089 })?
8090 .await
8091 .into_iter();
8092
8093 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8094 responses: all_actions
8095 .map(|(server_id, code_actions)| proto::LspResponse {
8096 server_id: server_id.to_proto(),
8097 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
8098 GetCodeActions::response_to_proto(
8099 code_actions,
8100 project,
8101 sender_id,
8102 &buffer_version,
8103 cx,
8104 ),
8105 )),
8106 })
8107 .collect(),
8108 })
8109 }
8110 Some(proto::multi_lsp_query::Request::GetSignatureHelp(message)) => {
8111 buffer
8112 .update(&mut cx, |buffer, _| {
8113 buffer.wait_for_version(deserialize_version(&message.version))
8114 })?
8115 .await?;
8116 let get_signature_help = GetSignatureHelp::from_proto(
8117 message,
8118 lsp_store.clone(),
8119 buffer.clone(),
8120 cx.clone(),
8121 )
8122 .await?;
8123
8124 let all_signatures = lsp_store
8125 .update(&mut cx, |project, cx| {
8126 project.request_multiple_lsp_locally(
8127 &buffer,
8128 Some(get_signature_help.position),
8129 get_signature_help,
8130 cx,
8131 )
8132 })?
8133 .await
8134 .into_iter();
8135
8136 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8137 responses: all_signatures
8138 .map(|(server_id, signature_help)| proto::LspResponse {
8139 server_id: server_id.to_proto(),
8140 response: Some(
8141 proto::lsp_response::Response::GetSignatureHelpResponse(
8142 GetSignatureHelp::response_to_proto(
8143 signature_help,
8144 project,
8145 sender_id,
8146 &buffer_version,
8147 cx,
8148 ),
8149 ),
8150 ),
8151 })
8152 .collect(),
8153 })
8154 }
8155 Some(proto::multi_lsp_query::Request::GetCodeLens(message)) => {
8156 buffer
8157 .update(&mut cx, |buffer, _| {
8158 buffer.wait_for_version(deserialize_version(&message.version))
8159 })?
8160 .await?;
8161 let get_code_lens =
8162 GetCodeLens::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
8163 .await?;
8164
8165 let code_lens_actions = lsp_store
8166 .update(&mut cx, |project, cx| {
8167 project.request_multiple_lsp_locally(
8168 &buffer,
8169 None::<usize>,
8170 get_code_lens,
8171 cx,
8172 )
8173 })?
8174 .await
8175 .into_iter();
8176
8177 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8178 responses: code_lens_actions
8179 .map(|(server_id, actions)| proto::LspResponse {
8180 server_id: server_id.to_proto(),
8181 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
8182 GetCodeLens::response_to_proto(
8183 actions,
8184 project,
8185 sender_id,
8186 &buffer_version,
8187 cx,
8188 ),
8189 )),
8190 })
8191 .collect(),
8192 })
8193 }
8194 Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(message)) => {
8195 buffer
8196 .update(&mut cx, |buffer, _| {
8197 buffer.wait_for_version(deserialize_version(&message.version))
8198 })?
8199 .await?;
8200 lsp_store
8201 .update(&mut cx, |lsp_store, cx| {
8202 lsp_store.pull_diagnostics_for_buffer(buffer, cx)
8203 })?
8204 .await?;
8205 // `pull_diagnostics_for_buffer` will merge in the new diagnostics and send them to the client.
8206 // The client cannot merge anything into its non-local LspStore, so we do not need to return anything.
8207 Ok(proto::MultiLspQueryResponse {
8208 responses: Vec::new(),
8209 })
8210 }
8211 Some(proto::multi_lsp_query::Request::GetDocumentColor(message)) => {
8212 buffer
8213 .update(&mut cx, |buffer, _| {
8214 buffer.wait_for_version(deserialize_version(&message.version))
8215 })?
8216 .await?;
8217 let get_document_color = GetDocumentColor::from_proto(
8218 message,
8219 lsp_store.clone(),
8220 buffer.clone(),
8221 cx.clone(),
8222 )
8223 .await?;
8224
8225 let all_colors = lsp_store
8226 .update(&mut cx, |project, cx| {
8227 project.request_multiple_lsp_locally(
8228 &buffer,
8229 None::<usize>,
8230 get_document_color,
8231 cx,
8232 )
8233 })?
8234 .await
8235 .into_iter();
8236
8237 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8238 responses: all_colors
8239 .map(|(server_id, colors)| proto::LspResponse {
8240 server_id: server_id.to_proto(),
8241 response: Some(
8242 proto::lsp_response::Response::GetDocumentColorResponse(
8243 GetDocumentColor::response_to_proto(
8244 colors,
8245 project,
8246 sender_id,
8247 &buffer_version,
8248 cx,
8249 ),
8250 ),
8251 ),
8252 })
8253 .collect(),
8254 })
8255 }
8256 Some(proto::multi_lsp_query::Request::GetDefinition(message)) => {
8257 let get_definitions = GetDefinitions::from_proto(
8258 message,
8259 lsp_store.clone(),
8260 buffer.clone(),
8261 cx.clone(),
8262 )
8263 .await?;
8264
8265 let definitions = lsp_store
8266 .update(&mut cx, |project, cx| {
8267 project.request_multiple_lsp_locally(
8268 &buffer,
8269 Some(get_definitions.position),
8270 get_definitions,
8271 cx,
8272 )
8273 })?
8274 .await
8275 .into_iter();
8276
8277 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8278 responses: definitions
8279 .map(|(server_id, definitions)| proto::LspResponse {
8280 server_id: server_id.to_proto(),
8281 response: Some(proto::lsp_response::Response::GetDefinitionResponse(
8282 GetDefinitions::response_to_proto(
8283 definitions,
8284 project,
8285 sender_id,
8286 &buffer_version,
8287 cx,
8288 ),
8289 )),
8290 })
8291 .collect(),
8292 })
8293 }
8294 Some(proto::multi_lsp_query::Request::GetDeclaration(message)) => {
8295 let get_declarations = GetDeclarations::from_proto(
8296 message,
8297 lsp_store.clone(),
8298 buffer.clone(),
8299 cx.clone(),
8300 )
8301 .await?;
8302
8303 let declarations = lsp_store
8304 .update(&mut cx, |project, cx| {
8305 project.request_multiple_lsp_locally(
8306 &buffer,
8307 Some(get_declarations.position),
8308 get_declarations,
8309 cx,
8310 )
8311 })?
8312 .await
8313 .into_iter();
8314
8315 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8316 responses: declarations
8317 .map(|(server_id, declarations)| proto::LspResponse {
8318 server_id: server_id.to_proto(),
8319 response: Some(proto::lsp_response::Response::GetDeclarationResponse(
8320 GetDeclarations::response_to_proto(
8321 declarations,
8322 project,
8323 sender_id,
8324 &buffer_version,
8325 cx,
8326 ),
8327 )),
8328 })
8329 .collect(),
8330 })
8331 }
8332 Some(proto::multi_lsp_query::Request::GetTypeDefinition(message)) => {
8333 let get_type_definitions = GetTypeDefinitions::from_proto(
8334 message,
8335 lsp_store.clone(),
8336 buffer.clone(),
8337 cx.clone(),
8338 )
8339 .await?;
8340
8341 let type_definitions = lsp_store
8342 .update(&mut cx, |project, cx| {
8343 project.request_multiple_lsp_locally(
8344 &buffer,
8345 Some(get_type_definitions.position),
8346 get_type_definitions,
8347 cx,
8348 )
8349 })?
8350 .await
8351 .into_iter();
8352
8353 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8354 responses: type_definitions
8355 .map(|(server_id, type_definitions)| proto::LspResponse {
8356 server_id: server_id.to_proto(),
8357 response: Some(
8358 proto::lsp_response::Response::GetTypeDefinitionResponse(
8359 GetTypeDefinitions::response_to_proto(
8360 type_definitions,
8361 project,
8362 sender_id,
8363 &buffer_version,
8364 cx,
8365 ),
8366 ),
8367 ),
8368 })
8369 .collect(),
8370 })
8371 }
8372 Some(proto::multi_lsp_query::Request::GetImplementation(message)) => {
8373 let get_implementations = GetImplementations::from_proto(
8374 message,
8375 lsp_store.clone(),
8376 buffer.clone(),
8377 cx.clone(),
8378 )
8379 .await?;
8380
8381 let implementations = lsp_store
8382 .update(&mut cx, |project, cx| {
8383 project.request_multiple_lsp_locally(
8384 &buffer,
8385 Some(get_implementations.position),
8386 get_implementations,
8387 cx,
8388 )
8389 })?
8390 .await
8391 .into_iter();
8392
8393 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8394 responses: implementations
8395 .map(|(server_id, implementations)| proto::LspResponse {
8396 server_id: server_id.to_proto(),
8397 response: Some(
8398 proto::lsp_response::Response::GetImplementationResponse(
8399 GetImplementations::response_to_proto(
8400 implementations,
8401 project,
8402 sender_id,
8403 &buffer_version,
8404 cx,
8405 ),
8406 ),
8407 ),
8408 })
8409 .collect(),
8410 })
8411 }
8412 Some(proto::multi_lsp_query::Request::GetReferences(message)) => {
8413 let get_references = GetReferences::from_proto(
8414 message,
8415 lsp_store.clone(),
8416 buffer.clone(),
8417 cx.clone(),
8418 )
8419 .await?;
8420
8421 let references = lsp_store
8422 .update(&mut cx, |project, cx| {
8423 project.request_multiple_lsp_locally(
8424 &buffer,
8425 Some(get_references.position),
8426 get_references,
8427 cx,
8428 )
8429 })?
8430 .await
8431 .into_iter();
8432
8433 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8434 responses: references
8435 .map(|(server_id, references)| proto::LspResponse {
8436 server_id: server_id.to_proto(),
8437 response: Some(proto::lsp_response::Response::GetReferencesResponse(
8438 GetReferences::response_to_proto(
8439 references,
8440 project,
8441 sender_id,
8442 &buffer_version,
8443 cx,
8444 ),
8445 )),
8446 })
8447 .collect(),
8448 })
8449 }
8450 None => anyhow::bail!("empty multi lsp query request"),
8451 }
8452 }
8453
8454 async fn handle_apply_code_action(
8455 this: Entity<Self>,
8456 envelope: TypedEnvelope<proto::ApplyCodeAction>,
8457 mut cx: AsyncApp,
8458 ) -> Result<proto::ApplyCodeActionResponse> {
8459 let sender_id = envelope.original_sender_id().unwrap_or_default();
8460 let action =
8461 Self::deserialize_code_action(envelope.payload.action.context("invalid action")?)?;
8462 let apply_code_action = this.update(&mut cx, |this, cx| {
8463 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8464 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8465 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
8466 })??;
8467
8468 let project_transaction = apply_code_action.await?;
8469 let project_transaction = this.update(&mut cx, |this, cx| {
8470 this.buffer_store.update(cx, |buffer_store, cx| {
8471 buffer_store.serialize_project_transaction_for_peer(
8472 project_transaction,
8473 sender_id,
8474 cx,
8475 )
8476 })
8477 })?;
8478 Ok(proto::ApplyCodeActionResponse {
8479 transaction: Some(project_transaction),
8480 })
8481 }
8482
8483 async fn handle_register_buffer_with_language_servers(
8484 this: Entity<Self>,
8485 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
8486 mut cx: AsyncApp,
8487 ) -> Result<proto::Ack> {
8488 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8489 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
8490 this.update(&mut cx, |this, cx| {
8491 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
8492 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
8493 project_id: upstream_project_id,
8494 buffer_id: buffer_id.to_proto(),
8495 only_servers: envelope.payload.only_servers,
8496 });
8497 }
8498
8499 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
8500 anyhow::bail!("buffer is not open");
8501 };
8502
8503 let handle = this.register_buffer_with_language_servers(
8504 &buffer,
8505 envelope
8506 .payload
8507 .only_servers
8508 .into_iter()
8509 .filter_map(|selector| {
8510 Some(match selector.selector? {
8511 proto::language_server_selector::Selector::ServerId(server_id) => {
8512 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
8513 }
8514 proto::language_server_selector::Selector::Name(name) => {
8515 LanguageServerSelector::Name(LanguageServerName(
8516 SharedString::from(name),
8517 ))
8518 }
8519 })
8520 })
8521 .collect(),
8522 false,
8523 cx,
8524 );
8525 this.buffer_store().update(cx, |buffer_store, _| {
8526 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
8527 });
8528
8529 Ok(())
8530 })??;
8531 Ok(proto::Ack {})
8532 }
8533
8534 async fn handle_language_server_id_for_name(
8535 lsp_store: Entity<Self>,
8536 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
8537 mut cx: AsyncApp,
8538 ) -> Result<proto::LanguageServerIdForNameResponse> {
8539 let name = &envelope.payload.name;
8540 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8541 lsp_store
8542 .update(&mut cx, |lsp_store, cx| {
8543 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
8544 let server_id = buffer.update(cx, |buffer, cx| {
8545 lsp_store
8546 .language_servers_for_local_buffer(buffer, cx)
8547 .find_map(|(adapter, server)| {
8548 if adapter.name.0.as_ref() == name {
8549 Some(server.server_id())
8550 } else {
8551 None
8552 }
8553 })
8554 });
8555 Ok(server_id)
8556 })?
8557 .map(|server_id| proto::LanguageServerIdForNameResponse {
8558 server_id: server_id.map(|id| id.to_proto()),
8559 })
8560 }
8561
8562 async fn handle_rename_project_entry(
8563 this: Entity<Self>,
8564 envelope: TypedEnvelope<proto::RenameProjectEntry>,
8565 mut cx: AsyncApp,
8566 ) -> Result<proto::ProjectEntryResponse> {
8567 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8568 let (worktree_id, worktree, old_path, is_dir) = this
8569 .update(&mut cx, |this, cx| {
8570 this.worktree_store
8571 .read(cx)
8572 .worktree_and_entry_for_id(entry_id, cx)
8573 .map(|(worktree, entry)| {
8574 (
8575 worktree.read(cx).id(),
8576 worktree,
8577 entry.path.clone(),
8578 entry.is_dir(),
8579 )
8580 })
8581 })?
8582 .context("worktree not found")?;
8583 let (old_abs_path, new_abs_path) = {
8584 let root_path = worktree.read_with(&mut cx, |this, _| this.abs_path())?;
8585 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
8586 (root_path.join(&old_path), root_path.join(&new_path))
8587 };
8588
8589 Self::will_rename_entry(
8590 this.downgrade(),
8591 worktree_id,
8592 &old_abs_path,
8593 &new_abs_path,
8594 is_dir,
8595 cx.clone(),
8596 )
8597 .await;
8598 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
8599 this.read_with(&mut cx, |this, _| {
8600 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
8601 })
8602 .ok();
8603 response
8604 }
8605
8606 async fn handle_update_diagnostic_summary(
8607 this: Entity<Self>,
8608 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
8609 mut cx: AsyncApp,
8610 ) -> Result<()> {
8611 this.update(&mut cx, |this, cx| {
8612 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8613 if let Some(message) = envelope.payload.summary {
8614 let project_path = ProjectPath {
8615 worktree_id,
8616 path: Arc::<Path>::from_proto(message.path),
8617 };
8618 let path = project_path.path.clone();
8619 let server_id = LanguageServerId(message.language_server_id as usize);
8620 let summary = DiagnosticSummary {
8621 error_count: message.error_count as usize,
8622 warning_count: message.warning_count as usize,
8623 };
8624
8625 if summary.is_empty() {
8626 if let Some(worktree_summaries) =
8627 this.diagnostic_summaries.get_mut(&worktree_id)
8628 {
8629 if let Some(summaries) = worktree_summaries.get_mut(&path) {
8630 summaries.remove(&server_id);
8631 if summaries.is_empty() {
8632 worktree_summaries.remove(&path);
8633 }
8634 }
8635 }
8636 } else {
8637 this.diagnostic_summaries
8638 .entry(worktree_id)
8639 .or_default()
8640 .entry(path)
8641 .or_default()
8642 .insert(server_id, summary);
8643 }
8644 if let Some((downstream_client, project_id)) = &this.downstream_client {
8645 downstream_client
8646 .send(proto::UpdateDiagnosticSummary {
8647 project_id: *project_id,
8648 worktree_id: worktree_id.to_proto(),
8649 summary: Some(proto::DiagnosticSummary {
8650 path: project_path.path.as_ref().to_proto(),
8651 language_server_id: server_id.0 as u64,
8652 error_count: summary.error_count as u32,
8653 warning_count: summary.warning_count as u32,
8654 }),
8655 })
8656 .log_err();
8657 }
8658 cx.emit(LspStoreEvent::DiagnosticsUpdated {
8659 language_server_id: LanguageServerId(message.language_server_id as usize),
8660 path: project_path,
8661 });
8662 }
8663 Ok(())
8664 })?
8665 }
8666
8667 async fn handle_start_language_server(
8668 this: Entity<Self>,
8669 envelope: TypedEnvelope<proto::StartLanguageServer>,
8670 mut cx: AsyncApp,
8671 ) -> Result<()> {
8672 let server = envelope.payload.server.context("invalid server")?;
8673
8674 this.update(&mut cx, |this, cx| {
8675 let server_id = LanguageServerId(server.id as usize);
8676 this.language_server_statuses.insert(
8677 server_id,
8678 LanguageServerStatus {
8679 name: server.name.clone(),
8680 pending_work: Default::default(),
8681 has_pending_diagnostic_updates: false,
8682 progress_tokens: Default::default(),
8683 },
8684 );
8685 cx.emit(LspStoreEvent::LanguageServerAdded(
8686 server_id,
8687 LanguageServerName(server.name.into()),
8688 server.worktree_id.map(WorktreeId::from_proto),
8689 ));
8690 cx.notify();
8691 })?;
8692 Ok(())
8693 }
8694
8695 async fn handle_update_language_server(
8696 lsp_store: Entity<Self>,
8697 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
8698 mut cx: AsyncApp,
8699 ) -> Result<()> {
8700 lsp_store.update(&mut cx, |lsp_store, cx| {
8701 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8702
8703 match envelope.payload.variant.context("invalid variant")? {
8704 proto::update_language_server::Variant::WorkStart(payload) => {
8705 lsp_store.on_lsp_work_start(
8706 language_server_id,
8707 payload.token,
8708 LanguageServerProgress {
8709 title: payload.title,
8710 is_disk_based_diagnostics_progress: false,
8711 is_cancellable: payload.is_cancellable.unwrap_or(false),
8712 message: payload.message,
8713 percentage: payload.percentage.map(|p| p as usize),
8714 last_update_at: cx.background_executor().now(),
8715 },
8716 cx,
8717 );
8718 }
8719 proto::update_language_server::Variant::WorkProgress(payload) => {
8720 lsp_store.on_lsp_work_progress(
8721 language_server_id,
8722 payload.token,
8723 LanguageServerProgress {
8724 title: None,
8725 is_disk_based_diagnostics_progress: false,
8726 is_cancellable: payload.is_cancellable.unwrap_or(false),
8727 message: payload.message,
8728 percentage: payload.percentage.map(|p| p as usize),
8729 last_update_at: cx.background_executor().now(),
8730 },
8731 cx,
8732 );
8733 }
8734
8735 proto::update_language_server::Variant::WorkEnd(payload) => {
8736 lsp_store.on_lsp_work_end(language_server_id, payload.token, cx);
8737 }
8738
8739 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
8740 lsp_store.disk_based_diagnostics_started(language_server_id, cx);
8741 }
8742
8743 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
8744 lsp_store.disk_based_diagnostics_finished(language_server_id, cx)
8745 }
8746
8747 non_lsp @ proto::update_language_server::Variant::StatusUpdate(_)
8748 | non_lsp @ proto::update_language_server::Variant::RegisteredForBuffer(_) => {
8749 cx.emit(LspStoreEvent::LanguageServerUpdate {
8750 language_server_id,
8751 name: envelope
8752 .payload
8753 .server_name
8754 .map(SharedString::new)
8755 .map(LanguageServerName),
8756 message: non_lsp,
8757 });
8758 }
8759 }
8760
8761 Ok(())
8762 })?
8763 }
8764
8765 async fn handle_language_server_log(
8766 this: Entity<Self>,
8767 envelope: TypedEnvelope<proto::LanguageServerLog>,
8768 mut cx: AsyncApp,
8769 ) -> Result<()> {
8770 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8771 let log_type = envelope
8772 .payload
8773 .log_type
8774 .map(LanguageServerLogType::from_proto)
8775 .context("invalid language server log type")?;
8776
8777 let message = envelope.payload.message;
8778
8779 this.update(&mut cx, |_, cx| {
8780 cx.emit(LspStoreEvent::LanguageServerLog(
8781 language_server_id,
8782 log_type,
8783 message,
8784 ));
8785 })
8786 }
8787
8788 async fn handle_lsp_ext_cancel_flycheck(
8789 lsp_store: Entity<Self>,
8790 envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
8791 mut cx: AsyncApp,
8792 ) -> Result<proto::Ack> {
8793 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8794 lsp_store.read_with(&mut cx, |lsp_store, _| {
8795 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8796 server
8797 .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
8798 .context("handling lsp ext cancel flycheck")
8799 } else {
8800 anyhow::Ok(())
8801 }
8802 })??;
8803
8804 Ok(proto::Ack {})
8805 }
8806
8807 async fn handle_lsp_ext_run_flycheck(
8808 lsp_store: Entity<Self>,
8809 envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
8810 mut cx: AsyncApp,
8811 ) -> Result<proto::Ack> {
8812 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8813 lsp_store.update(&mut cx, |lsp_store, cx| {
8814 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8815 let text_document = if envelope.payload.current_file_only {
8816 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8817 lsp_store
8818 .buffer_store()
8819 .read(cx)
8820 .get(buffer_id)
8821 .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
8822 .map(|path| make_text_document_identifier(&path))
8823 .transpose()?
8824 } else {
8825 None
8826 };
8827 server
8828 .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
8829 &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
8830 )
8831 .context("handling lsp ext run flycheck")
8832 } else {
8833 anyhow::Ok(())
8834 }
8835 })??;
8836
8837 Ok(proto::Ack {})
8838 }
8839
8840 async fn handle_lsp_ext_clear_flycheck(
8841 lsp_store: Entity<Self>,
8842 envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
8843 mut cx: AsyncApp,
8844 ) -> Result<proto::Ack> {
8845 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8846 lsp_store.read_with(&mut cx, |lsp_store, _| {
8847 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8848 server
8849 .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
8850 .context("handling lsp ext clear flycheck")
8851 } else {
8852 anyhow::Ok(())
8853 }
8854 })??;
8855
8856 Ok(proto::Ack {})
8857 }
8858
8859 pub fn disk_based_diagnostics_started(
8860 &mut self,
8861 language_server_id: LanguageServerId,
8862 cx: &mut Context<Self>,
8863 ) {
8864 if let Some(language_server_status) =
8865 self.language_server_statuses.get_mut(&language_server_id)
8866 {
8867 language_server_status.has_pending_diagnostic_updates = true;
8868 }
8869
8870 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
8871 cx.emit(LspStoreEvent::LanguageServerUpdate {
8872 language_server_id,
8873 name: self
8874 .language_server_adapter_for_id(language_server_id)
8875 .map(|adapter| adapter.name()),
8876 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
8877 Default::default(),
8878 ),
8879 })
8880 }
8881
8882 pub fn disk_based_diagnostics_finished(
8883 &mut self,
8884 language_server_id: LanguageServerId,
8885 cx: &mut Context<Self>,
8886 ) {
8887 if let Some(language_server_status) =
8888 self.language_server_statuses.get_mut(&language_server_id)
8889 {
8890 language_server_status.has_pending_diagnostic_updates = false;
8891 }
8892
8893 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
8894 cx.emit(LspStoreEvent::LanguageServerUpdate {
8895 language_server_id,
8896 name: self
8897 .language_server_adapter_for_id(language_server_id)
8898 .map(|adapter| adapter.name()),
8899 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
8900 Default::default(),
8901 ),
8902 })
8903 }
8904
8905 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
8906 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
8907 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
8908 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
8909 // the language server might take some time to publish diagnostics.
8910 fn simulate_disk_based_diagnostics_events_if_needed(
8911 &mut self,
8912 language_server_id: LanguageServerId,
8913 cx: &mut Context<Self>,
8914 ) {
8915 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
8916
8917 let Some(LanguageServerState::Running {
8918 simulate_disk_based_diagnostics_completion,
8919 adapter,
8920 ..
8921 }) = self
8922 .as_local_mut()
8923 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
8924 else {
8925 return;
8926 };
8927
8928 if adapter.disk_based_diagnostics_progress_token.is_some() {
8929 return;
8930 }
8931
8932 let prev_task =
8933 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
8934 cx.background_executor()
8935 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
8936 .await;
8937
8938 this.update(cx, |this, cx| {
8939 this.disk_based_diagnostics_finished(language_server_id, cx);
8940
8941 if let Some(LanguageServerState::Running {
8942 simulate_disk_based_diagnostics_completion,
8943 ..
8944 }) = this.as_local_mut().and_then(|local_store| {
8945 local_store.language_servers.get_mut(&language_server_id)
8946 }) {
8947 *simulate_disk_based_diagnostics_completion = None;
8948 }
8949 })
8950 .ok();
8951 }));
8952
8953 if prev_task.is_none() {
8954 self.disk_based_diagnostics_started(language_server_id, cx);
8955 }
8956 }
8957
8958 pub fn language_server_statuses(
8959 &self,
8960 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
8961 self.language_server_statuses
8962 .iter()
8963 .map(|(key, value)| (*key, value))
8964 }
8965
8966 pub(super) fn did_rename_entry(
8967 &self,
8968 worktree_id: WorktreeId,
8969 old_path: &Path,
8970 new_path: &Path,
8971 is_dir: bool,
8972 ) {
8973 maybe!({
8974 let local_store = self.as_local()?;
8975
8976 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
8977 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
8978
8979 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8980 let Some(filter) = local_store
8981 .language_server_paths_watched_for_rename
8982 .get(&language_server.server_id())
8983 else {
8984 continue;
8985 };
8986
8987 if filter.should_send_did_rename(&old_uri, is_dir) {
8988 language_server
8989 .notify::<DidRenameFiles>(&RenameFilesParams {
8990 files: vec![FileRename {
8991 old_uri: old_uri.clone(),
8992 new_uri: new_uri.clone(),
8993 }],
8994 })
8995 .ok();
8996 }
8997 }
8998 Some(())
8999 });
9000 }
9001
9002 pub(super) fn will_rename_entry(
9003 this: WeakEntity<Self>,
9004 worktree_id: WorktreeId,
9005 old_path: &Path,
9006 new_path: &Path,
9007 is_dir: bool,
9008 cx: AsyncApp,
9009 ) -> Task<()> {
9010 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
9011 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
9012 cx.spawn(async move |cx| {
9013 let mut tasks = vec![];
9014 this.update(cx, |this, cx| {
9015 let local_store = this.as_local()?;
9016 let old_uri = old_uri?;
9017 let new_uri = new_uri?;
9018 for language_server in local_store.language_servers_for_worktree(worktree_id) {
9019 let Some(filter) = local_store
9020 .language_server_paths_watched_for_rename
9021 .get(&language_server.server_id())
9022 else {
9023 continue;
9024 };
9025 let Some(adapter) =
9026 this.language_server_adapter_for_id(language_server.server_id())
9027 else {
9028 continue;
9029 };
9030 if filter.should_send_will_rename(&old_uri, is_dir) {
9031 let apply_edit = cx.spawn({
9032 let old_uri = old_uri.clone();
9033 let new_uri = new_uri.clone();
9034 let language_server = language_server.clone();
9035 async move |this, cx| {
9036 let edit = language_server
9037 .request::<WillRenameFiles>(RenameFilesParams {
9038 files: vec![FileRename { old_uri, new_uri }],
9039 })
9040 .await
9041 .into_response()
9042 .context("will rename files")
9043 .log_err()
9044 .flatten()?;
9045
9046 LocalLspStore::deserialize_workspace_edit(
9047 this.upgrade()?,
9048 edit,
9049 false,
9050 adapter.clone(),
9051 language_server.clone(),
9052 cx,
9053 )
9054 .await
9055 .ok();
9056 Some(())
9057 }
9058 });
9059 tasks.push(apply_edit);
9060 }
9061 }
9062 Some(())
9063 })
9064 .ok()
9065 .flatten();
9066 for task in tasks {
9067 // Await on tasks sequentially so that the order of application of edits is deterministic
9068 // (at least with regards to the order of registration of language servers)
9069 task.await;
9070 }
9071 })
9072 }
9073
9074 fn lsp_notify_abs_paths_changed(
9075 &mut self,
9076 server_id: LanguageServerId,
9077 changes: Vec<PathEvent>,
9078 ) {
9079 maybe!({
9080 let server = self.language_server_for_id(server_id)?;
9081 let changes = changes
9082 .into_iter()
9083 .filter_map(|event| {
9084 let typ = match event.kind? {
9085 PathEventKind::Created => lsp::FileChangeType::CREATED,
9086 PathEventKind::Removed => lsp::FileChangeType::DELETED,
9087 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
9088 };
9089 Some(lsp::FileEvent {
9090 uri: file_path_to_lsp_url(&event.path).log_err()?,
9091 typ,
9092 })
9093 })
9094 .collect::<Vec<_>>();
9095 if !changes.is_empty() {
9096 server
9097 .notify::<lsp::notification::DidChangeWatchedFiles>(
9098 &lsp::DidChangeWatchedFilesParams { changes },
9099 )
9100 .ok();
9101 }
9102 Some(())
9103 });
9104 }
9105
9106 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9107 let local_lsp_store = self.as_local()?;
9108 if let Some(LanguageServerState::Running { server, .. }) =
9109 local_lsp_store.language_servers.get(&id)
9110 {
9111 Some(server.clone())
9112 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
9113 Some(Arc::clone(server))
9114 } else {
9115 None
9116 }
9117 }
9118
9119 fn on_lsp_progress(
9120 &mut self,
9121 progress: lsp::ProgressParams,
9122 language_server_id: LanguageServerId,
9123 disk_based_diagnostics_progress_token: Option<String>,
9124 cx: &mut Context<Self>,
9125 ) {
9126 let token = match progress.token {
9127 lsp::NumberOrString::String(token) => token,
9128 lsp::NumberOrString::Number(token) => {
9129 log::info!("skipping numeric progress token {}", token);
9130 return;
9131 }
9132 };
9133
9134 match progress.value {
9135 lsp::ProgressParamsValue::WorkDone(progress) => {
9136 self.handle_work_done_progress(
9137 progress,
9138 language_server_id,
9139 disk_based_diagnostics_progress_token,
9140 token,
9141 cx,
9142 );
9143 }
9144 lsp::ProgressParamsValue::WorkspaceDiagnostic(report) => {
9145 if let Some(LanguageServerState::Running {
9146 workspace_refresh_task: Some(workspace_refresh_task),
9147 ..
9148 }) = self
9149 .as_local_mut()
9150 .and_then(|local| local.language_servers.get_mut(&language_server_id))
9151 {
9152 workspace_refresh_task.progress_tx.try_send(()).ok();
9153 self.apply_workspace_diagnostic_report(language_server_id, report, cx)
9154 }
9155 }
9156 }
9157 }
9158
9159 fn handle_work_done_progress(
9160 &mut self,
9161 progress: lsp::WorkDoneProgress,
9162 language_server_id: LanguageServerId,
9163 disk_based_diagnostics_progress_token: Option<String>,
9164 token: String,
9165 cx: &mut Context<Self>,
9166 ) {
9167 let language_server_status =
9168 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
9169 status
9170 } else {
9171 return;
9172 };
9173
9174 if !language_server_status.progress_tokens.contains(&token) {
9175 return;
9176 }
9177
9178 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
9179 .as_ref()
9180 .map_or(false, |disk_based_token| {
9181 token.starts_with(disk_based_token)
9182 });
9183
9184 match progress {
9185 lsp::WorkDoneProgress::Begin(report) => {
9186 if is_disk_based_diagnostics_progress {
9187 self.disk_based_diagnostics_started(language_server_id, cx);
9188 }
9189 self.on_lsp_work_start(
9190 language_server_id,
9191 token.clone(),
9192 LanguageServerProgress {
9193 title: Some(report.title),
9194 is_disk_based_diagnostics_progress,
9195 is_cancellable: report.cancellable.unwrap_or(false),
9196 message: report.message.clone(),
9197 percentage: report.percentage.map(|p| p as usize),
9198 last_update_at: cx.background_executor().now(),
9199 },
9200 cx,
9201 );
9202 }
9203 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
9204 language_server_id,
9205 token,
9206 LanguageServerProgress {
9207 title: None,
9208 is_disk_based_diagnostics_progress,
9209 is_cancellable: report.cancellable.unwrap_or(false),
9210 message: report.message,
9211 percentage: report.percentage.map(|p| p as usize),
9212 last_update_at: cx.background_executor().now(),
9213 },
9214 cx,
9215 ),
9216 lsp::WorkDoneProgress::End(_) => {
9217 language_server_status.progress_tokens.remove(&token);
9218 self.on_lsp_work_end(language_server_id, token.clone(), cx);
9219 if is_disk_based_diagnostics_progress {
9220 self.disk_based_diagnostics_finished(language_server_id, cx);
9221 }
9222 }
9223 }
9224 }
9225
9226 fn on_lsp_work_start(
9227 &mut self,
9228 language_server_id: LanguageServerId,
9229 token: String,
9230 progress: LanguageServerProgress,
9231 cx: &mut Context<Self>,
9232 ) {
9233 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
9234 status.pending_work.insert(token.clone(), progress.clone());
9235 cx.notify();
9236 }
9237 cx.emit(LspStoreEvent::LanguageServerUpdate {
9238 language_server_id,
9239 name: self
9240 .language_server_adapter_for_id(language_server_id)
9241 .map(|adapter| adapter.name()),
9242 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
9243 token,
9244 title: progress.title,
9245 message: progress.message,
9246 percentage: progress.percentage.map(|p| p as u32),
9247 is_cancellable: Some(progress.is_cancellable),
9248 }),
9249 })
9250 }
9251
9252 fn on_lsp_work_progress(
9253 &mut self,
9254 language_server_id: LanguageServerId,
9255 token: String,
9256 progress: LanguageServerProgress,
9257 cx: &mut Context<Self>,
9258 ) {
9259 let mut did_update = false;
9260 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
9261 match status.pending_work.entry(token.clone()) {
9262 btree_map::Entry::Vacant(entry) => {
9263 entry.insert(progress.clone());
9264 did_update = true;
9265 }
9266 btree_map::Entry::Occupied(mut entry) => {
9267 let entry = entry.get_mut();
9268 if (progress.last_update_at - entry.last_update_at)
9269 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
9270 {
9271 entry.last_update_at = progress.last_update_at;
9272 if progress.message.is_some() {
9273 entry.message = progress.message.clone();
9274 }
9275 if progress.percentage.is_some() {
9276 entry.percentage = progress.percentage;
9277 }
9278 if progress.is_cancellable != entry.is_cancellable {
9279 entry.is_cancellable = progress.is_cancellable;
9280 }
9281 did_update = true;
9282 }
9283 }
9284 }
9285 }
9286
9287 if did_update {
9288 cx.emit(LspStoreEvent::LanguageServerUpdate {
9289 language_server_id,
9290 name: self
9291 .language_server_adapter_for_id(language_server_id)
9292 .map(|adapter| adapter.name()),
9293 message: proto::update_language_server::Variant::WorkProgress(
9294 proto::LspWorkProgress {
9295 token,
9296 message: progress.message,
9297 percentage: progress.percentage.map(|p| p as u32),
9298 is_cancellable: Some(progress.is_cancellable),
9299 },
9300 ),
9301 })
9302 }
9303 }
9304
9305 fn on_lsp_work_end(
9306 &mut self,
9307 language_server_id: LanguageServerId,
9308 token: String,
9309 cx: &mut Context<Self>,
9310 ) {
9311 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
9312 if let Some(work) = status.pending_work.remove(&token) {
9313 if !work.is_disk_based_diagnostics_progress {
9314 cx.emit(LspStoreEvent::RefreshInlayHints);
9315 }
9316 }
9317 cx.notify();
9318 }
9319
9320 cx.emit(LspStoreEvent::LanguageServerUpdate {
9321 language_server_id,
9322 name: self
9323 .language_server_adapter_for_id(language_server_id)
9324 .map(|adapter| adapter.name()),
9325 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
9326 })
9327 }
9328
9329 pub async fn handle_resolve_completion_documentation(
9330 this: Entity<Self>,
9331 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
9332 mut cx: AsyncApp,
9333 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
9334 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
9335
9336 let completion = this
9337 .read_with(&cx, |this, cx| {
9338 let id = LanguageServerId(envelope.payload.language_server_id as usize);
9339 let server = this
9340 .language_server_for_id(id)
9341 .with_context(|| format!("No language server {id}"))?;
9342
9343 anyhow::Ok(cx.background_spawn(async move {
9344 let can_resolve = server
9345 .capabilities()
9346 .completion_provider
9347 .as_ref()
9348 .and_then(|options| options.resolve_provider)
9349 .unwrap_or(false);
9350 if can_resolve {
9351 server
9352 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
9353 .await
9354 .into_response()
9355 .context("resolve completion item")
9356 } else {
9357 anyhow::Ok(lsp_completion)
9358 }
9359 }))
9360 })??
9361 .await?;
9362
9363 let mut documentation_is_markdown = false;
9364 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
9365 let documentation = match completion.documentation {
9366 Some(lsp::Documentation::String(text)) => text,
9367
9368 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
9369 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
9370 value
9371 }
9372
9373 _ => String::new(),
9374 };
9375
9376 // If we have a new buffer_id, that means we're talking to a new client
9377 // and want to check for new text_edits in the completion too.
9378 let mut old_replace_start = None;
9379 let mut old_replace_end = None;
9380 let mut old_insert_start = None;
9381 let mut old_insert_end = None;
9382 let mut new_text = String::default();
9383 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
9384 let buffer_snapshot = this.update(&mut cx, |this, cx| {
9385 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
9386 anyhow::Ok(buffer.read(cx).snapshot())
9387 })??;
9388
9389 if let Some(text_edit) = completion.text_edit.as_ref() {
9390 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
9391
9392 if let Some(mut edit) = edit {
9393 LineEnding::normalize(&mut edit.new_text);
9394
9395 new_text = edit.new_text;
9396 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
9397 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
9398 if let Some(insert_range) = edit.insert_range {
9399 old_insert_start = Some(serialize_anchor(&insert_range.start));
9400 old_insert_end = Some(serialize_anchor(&insert_range.end));
9401 }
9402 }
9403 }
9404 }
9405
9406 Ok(proto::ResolveCompletionDocumentationResponse {
9407 documentation,
9408 documentation_is_markdown,
9409 old_replace_start,
9410 old_replace_end,
9411 new_text,
9412 lsp_completion,
9413 old_insert_start,
9414 old_insert_end,
9415 })
9416 }
9417
9418 async fn handle_on_type_formatting(
9419 this: Entity<Self>,
9420 envelope: TypedEnvelope<proto::OnTypeFormatting>,
9421 mut cx: AsyncApp,
9422 ) -> Result<proto::OnTypeFormattingResponse> {
9423 let on_type_formatting = this.update(&mut cx, |this, cx| {
9424 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9425 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
9426 let position = envelope
9427 .payload
9428 .position
9429 .and_then(deserialize_anchor)
9430 .context("invalid position")?;
9431 anyhow::Ok(this.apply_on_type_formatting(
9432 buffer,
9433 position,
9434 envelope.payload.trigger.clone(),
9435 cx,
9436 ))
9437 })??;
9438
9439 let transaction = on_type_formatting
9440 .await?
9441 .as_ref()
9442 .map(language::proto::serialize_transaction);
9443 Ok(proto::OnTypeFormattingResponse { transaction })
9444 }
9445
9446 async fn handle_refresh_inlay_hints(
9447 this: Entity<Self>,
9448 _: TypedEnvelope<proto::RefreshInlayHints>,
9449 mut cx: AsyncApp,
9450 ) -> Result<proto::Ack> {
9451 this.update(&mut cx, |_, cx| {
9452 cx.emit(LspStoreEvent::RefreshInlayHints);
9453 })?;
9454 Ok(proto::Ack {})
9455 }
9456
9457 async fn handle_pull_workspace_diagnostics(
9458 lsp_store: Entity<Self>,
9459 envelope: TypedEnvelope<proto::PullWorkspaceDiagnostics>,
9460 mut cx: AsyncApp,
9461 ) -> Result<proto::Ack> {
9462 let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
9463 lsp_store.update(&mut cx, |lsp_store, _| {
9464 lsp_store.pull_workspace_diagnostics(server_id);
9465 })?;
9466 Ok(proto::Ack {})
9467 }
9468
9469 async fn handle_inlay_hints(
9470 this: Entity<Self>,
9471 envelope: TypedEnvelope<proto::InlayHints>,
9472 mut cx: AsyncApp,
9473 ) -> Result<proto::InlayHintsResponse> {
9474 let sender_id = envelope.original_sender_id().unwrap_or_default();
9475 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9476 let buffer = this.update(&mut cx, |this, cx| {
9477 this.buffer_store.read(cx).get_existing(buffer_id)
9478 })??;
9479 buffer
9480 .update(&mut cx, |buffer, _| {
9481 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
9482 })?
9483 .await
9484 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
9485
9486 let start = envelope
9487 .payload
9488 .start
9489 .and_then(deserialize_anchor)
9490 .context("missing range start")?;
9491 let end = envelope
9492 .payload
9493 .end
9494 .and_then(deserialize_anchor)
9495 .context("missing range end")?;
9496 let buffer_hints = this
9497 .update(&mut cx, |lsp_store, cx| {
9498 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
9499 })?
9500 .await
9501 .context("inlay hints fetch")?;
9502
9503 this.update(&mut cx, |project, cx| {
9504 InlayHints::response_to_proto(
9505 buffer_hints,
9506 project,
9507 sender_id,
9508 &buffer.read(cx).version(),
9509 cx,
9510 )
9511 })
9512 }
9513
9514 async fn handle_get_color_presentation(
9515 lsp_store: Entity<Self>,
9516 envelope: TypedEnvelope<proto::GetColorPresentation>,
9517 mut cx: AsyncApp,
9518 ) -> Result<proto::GetColorPresentationResponse> {
9519 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9520 let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
9521 lsp_store.buffer_store.read(cx).get_existing(buffer_id)
9522 })??;
9523
9524 let color = envelope
9525 .payload
9526 .color
9527 .context("invalid color resolve request")?;
9528 let start = color
9529 .lsp_range_start
9530 .context("invalid color resolve request")?;
9531 let end = color
9532 .lsp_range_end
9533 .context("invalid color resolve request")?;
9534
9535 let color = DocumentColor {
9536 lsp_range: lsp::Range {
9537 start: point_to_lsp(PointUtf16::new(start.row, start.column)),
9538 end: point_to_lsp(PointUtf16::new(end.row, end.column)),
9539 },
9540 color: lsp::Color {
9541 red: color.red,
9542 green: color.green,
9543 blue: color.blue,
9544 alpha: color.alpha,
9545 },
9546 resolved: false,
9547 color_presentations: Vec::new(),
9548 };
9549 let resolved_color = lsp_store
9550 .update(&mut cx, |lsp_store, cx| {
9551 lsp_store.resolve_color_presentation(
9552 color,
9553 buffer.clone(),
9554 LanguageServerId(envelope.payload.server_id as usize),
9555 cx,
9556 )
9557 })?
9558 .await
9559 .context("resolving color presentation")?;
9560
9561 Ok(proto::GetColorPresentationResponse {
9562 presentations: resolved_color
9563 .color_presentations
9564 .into_iter()
9565 .map(|presentation| proto::ColorPresentation {
9566 label: presentation.label.to_string(),
9567 text_edit: presentation.text_edit.map(serialize_lsp_edit),
9568 additional_text_edits: presentation
9569 .additional_text_edits
9570 .into_iter()
9571 .map(serialize_lsp_edit)
9572 .collect(),
9573 })
9574 .collect(),
9575 })
9576 }
9577
9578 async fn handle_resolve_inlay_hint(
9579 this: Entity<Self>,
9580 envelope: TypedEnvelope<proto::ResolveInlayHint>,
9581 mut cx: AsyncApp,
9582 ) -> Result<proto::ResolveInlayHintResponse> {
9583 let proto_hint = envelope
9584 .payload
9585 .hint
9586 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
9587 let hint = InlayHints::proto_to_project_hint(proto_hint)
9588 .context("resolved proto inlay hint conversion")?;
9589 let buffer = this.update(&mut cx, |this, cx| {
9590 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9591 this.buffer_store.read(cx).get_existing(buffer_id)
9592 })??;
9593 let response_hint = this
9594 .update(&mut cx, |this, cx| {
9595 this.resolve_inlay_hint(
9596 hint,
9597 buffer,
9598 LanguageServerId(envelope.payload.language_server_id as usize),
9599 cx,
9600 )
9601 })?
9602 .await
9603 .context("inlay hints fetch")?;
9604 Ok(proto::ResolveInlayHintResponse {
9605 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
9606 })
9607 }
9608
9609 async fn handle_refresh_code_lens(
9610 this: Entity<Self>,
9611 _: TypedEnvelope<proto::RefreshCodeLens>,
9612 mut cx: AsyncApp,
9613 ) -> Result<proto::Ack> {
9614 this.update(&mut cx, |_, cx| {
9615 cx.emit(LspStoreEvent::RefreshCodeLens);
9616 })?;
9617 Ok(proto::Ack {})
9618 }
9619
9620 async fn handle_open_buffer_for_symbol(
9621 this: Entity<Self>,
9622 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
9623 mut cx: AsyncApp,
9624 ) -> Result<proto::OpenBufferForSymbolResponse> {
9625 let peer_id = envelope.original_sender_id().unwrap_or_default();
9626 let symbol = envelope.payload.symbol.context("invalid symbol")?;
9627 let symbol = Self::deserialize_symbol(symbol)?;
9628 let symbol = this.read_with(&mut cx, |this, _| {
9629 let signature = this.symbol_signature(&symbol.path);
9630 anyhow::ensure!(signature == symbol.signature, "invalid symbol signature");
9631 Ok(symbol)
9632 })??;
9633 let buffer = this
9634 .update(&mut cx, |this, cx| {
9635 this.open_buffer_for_symbol(
9636 &Symbol {
9637 language_server_name: symbol.language_server_name,
9638 source_worktree_id: symbol.source_worktree_id,
9639 source_language_server_id: symbol.source_language_server_id,
9640 path: symbol.path,
9641 name: symbol.name,
9642 kind: symbol.kind,
9643 range: symbol.range,
9644 signature: symbol.signature,
9645 label: CodeLabel {
9646 text: Default::default(),
9647 runs: Default::default(),
9648 filter_range: Default::default(),
9649 },
9650 },
9651 cx,
9652 )
9653 })?
9654 .await?;
9655
9656 this.update(&mut cx, |this, cx| {
9657 let is_private = buffer
9658 .read(cx)
9659 .file()
9660 .map(|f| f.is_private())
9661 .unwrap_or_default();
9662 if is_private {
9663 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
9664 } else {
9665 this.buffer_store
9666 .update(cx, |buffer_store, cx| {
9667 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
9668 })
9669 .detach_and_log_err(cx);
9670 let buffer_id = buffer.read(cx).remote_id().to_proto();
9671 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
9672 }
9673 })?
9674 }
9675
9676 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
9677 let mut hasher = Sha256::new();
9678 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
9679 hasher.update(project_path.path.to_string_lossy().as_bytes());
9680 hasher.update(self.nonce.to_be_bytes());
9681 hasher.finalize().as_slice().try_into().unwrap()
9682 }
9683
9684 pub async fn handle_get_project_symbols(
9685 this: Entity<Self>,
9686 envelope: TypedEnvelope<proto::GetProjectSymbols>,
9687 mut cx: AsyncApp,
9688 ) -> Result<proto::GetProjectSymbolsResponse> {
9689 let symbols = this
9690 .update(&mut cx, |this, cx| {
9691 this.symbols(&envelope.payload.query, cx)
9692 })?
9693 .await?;
9694
9695 Ok(proto::GetProjectSymbolsResponse {
9696 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
9697 })
9698 }
9699
9700 pub async fn handle_restart_language_servers(
9701 this: Entity<Self>,
9702 envelope: TypedEnvelope<proto::RestartLanguageServers>,
9703 mut cx: AsyncApp,
9704 ) -> Result<proto::Ack> {
9705 this.update(&mut cx, |lsp_store, cx| {
9706 let buffers =
9707 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9708 lsp_store.restart_language_servers_for_buffers(
9709 buffers,
9710 envelope
9711 .payload
9712 .only_servers
9713 .into_iter()
9714 .filter_map(|selector| {
9715 Some(match selector.selector? {
9716 proto::language_server_selector::Selector::ServerId(server_id) => {
9717 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
9718 }
9719 proto::language_server_selector::Selector::Name(name) => {
9720 LanguageServerSelector::Name(LanguageServerName(
9721 SharedString::from(name),
9722 ))
9723 }
9724 })
9725 })
9726 .collect(),
9727 cx,
9728 );
9729 })?;
9730
9731 Ok(proto::Ack {})
9732 }
9733
9734 pub async fn handle_stop_language_servers(
9735 lsp_store: Entity<Self>,
9736 envelope: TypedEnvelope<proto::StopLanguageServers>,
9737 mut cx: AsyncApp,
9738 ) -> Result<proto::Ack> {
9739 lsp_store.update(&mut cx, |lsp_store, cx| {
9740 if envelope.payload.all
9741 && envelope.payload.also_servers.is_empty()
9742 && envelope.payload.buffer_ids.is_empty()
9743 {
9744 lsp_store.stop_all_language_servers(cx);
9745 } else {
9746 let buffers =
9747 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9748 lsp_store
9749 .stop_language_servers_for_buffers(
9750 buffers,
9751 envelope
9752 .payload
9753 .also_servers
9754 .into_iter()
9755 .filter_map(|selector| {
9756 Some(match selector.selector? {
9757 proto::language_server_selector::Selector::ServerId(
9758 server_id,
9759 ) => LanguageServerSelector::Id(LanguageServerId::from_proto(
9760 server_id,
9761 )),
9762 proto::language_server_selector::Selector::Name(name) => {
9763 LanguageServerSelector::Name(LanguageServerName(
9764 SharedString::from(name),
9765 ))
9766 }
9767 })
9768 })
9769 .collect(),
9770 cx,
9771 )
9772 .detach_and_log_err(cx);
9773 }
9774 })?;
9775
9776 Ok(proto::Ack {})
9777 }
9778
9779 pub async fn handle_cancel_language_server_work(
9780 this: Entity<Self>,
9781 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
9782 mut cx: AsyncApp,
9783 ) -> Result<proto::Ack> {
9784 this.update(&mut cx, |this, cx| {
9785 if let Some(work) = envelope.payload.work {
9786 match work {
9787 proto::cancel_language_server_work::Work::Buffers(buffers) => {
9788 let buffers =
9789 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
9790 this.cancel_language_server_work_for_buffers(buffers, cx);
9791 }
9792 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
9793 let server_id = LanguageServerId::from_proto(work.language_server_id);
9794 this.cancel_language_server_work(server_id, work.token, cx);
9795 }
9796 }
9797 }
9798 })?;
9799
9800 Ok(proto::Ack {})
9801 }
9802
9803 fn buffer_ids_to_buffers(
9804 &mut self,
9805 buffer_ids: impl Iterator<Item = u64>,
9806 cx: &mut Context<Self>,
9807 ) -> Vec<Entity<Buffer>> {
9808 buffer_ids
9809 .into_iter()
9810 .flat_map(|buffer_id| {
9811 self.buffer_store
9812 .read(cx)
9813 .get(BufferId::new(buffer_id).log_err()?)
9814 })
9815 .collect::<Vec<_>>()
9816 }
9817
9818 async fn handle_apply_additional_edits_for_completion(
9819 this: Entity<Self>,
9820 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
9821 mut cx: AsyncApp,
9822 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
9823 let (buffer, completion) = this.update(&mut cx, |this, cx| {
9824 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9825 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
9826 let completion = Self::deserialize_completion(
9827 envelope.payload.completion.context("invalid completion")?,
9828 )?;
9829 anyhow::Ok((buffer, completion))
9830 })??;
9831
9832 let apply_additional_edits = this.update(&mut cx, |this, cx| {
9833 this.apply_additional_edits_for_completion(
9834 buffer,
9835 Rc::new(RefCell::new(Box::new([Completion {
9836 replace_range: completion.replace_range,
9837 new_text: completion.new_text,
9838 source: completion.source,
9839 documentation: None,
9840 label: CodeLabel {
9841 text: Default::default(),
9842 runs: Default::default(),
9843 filter_range: Default::default(),
9844 },
9845 insert_text_mode: None,
9846 icon_path: None,
9847 confirm: None,
9848 }]))),
9849 0,
9850 false,
9851 cx,
9852 )
9853 })?;
9854
9855 Ok(proto::ApplyCompletionAdditionalEditsResponse {
9856 transaction: apply_additional_edits
9857 .await?
9858 .as_ref()
9859 .map(language::proto::serialize_transaction),
9860 })
9861 }
9862
9863 pub fn last_formatting_failure(&self) -> Option<&str> {
9864 self.last_formatting_failure.as_deref()
9865 }
9866
9867 pub fn reset_last_formatting_failure(&mut self) {
9868 self.last_formatting_failure = None;
9869 }
9870
9871 pub fn environment_for_buffer(
9872 &self,
9873 buffer: &Entity<Buffer>,
9874 cx: &mut Context<Self>,
9875 ) -> Shared<Task<Option<HashMap<String, String>>>> {
9876 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
9877 environment.update(cx, |env, cx| {
9878 env.get_buffer_environment(&buffer, &self.worktree_store, cx)
9879 })
9880 } else {
9881 Task::ready(None).shared()
9882 }
9883 }
9884
9885 pub fn format(
9886 &mut self,
9887 buffers: HashSet<Entity<Buffer>>,
9888 target: LspFormatTarget,
9889 push_to_history: bool,
9890 trigger: FormatTrigger,
9891 cx: &mut Context<Self>,
9892 ) -> Task<anyhow::Result<ProjectTransaction>> {
9893 let logger = zlog::scoped!("format");
9894 if let Some(_) = self.as_local() {
9895 zlog::trace!(logger => "Formatting locally");
9896 let logger = zlog::scoped!(logger => "local");
9897 let buffers = buffers
9898 .into_iter()
9899 .map(|buffer_handle| {
9900 let buffer = buffer_handle.read(cx);
9901 let buffer_abs_path = File::from_dyn(buffer.file())
9902 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
9903
9904 (buffer_handle, buffer_abs_path, buffer.remote_id())
9905 })
9906 .collect::<Vec<_>>();
9907
9908 cx.spawn(async move |lsp_store, cx| {
9909 let mut formattable_buffers = Vec::with_capacity(buffers.len());
9910
9911 for (handle, abs_path, id) in buffers {
9912 let env = lsp_store
9913 .update(cx, |lsp_store, cx| {
9914 lsp_store.environment_for_buffer(&handle, cx)
9915 })?
9916 .await;
9917
9918 let ranges = match &target {
9919 LspFormatTarget::Buffers => None,
9920 LspFormatTarget::Ranges(ranges) => {
9921 Some(ranges.get(&id).context("No format ranges provided for buffer")?.clone())
9922 }
9923 };
9924
9925 formattable_buffers.push(FormattableBuffer {
9926 handle,
9927 abs_path,
9928 env,
9929 ranges,
9930 });
9931 }
9932 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
9933
9934 let format_timer = zlog::time!(logger => "Formatting buffers");
9935 let result = LocalLspStore::format_locally(
9936 lsp_store.clone(),
9937 formattable_buffers,
9938 push_to_history,
9939 trigger,
9940 logger,
9941 cx,
9942 )
9943 .await;
9944 format_timer.end();
9945
9946 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
9947
9948 lsp_store.update(cx, |lsp_store, _| {
9949 lsp_store.update_last_formatting_failure(&result);
9950 })?;
9951
9952 result
9953 })
9954 } else if let Some((client, project_id)) = self.upstream_client() {
9955 zlog::trace!(logger => "Formatting remotely");
9956 let logger = zlog::scoped!(logger => "remote");
9957 // Don't support formatting ranges via remote
9958 match target {
9959 LspFormatTarget::Buffers => {}
9960 LspFormatTarget::Ranges(_) => {
9961 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
9962 return Task::ready(Ok(ProjectTransaction::default()));
9963 }
9964 }
9965
9966 let buffer_store = self.buffer_store();
9967 cx.spawn(async move |lsp_store, cx| {
9968 zlog::trace!(logger => "Sending remote format request");
9969 let request_timer = zlog::time!(logger => "remote format request");
9970 let result = client
9971 .request(proto::FormatBuffers {
9972 project_id,
9973 trigger: trigger as i32,
9974 buffer_ids: buffers
9975 .iter()
9976 .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id().into()))
9977 .collect::<Result<_>>()?,
9978 })
9979 .await
9980 .and_then(|result| result.transaction.context("missing transaction"));
9981 request_timer.end();
9982
9983 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
9984
9985 lsp_store.update(cx, |lsp_store, _| {
9986 lsp_store.update_last_formatting_failure(&result);
9987 })?;
9988
9989 let transaction_response = result?;
9990 let _timer = zlog::time!(logger => "deserializing project transaction");
9991 buffer_store
9992 .update(cx, |buffer_store, cx| {
9993 buffer_store.deserialize_project_transaction(
9994 transaction_response,
9995 push_to_history,
9996 cx,
9997 )
9998 })?
9999 .await
10000 })
10001 } else {
10002 zlog::trace!(logger => "Not formatting");
10003 Task::ready(Ok(ProjectTransaction::default()))
10004 }
10005 }
10006
10007 async fn handle_format_buffers(
10008 this: Entity<Self>,
10009 envelope: TypedEnvelope<proto::FormatBuffers>,
10010 mut cx: AsyncApp,
10011 ) -> Result<proto::FormatBuffersResponse> {
10012 let sender_id = envelope.original_sender_id().unwrap_or_default();
10013 let format = this.update(&mut cx, |this, cx| {
10014 let mut buffers = HashSet::default();
10015 for buffer_id in &envelope.payload.buffer_ids {
10016 let buffer_id = BufferId::new(*buffer_id)?;
10017 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
10018 }
10019 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
10020 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
10021 })??;
10022
10023 let project_transaction = format.await?;
10024 let project_transaction = this.update(&mut cx, |this, cx| {
10025 this.buffer_store.update(cx, |buffer_store, cx| {
10026 buffer_store.serialize_project_transaction_for_peer(
10027 project_transaction,
10028 sender_id,
10029 cx,
10030 )
10031 })
10032 })?;
10033 Ok(proto::FormatBuffersResponse {
10034 transaction: Some(project_transaction),
10035 })
10036 }
10037
10038 async fn handle_apply_code_action_kind(
10039 this: Entity<Self>,
10040 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
10041 mut cx: AsyncApp,
10042 ) -> Result<proto::ApplyCodeActionKindResponse> {
10043 let sender_id = envelope.original_sender_id().unwrap_or_default();
10044 let format = this.update(&mut cx, |this, cx| {
10045 let mut buffers = HashSet::default();
10046 for buffer_id in &envelope.payload.buffer_ids {
10047 let buffer_id = BufferId::new(*buffer_id)?;
10048 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
10049 }
10050 let kind = match envelope.payload.kind.as_str() {
10051 "" => CodeActionKind::EMPTY,
10052 "quickfix" => CodeActionKind::QUICKFIX,
10053 "refactor" => CodeActionKind::REFACTOR,
10054 "refactor.extract" => CodeActionKind::REFACTOR_EXTRACT,
10055 "refactor.inline" => CodeActionKind::REFACTOR_INLINE,
10056 "refactor.rewrite" => CodeActionKind::REFACTOR_REWRITE,
10057 "source" => CodeActionKind::SOURCE,
10058 "source.organizeImports" => CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
10059 "source.fixAll" => CodeActionKind::SOURCE_FIX_ALL,
10060 _ => anyhow::bail!(
10061 "Invalid code action kind {}",
10062 envelope.payload.kind.as_str()
10063 ),
10064 };
10065 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
10066 })??;
10067
10068 let project_transaction = format.await?;
10069 let project_transaction = this.update(&mut cx, |this, cx| {
10070 this.buffer_store.update(cx, |buffer_store, cx| {
10071 buffer_store.serialize_project_transaction_for_peer(
10072 project_transaction,
10073 sender_id,
10074 cx,
10075 )
10076 })
10077 })?;
10078 Ok(proto::ApplyCodeActionKindResponse {
10079 transaction: Some(project_transaction),
10080 })
10081 }
10082
10083 async fn shutdown_language_server(
10084 server_state: Option<LanguageServerState>,
10085 name: LanguageServerName,
10086 cx: &mut AsyncApp,
10087 ) {
10088 let server = match server_state {
10089 Some(LanguageServerState::Starting { startup, .. }) => {
10090 let mut timer = cx
10091 .background_executor()
10092 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
10093 .fuse();
10094
10095 select! {
10096 server = startup.fuse() => server,
10097 () = timer => {
10098 log::info!("timeout waiting for language server {name} to finish launching before stopping");
10099 None
10100 },
10101 }
10102 }
10103
10104 Some(LanguageServerState::Running { server, .. }) => Some(server),
10105
10106 None => None,
10107 };
10108
10109 if let Some(server) = server {
10110 if let Some(shutdown) = server.shutdown() {
10111 shutdown.await;
10112 }
10113 }
10114 }
10115
10116 // Returns a list of all of the worktrees which no longer have a language server and the root path
10117 // for the stopped server
10118 fn stop_local_language_server(
10119 &mut self,
10120 server_id: LanguageServerId,
10121 cx: &mut Context<Self>,
10122 ) -> Task<Vec<WorktreeId>> {
10123 let local = match &mut self.mode {
10124 LspStoreMode::Local(local) => local,
10125 _ => {
10126 return Task::ready(Vec::new());
10127 }
10128 };
10129
10130 let mut orphaned_worktrees = Vec::new();
10131 // Remove this server ID from all entries in the given worktree.
10132 local.language_server_ids.retain(|(worktree, _), ids| {
10133 if !ids.remove(&server_id) {
10134 return true;
10135 }
10136
10137 if ids.is_empty() {
10138 orphaned_worktrees.push(*worktree);
10139 false
10140 } else {
10141 true
10142 }
10143 });
10144 self.buffer_store.update(cx, |buffer_store, cx| {
10145 for buffer in buffer_store.buffers() {
10146 buffer.update(cx, |buffer, cx| {
10147 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
10148 buffer.set_completion_triggers(server_id, Default::default(), cx);
10149 });
10150 }
10151 });
10152
10153 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
10154 summaries.retain(|path, summaries_by_server_id| {
10155 if summaries_by_server_id.remove(&server_id).is_some() {
10156 if let Some((client, project_id)) = self.downstream_client.clone() {
10157 client
10158 .send(proto::UpdateDiagnosticSummary {
10159 project_id,
10160 worktree_id: worktree_id.to_proto(),
10161 summary: Some(proto::DiagnosticSummary {
10162 path: path.as_ref().to_proto(),
10163 language_server_id: server_id.0 as u64,
10164 error_count: 0,
10165 warning_count: 0,
10166 }),
10167 })
10168 .log_err();
10169 }
10170 !summaries_by_server_id.is_empty()
10171 } else {
10172 true
10173 }
10174 });
10175 }
10176
10177 let local = self.as_local_mut().unwrap();
10178 for diagnostics in local.diagnostics.values_mut() {
10179 diagnostics.retain(|_, diagnostics_by_server_id| {
10180 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
10181 diagnostics_by_server_id.remove(ix);
10182 !diagnostics_by_server_id.is_empty()
10183 } else {
10184 true
10185 }
10186 });
10187 }
10188 local.language_server_watched_paths.remove(&server_id);
10189
10190 let server_state = local.language_servers.remove(&server_id);
10191 self.cleanup_lsp_data(server_id);
10192 let name = self
10193 .language_server_statuses
10194 .remove(&server_id)
10195 .map(|status| LanguageServerName::from(status.name.as_str()))
10196 .or_else(|| {
10197 if let Some(LanguageServerState::Running { adapter, .. }) = server_state.as_ref() {
10198 Some(adapter.name())
10199 } else {
10200 None
10201 }
10202 });
10203
10204 if let Some(name) = name {
10205 log::info!("stopping language server {name}");
10206 self.languages
10207 .update_lsp_binary_status(name.clone(), BinaryStatus::Stopping);
10208 cx.notify();
10209
10210 return cx.spawn(async move |lsp_store, cx| {
10211 Self::shutdown_language_server(server_state, name.clone(), cx).await;
10212 lsp_store
10213 .update(cx, |lsp_store, cx| {
10214 lsp_store
10215 .languages
10216 .update_lsp_binary_status(name, BinaryStatus::Stopped);
10217 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
10218 cx.notify();
10219 })
10220 .ok();
10221 orphaned_worktrees
10222 });
10223 }
10224
10225 if server_state.is_some() {
10226 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
10227 }
10228 Task::ready(orphaned_worktrees)
10229 }
10230
10231 pub fn stop_all_language_servers(&mut self, cx: &mut Context<Self>) {
10232 if let Some((client, project_id)) = self.upstream_client() {
10233 let request = client.request(proto::StopLanguageServers {
10234 project_id,
10235 buffer_ids: Vec::new(),
10236 also_servers: Vec::new(),
10237 all: true,
10238 });
10239 cx.background_spawn(request).detach_and_log_err(cx);
10240 } else {
10241 let Some(local) = self.as_local_mut() else {
10242 return;
10243 };
10244 let language_servers_to_stop = local
10245 .language_server_ids
10246 .values()
10247 .flatten()
10248 .copied()
10249 .collect();
10250 local.lsp_tree.update(cx, |this, _| {
10251 this.remove_nodes(&language_servers_to_stop);
10252 });
10253 let tasks = language_servers_to_stop
10254 .into_iter()
10255 .map(|server| self.stop_local_language_server(server, cx))
10256 .collect::<Vec<_>>();
10257 cx.background_spawn(async move {
10258 futures::future::join_all(tasks).await;
10259 })
10260 .detach();
10261 }
10262 }
10263
10264 pub fn restart_language_servers_for_buffers(
10265 &mut self,
10266 buffers: Vec<Entity<Buffer>>,
10267 only_restart_servers: HashSet<LanguageServerSelector>,
10268 cx: &mut Context<Self>,
10269 ) {
10270 if let Some((client, project_id)) = self.upstream_client() {
10271 let request = client.request(proto::RestartLanguageServers {
10272 project_id,
10273 buffer_ids: buffers
10274 .into_iter()
10275 .map(|b| b.read(cx).remote_id().to_proto())
10276 .collect(),
10277 only_servers: only_restart_servers
10278 .into_iter()
10279 .map(|selector| {
10280 let selector = match selector {
10281 LanguageServerSelector::Id(language_server_id) => {
10282 proto::language_server_selector::Selector::ServerId(
10283 language_server_id.to_proto(),
10284 )
10285 }
10286 LanguageServerSelector::Name(language_server_name) => {
10287 proto::language_server_selector::Selector::Name(
10288 language_server_name.to_string(),
10289 )
10290 }
10291 };
10292 proto::LanguageServerSelector {
10293 selector: Some(selector),
10294 }
10295 })
10296 .collect(),
10297 all: false,
10298 });
10299 cx.background_spawn(request).detach_and_log_err(cx);
10300 } else {
10301 let stop_task = if only_restart_servers.is_empty() {
10302 self.stop_local_language_servers_for_buffers(&buffers, HashSet::default(), cx)
10303 } else {
10304 self.stop_local_language_servers_for_buffers(&[], only_restart_servers.clone(), cx)
10305 };
10306 cx.spawn(async move |lsp_store, cx| {
10307 stop_task.await;
10308 lsp_store
10309 .update(cx, |lsp_store, cx| {
10310 for buffer in buffers {
10311 lsp_store.register_buffer_with_language_servers(
10312 &buffer,
10313 only_restart_servers.clone(),
10314 true,
10315 cx,
10316 );
10317 }
10318 })
10319 .ok()
10320 })
10321 .detach();
10322 }
10323 }
10324
10325 pub fn stop_language_servers_for_buffers(
10326 &mut self,
10327 buffers: Vec<Entity<Buffer>>,
10328 also_stop_servers: HashSet<LanguageServerSelector>,
10329 cx: &mut Context<Self>,
10330 ) -> Task<Result<()>> {
10331 if let Some((client, project_id)) = self.upstream_client() {
10332 let request = client.request(proto::StopLanguageServers {
10333 project_id,
10334 buffer_ids: buffers
10335 .into_iter()
10336 .map(|b| b.read(cx).remote_id().to_proto())
10337 .collect(),
10338 also_servers: also_stop_servers
10339 .into_iter()
10340 .map(|selector| {
10341 let selector = match selector {
10342 LanguageServerSelector::Id(language_server_id) => {
10343 proto::language_server_selector::Selector::ServerId(
10344 language_server_id.to_proto(),
10345 )
10346 }
10347 LanguageServerSelector::Name(language_server_name) => {
10348 proto::language_server_selector::Selector::Name(
10349 language_server_name.to_string(),
10350 )
10351 }
10352 };
10353 proto::LanguageServerSelector {
10354 selector: Some(selector),
10355 }
10356 })
10357 .collect(),
10358 all: false,
10359 });
10360 cx.background_spawn(async move {
10361 let _ = request.await?;
10362 Ok(())
10363 })
10364 } else {
10365 let task =
10366 self.stop_local_language_servers_for_buffers(&buffers, also_stop_servers, cx);
10367 cx.background_spawn(async move {
10368 task.await;
10369 Ok(())
10370 })
10371 }
10372 }
10373
10374 fn stop_local_language_servers_for_buffers(
10375 &mut self,
10376 buffers: &[Entity<Buffer>],
10377 also_stop_servers: HashSet<LanguageServerSelector>,
10378 cx: &mut Context<Self>,
10379 ) -> Task<()> {
10380 let Some(local) = self.as_local_mut() else {
10381 return Task::ready(());
10382 };
10383 let mut language_server_names_to_stop = BTreeSet::default();
10384 let mut language_servers_to_stop = also_stop_servers
10385 .into_iter()
10386 .flat_map(|selector| match selector {
10387 LanguageServerSelector::Id(id) => Some(id),
10388 LanguageServerSelector::Name(name) => {
10389 language_server_names_to_stop.insert(name);
10390 None
10391 }
10392 })
10393 .collect::<BTreeSet<_>>();
10394
10395 let mut covered_worktrees = HashSet::default();
10396 for buffer in buffers {
10397 buffer.update(cx, |buffer, cx| {
10398 language_servers_to_stop.extend(local.language_server_ids_for_buffer(buffer, cx));
10399 if let Some(worktree_id) = buffer.file().map(|f| f.worktree_id(cx)) {
10400 if covered_worktrees.insert(worktree_id) {
10401 language_server_names_to_stop.retain(|name| {
10402 match local.language_server_ids.get(&(worktree_id, name.clone())) {
10403 Some(server_ids) => {
10404 language_servers_to_stop
10405 .extend(server_ids.into_iter().copied());
10406 false
10407 }
10408 None => true,
10409 }
10410 });
10411 }
10412 }
10413 });
10414 }
10415 for name in language_server_names_to_stop {
10416 if let Some(server_ids) = local
10417 .language_server_ids
10418 .iter()
10419 .filter(|((_, server_name), _)| server_name == &name)
10420 .map(|((_, _), server_ids)| server_ids)
10421 .max_by_key(|server_ids| server_ids.len())
10422 {
10423 language_servers_to_stop.extend(server_ids.into_iter().copied());
10424 }
10425 }
10426
10427 local.lsp_tree.update(cx, |this, _| {
10428 this.remove_nodes(&language_servers_to_stop);
10429 });
10430 let tasks = language_servers_to_stop
10431 .into_iter()
10432 .map(|server| self.stop_local_language_server(server, cx))
10433 .collect::<Vec<_>>();
10434
10435 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
10436 }
10437
10438 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
10439 let (worktree, relative_path) =
10440 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
10441
10442 let project_path = ProjectPath {
10443 worktree_id: worktree.read(cx).id(),
10444 path: relative_path.into(),
10445 };
10446
10447 Some(
10448 self.buffer_store()
10449 .read(cx)
10450 .get_by_path(&project_path)?
10451 .read(cx),
10452 )
10453 }
10454
10455 pub fn update_diagnostics(
10456 &mut self,
10457 language_server_id: LanguageServerId,
10458 params: lsp::PublishDiagnosticsParams,
10459 result_id: Option<String>,
10460 source_kind: DiagnosticSourceKind,
10461 disk_based_sources: &[String],
10462 cx: &mut Context<Self>,
10463 ) -> Result<()> {
10464 self.merge_diagnostics(
10465 language_server_id,
10466 params,
10467 result_id,
10468 source_kind,
10469 disk_based_sources,
10470 |_, _, _| false,
10471 cx,
10472 )
10473 }
10474
10475 pub fn merge_diagnostics(
10476 &mut self,
10477 language_server_id: LanguageServerId,
10478 mut params: lsp::PublishDiagnosticsParams,
10479 result_id: Option<String>,
10480 source_kind: DiagnosticSourceKind,
10481 disk_based_sources: &[String],
10482 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
10483 cx: &mut Context<Self>,
10484 ) -> Result<()> {
10485 anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
10486 let abs_path = params
10487 .uri
10488 .to_file_path()
10489 .map_err(|()| anyhow!("URI is not a file"))?;
10490 let mut diagnostics = Vec::default();
10491 let mut primary_diagnostic_group_ids = HashMap::default();
10492 let mut sources_by_group_id = HashMap::default();
10493 let mut supporting_diagnostics = HashMap::default();
10494
10495 let adapter = self.language_server_adapter_for_id(language_server_id);
10496
10497 // Ensure that primary diagnostics are always the most severe
10498 params.diagnostics.sort_by_key(|item| item.severity);
10499
10500 for diagnostic in ¶ms.diagnostics {
10501 let source = diagnostic.source.as_ref();
10502 let range = range_from_lsp(diagnostic.range);
10503 let is_supporting = diagnostic
10504 .related_information
10505 .as_ref()
10506 .map_or(false, |infos| {
10507 infos.iter().any(|info| {
10508 primary_diagnostic_group_ids.contains_key(&(
10509 source,
10510 diagnostic.code.clone(),
10511 range_from_lsp(info.location.range),
10512 ))
10513 })
10514 });
10515
10516 let is_unnecessary = diagnostic
10517 .tags
10518 .as_ref()
10519 .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
10520
10521 let underline = self
10522 .language_server_adapter_for_id(language_server_id)
10523 .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
10524
10525 if is_supporting {
10526 supporting_diagnostics.insert(
10527 (source, diagnostic.code.clone(), range),
10528 (diagnostic.severity, is_unnecessary),
10529 );
10530 } else {
10531 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
10532 let is_disk_based =
10533 source.map_or(false, |source| disk_based_sources.contains(source));
10534
10535 sources_by_group_id.insert(group_id, source);
10536 primary_diagnostic_group_ids
10537 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
10538
10539 diagnostics.push(DiagnosticEntry {
10540 range,
10541 diagnostic: Diagnostic {
10542 source: diagnostic.source.clone(),
10543 source_kind,
10544 code: diagnostic.code.clone(),
10545 code_description: diagnostic
10546 .code_description
10547 .as_ref()
10548 .and_then(|d| d.href.clone()),
10549 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
10550 markdown: adapter.as_ref().and_then(|adapter| {
10551 adapter.diagnostic_message_to_markdown(&diagnostic.message)
10552 }),
10553 message: diagnostic.message.trim().to_string(),
10554 group_id,
10555 is_primary: true,
10556 is_disk_based,
10557 is_unnecessary,
10558 underline,
10559 data: diagnostic.data.clone(),
10560 },
10561 });
10562 if let Some(infos) = &diagnostic.related_information {
10563 for info in infos {
10564 if info.location.uri == params.uri && !info.message.is_empty() {
10565 let range = range_from_lsp(info.location.range);
10566 diagnostics.push(DiagnosticEntry {
10567 range,
10568 diagnostic: Diagnostic {
10569 source: diagnostic.source.clone(),
10570 source_kind,
10571 code: diagnostic.code.clone(),
10572 code_description: diagnostic
10573 .code_description
10574 .as_ref()
10575 .and_then(|d| d.href.clone()),
10576 severity: DiagnosticSeverity::INFORMATION,
10577 markdown: adapter.as_ref().and_then(|adapter| {
10578 adapter.diagnostic_message_to_markdown(&info.message)
10579 }),
10580 message: info.message.trim().to_string(),
10581 group_id,
10582 is_primary: false,
10583 is_disk_based,
10584 is_unnecessary: false,
10585 underline,
10586 data: diagnostic.data.clone(),
10587 },
10588 });
10589 }
10590 }
10591 }
10592 }
10593 }
10594
10595 for entry in &mut diagnostics {
10596 let diagnostic = &mut entry.diagnostic;
10597 if !diagnostic.is_primary {
10598 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
10599 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
10600 source,
10601 diagnostic.code.clone(),
10602 entry.range.clone(),
10603 )) {
10604 if let Some(severity) = severity {
10605 diagnostic.severity = severity;
10606 }
10607 diagnostic.is_unnecessary = is_unnecessary;
10608 }
10609 }
10610 }
10611
10612 self.merge_diagnostic_entries(
10613 language_server_id,
10614 abs_path,
10615 result_id,
10616 params.version,
10617 diagnostics,
10618 filter,
10619 cx,
10620 )?;
10621 Ok(())
10622 }
10623
10624 fn insert_newly_running_language_server(
10625 &mut self,
10626 adapter: Arc<CachedLspAdapter>,
10627 language_server: Arc<LanguageServer>,
10628 server_id: LanguageServerId,
10629 key: (WorktreeId, LanguageServerName),
10630 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
10631 cx: &mut Context<Self>,
10632 ) {
10633 let Some(local) = self.as_local_mut() else {
10634 return;
10635 };
10636 // If the language server for this key doesn't match the server id, don't store the
10637 // server. Which will cause it to be dropped, killing the process
10638 if local
10639 .language_server_ids
10640 .get(&key)
10641 .map(|ids| !ids.contains(&server_id))
10642 .unwrap_or(false)
10643 {
10644 return;
10645 }
10646
10647 // Update language_servers collection with Running variant of LanguageServerState
10648 // indicating that the server is up and running and ready
10649 let workspace_folders = workspace_folders.lock().clone();
10650 language_server.set_workspace_folders(workspace_folders);
10651
10652 local.language_servers.insert(
10653 server_id,
10654 LanguageServerState::Running {
10655 workspace_refresh_task: lsp_workspace_diagnostics_refresh(
10656 language_server.clone(),
10657 cx,
10658 ),
10659 adapter: adapter.clone(),
10660 server: language_server.clone(),
10661 simulate_disk_based_diagnostics_completion: None,
10662 },
10663 );
10664 local
10665 .languages
10666 .update_lsp_binary_status(adapter.name(), BinaryStatus::None);
10667 if let Some(file_ops_caps) = language_server
10668 .capabilities()
10669 .workspace
10670 .as_ref()
10671 .and_then(|ws| ws.file_operations.as_ref())
10672 {
10673 let did_rename_caps = file_ops_caps.did_rename.as_ref();
10674 let will_rename_caps = file_ops_caps.will_rename.as_ref();
10675 if did_rename_caps.or(will_rename_caps).is_some() {
10676 let watcher = RenamePathsWatchedForServer::default()
10677 .with_did_rename_patterns(did_rename_caps)
10678 .with_will_rename_patterns(will_rename_caps);
10679 local
10680 .language_server_paths_watched_for_rename
10681 .insert(server_id, watcher);
10682 }
10683 }
10684
10685 self.language_server_statuses.insert(
10686 server_id,
10687 LanguageServerStatus {
10688 name: language_server.name().to_string(),
10689 pending_work: Default::default(),
10690 has_pending_diagnostic_updates: false,
10691 progress_tokens: Default::default(),
10692 },
10693 );
10694
10695 cx.emit(LspStoreEvent::LanguageServerAdded(
10696 server_id,
10697 language_server.name(),
10698 Some(key.0),
10699 ));
10700 cx.emit(LspStoreEvent::RefreshInlayHints);
10701
10702 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
10703 downstream_client
10704 .send(proto::StartLanguageServer {
10705 project_id: *project_id,
10706 server: Some(proto::LanguageServer {
10707 id: server_id.0 as u64,
10708 name: language_server.name().to_string(),
10709 worktree_id: Some(key.0.to_proto()),
10710 }),
10711 })
10712 .log_err();
10713 }
10714
10715 // Tell the language server about every open buffer in the worktree that matches the language.
10716 // Also check for buffers in worktrees that reused this server
10717 let mut worktrees_using_server = vec![key.0];
10718 if let Some(local) = self.as_local() {
10719 // Find all worktrees that have this server in their language server tree
10720 for (worktree_id, servers) in &local.lsp_tree.read(cx).instances {
10721 if *worktree_id != key.0 {
10722 for (_, server_map) in &servers.roots {
10723 if server_map.contains_key(&key.1) {
10724 worktrees_using_server.push(*worktree_id);
10725 }
10726 }
10727 }
10728 }
10729 }
10730
10731 let mut buffer_paths_registered = Vec::new();
10732 self.buffer_store.clone().update(cx, |buffer_store, cx| {
10733 for buffer_handle in buffer_store.buffers() {
10734 let buffer = buffer_handle.read(cx);
10735 let file = match File::from_dyn(buffer.file()) {
10736 Some(file) => file,
10737 None => continue,
10738 };
10739 let language = match buffer.language() {
10740 Some(language) => language,
10741 None => continue,
10742 };
10743
10744 if !worktrees_using_server.contains(&file.worktree.read(cx).id())
10745 || !self
10746 .languages
10747 .lsp_adapters(&language.name())
10748 .iter()
10749 .any(|a| a.name == key.1)
10750 {
10751 continue;
10752 }
10753 // didOpen
10754 let file = match file.as_local() {
10755 Some(file) => file,
10756 None => continue,
10757 };
10758
10759 let local = self.as_local_mut().unwrap();
10760
10761 if local.registered_buffers.contains_key(&buffer.remote_id()) {
10762 let versions = local
10763 .buffer_snapshots
10764 .entry(buffer.remote_id())
10765 .or_default()
10766 .entry(server_id)
10767 .and_modify(|_| {
10768 assert!(
10769 false,
10770 "There should not be an existing snapshot for a newly inserted buffer"
10771 )
10772 })
10773 .or_insert_with(|| {
10774 vec![LspBufferSnapshot {
10775 version: 0,
10776 snapshot: buffer.text_snapshot(),
10777 }]
10778 });
10779
10780 let snapshot = versions.last().unwrap();
10781 let version = snapshot.version;
10782 let initial_snapshot = &snapshot.snapshot;
10783 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
10784 language_server.register_buffer(
10785 uri,
10786 adapter.language_id(&language.name()),
10787 version,
10788 initial_snapshot.text(),
10789 );
10790 buffer_paths_registered.push(file.abs_path(cx));
10791 local
10792 .buffers_opened_in_servers
10793 .entry(buffer.remote_id())
10794 .or_default()
10795 .insert(server_id);
10796 }
10797 buffer_handle.update(cx, |buffer, cx| {
10798 buffer.set_completion_triggers(
10799 server_id,
10800 language_server
10801 .capabilities()
10802 .completion_provider
10803 .as_ref()
10804 .and_then(|provider| {
10805 provider
10806 .trigger_characters
10807 .as_ref()
10808 .map(|characters| characters.iter().cloned().collect())
10809 })
10810 .unwrap_or_default(),
10811 cx,
10812 )
10813 });
10814 }
10815 });
10816
10817 for abs_path in buffer_paths_registered {
10818 cx.emit(LspStoreEvent::LanguageServerUpdate {
10819 language_server_id: server_id,
10820 name: Some(adapter.name()),
10821 message: proto::update_language_server::Variant::RegisteredForBuffer(
10822 proto::RegisteredForBuffer {
10823 buffer_abs_path: abs_path.to_string_lossy().to_string(),
10824 },
10825 ),
10826 });
10827 }
10828
10829 cx.notify();
10830 }
10831
10832 pub fn language_servers_running_disk_based_diagnostics(
10833 &self,
10834 ) -> impl Iterator<Item = LanguageServerId> + '_ {
10835 self.language_server_statuses
10836 .iter()
10837 .filter_map(|(id, status)| {
10838 if status.has_pending_diagnostic_updates {
10839 Some(*id)
10840 } else {
10841 None
10842 }
10843 })
10844 }
10845
10846 pub(crate) fn cancel_language_server_work_for_buffers(
10847 &mut self,
10848 buffers: impl IntoIterator<Item = Entity<Buffer>>,
10849 cx: &mut Context<Self>,
10850 ) {
10851 if let Some((client, project_id)) = self.upstream_client() {
10852 let request = client.request(proto::CancelLanguageServerWork {
10853 project_id,
10854 work: Some(proto::cancel_language_server_work::Work::Buffers(
10855 proto::cancel_language_server_work::Buffers {
10856 buffer_ids: buffers
10857 .into_iter()
10858 .map(|b| b.read(cx).remote_id().to_proto())
10859 .collect(),
10860 },
10861 )),
10862 });
10863 cx.background_spawn(request).detach_and_log_err(cx);
10864 } else if let Some(local) = self.as_local() {
10865 let servers = buffers
10866 .into_iter()
10867 .flat_map(|buffer| {
10868 buffer.update(cx, |buffer, cx| {
10869 local.language_server_ids_for_buffer(buffer, cx).into_iter()
10870 })
10871 })
10872 .collect::<HashSet<_>>();
10873 for server_id in servers {
10874 self.cancel_language_server_work(server_id, None, cx);
10875 }
10876 }
10877 }
10878
10879 pub(crate) fn cancel_language_server_work(
10880 &mut self,
10881 server_id: LanguageServerId,
10882 token_to_cancel: Option<String>,
10883 cx: &mut Context<Self>,
10884 ) {
10885 if let Some(local) = self.as_local() {
10886 let status = self.language_server_statuses.get(&server_id);
10887 let server = local.language_servers.get(&server_id);
10888 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
10889 {
10890 for (token, progress) in &status.pending_work {
10891 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
10892 if token != token_to_cancel {
10893 continue;
10894 }
10895 }
10896 if progress.is_cancellable {
10897 server
10898 .notify::<lsp::notification::WorkDoneProgressCancel>(
10899 &WorkDoneProgressCancelParams {
10900 token: lsp::NumberOrString::String(token.clone()),
10901 },
10902 )
10903 .ok();
10904 }
10905 }
10906 }
10907 } else if let Some((client, project_id)) = self.upstream_client() {
10908 let request = client.request(proto::CancelLanguageServerWork {
10909 project_id,
10910 work: Some(
10911 proto::cancel_language_server_work::Work::LanguageServerWork(
10912 proto::cancel_language_server_work::LanguageServerWork {
10913 language_server_id: server_id.to_proto(),
10914 token: token_to_cancel,
10915 },
10916 ),
10917 ),
10918 });
10919 cx.background_spawn(request).detach_and_log_err(cx);
10920 }
10921 }
10922
10923 fn register_supplementary_language_server(
10924 &mut self,
10925 id: LanguageServerId,
10926 name: LanguageServerName,
10927 server: Arc<LanguageServer>,
10928 cx: &mut Context<Self>,
10929 ) {
10930 if let Some(local) = self.as_local_mut() {
10931 local
10932 .supplementary_language_servers
10933 .insert(id, (name.clone(), server));
10934 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
10935 }
10936 }
10937
10938 fn unregister_supplementary_language_server(
10939 &mut self,
10940 id: LanguageServerId,
10941 cx: &mut Context<Self>,
10942 ) {
10943 if let Some(local) = self.as_local_mut() {
10944 local.supplementary_language_servers.remove(&id);
10945 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
10946 }
10947 }
10948
10949 pub(crate) fn supplementary_language_servers(
10950 &self,
10951 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
10952 self.as_local().into_iter().flat_map(|local| {
10953 local
10954 .supplementary_language_servers
10955 .iter()
10956 .map(|(id, (name, _))| (*id, name.clone()))
10957 })
10958 }
10959
10960 pub fn language_server_adapter_for_id(
10961 &self,
10962 id: LanguageServerId,
10963 ) -> Option<Arc<CachedLspAdapter>> {
10964 self.as_local()
10965 .and_then(|local| local.language_servers.get(&id))
10966 .and_then(|language_server_state| match language_server_state {
10967 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
10968 _ => None,
10969 })
10970 }
10971
10972 pub(super) fn update_local_worktree_language_servers(
10973 &mut self,
10974 worktree_handle: &Entity<Worktree>,
10975 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
10976 cx: &mut Context<Self>,
10977 ) {
10978 if changes.is_empty() {
10979 return;
10980 }
10981
10982 let Some(local) = self.as_local() else { return };
10983
10984 local.prettier_store.update(cx, |prettier_store, cx| {
10985 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
10986 });
10987
10988 let worktree_id = worktree_handle.read(cx).id();
10989 let mut language_server_ids = local
10990 .language_server_ids
10991 .iter()
10992 .flat_map(|((server_worktree, _), server_ids)| {
10993 server_ids
10994 .iter()
10995 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
10996 })
10997 .collect::<Vec<_>>();
10998 language_server_ids.sort();
10999 language_server_ids.dedup();
11000
11001 let abs_path = worktree_handle.read(cx).abs_path();
11002 for server_id in &language_server_ids {
11003 if let Some(LanguageServerState::Running { server, .. }) =
11004 local.language_servers.get(server_id)
11005 {
11006 if let Some(watched_paths) = local
11007 .language_server_watched_paths
11008 .get(server_id)
11009 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
11010 {
11011 let params = lsp::DidChangeWatchedFilesParams {
11012 changes: changes
11013 .iter()
11014 .filter_map(|(path, _, change)| {
11015 if !watched_paths.is_match(path) {
11016 return None;
11017 }
11018 let typ = match change {
11019 PathChange::Loaded => return None,
11020 PathChange::Added => lsp::FileChangeType::CREATED,
11021 PathChange::Removed => lsp::FileChangeType::DELETED,
11022 PathChange::Updated => lsp::FileChangeType::CHANGED,
11023 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
11024 };
11025 Some(lsp::FileEvent {
11026 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
11027 typ,
11028 })
11029 })
11030 .collect(),
11031 };
11032 if !params.changes.is_empty() {
11033 server
11034 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
11035 .ok();
11036 }
11037 }
11038 }
11039 }
11040 }
11041
11042 pub fn wait_for_remote_buffer(
11043 &mut self,
11044 id: BufferId,
11045 cx: &mut Context<Self>,
11046 ) -> Task<Result<Entity<Buffer>>> {
11047 self.buffer_store.update(cx, |buffer_store, cx| {
11048 buffer_store.wait_for_remote_buffer(id, cx)
11049 })
11050 }
11051
11052 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
11053 proto::Symbol {
11054 language_server_name: symbol.language_server_name.0.to_string(),
11055 source_worktree_id: symbol.source_worktree_id.to_proto(),
11056 language_server_id: symbol.source_language_server_id.to_proto(),
11057 worktree_id: symbol.path.worktree_id.to_proto(),
11058 path: symbol.path.path.as_ref().to_proto(),
11059 name: symbol.name.clone(),
11060 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
11061 start: Some(proto::PointUtf16 {
11062 row: symbol.range.start.0.row,
11063 column: symbol.range.start.0.column,
11064 }),
11065 end: Some(proto::PointUtf16 {
11066 row: symbol.range.end.0.row,
11067 column: symbol.range.end.0.column,
11068 }),
11069 signature: symbol.signature.to_vec(),
11070 }
11071 }
11072
11073 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
11074 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
11075 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
11076 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
11077 let path = ProjectPath {
11078 worktree_id,
11079 path: Arc::<Path>::from_proto(serialized_symbol.path),
11080 };
11081
11082 let start = serialized_symbol.start.context("invalid start")?;
11083 let end = serialized_symbol.end.context("invalid end")?;
11084 Ok(CoreSymbol {
11085 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
11086 source_worktree_id,
11087 source_language_server_id: LanguageServerId::from_proto(
11088 serialized_symbol.language_server_id,
11089 ),
11090 path,
11091 name: serialized_symbol.name,
11092 range: Unclipped(PointUtf16::new(start.row, start.column))
11093 ..Unclipped(PointUtf16::new(end.row, end.column)),
11094 kind,
11095 signature: serialized_symbol
11096 .signature
11097 .try_into()
11098 .map_err(|_| anyhow!("invalid signature"))?,
11099 })
11100 }
11101
11102 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
11103 let mut serialized_completion = proto::Completion {
11104 old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
11105 old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
11106 new_text: completion.new_text.clone(),
11107 ..proto::Completion::default()
11108 };
11109 match &completion.source {
11110 CompletionSource::Lsp {
11111 insert_range,
11112 server_id,
11113 lsp_completion,
11114 lsp_defaults,
11115 resolved,
11116 } => {
11117 let (old_insert_start, old_insert_end) = insert_range
11118 .as_ref()
11119 .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
11120 .unzip();
11121
11122 serialized_completion.old_insert_start = old_insert_start;
11123 serialized_completion.old_insert_end = old_insert_end;
11124 serialized_completion.source = proto::completion::Source::Lsp as i32;
11125 serialized_completion.server_id = server_id.0 as u64;
11126 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
11127 serialized_completion.lsp_defaults = lsp_defaults
11128 .as_deref()
11129 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
11130 serialized_completion.resolved = *resolved;
11131 }
11132 CompletionSource::BufferWord {
11133 word_range,
11134 resolved,
11135 } => {
11136 serialized_completion.source = proto::completion::Source::BufferWord as i32;
11137 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
11138 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
11139 serialized_completion.resolved = *resolved;
11140 }
11141 CompletionSource::Custom => {
11142 serialized_completion.source = proto::completion::Source::Custom as i32;
11143 serialized_completion.resolved = true;
11144 }
11145 CompletionSource::Dap { sort_text } => {
11146 serialized_completion.source = proto::completion::Source::Dap as i32;
11147 serialized_completion.sort_text = Some(sort_text.clone());
11148 }
11149 }
11150
11151 serialized_completion
11152 }
11153
11154 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
11155 let old_replace_start = completion
11156 .old_replace_start
11157 .and_then(deserialize_anchor)
11158 .context("invalid old start")?;
11159 let old_replace_end = completion
11160 .old_replace_end
11161 .and_then(deserialize_anchor)
11162 .context("invalid old end")?;
11163 let insert_range = {
11164 match completion.old_insert_start.zip(completion.old_insert_end) {
11165 Some((start, end)) => {
11166 let start = deserialize_anchor(start).context("invalid insert old start")?;
11167 let end = deserialize_anchor(end).context("invalid insert old end")?;
11168 Some(start..end)
11169 }
11170 None => None,
11171 }
11172 };
11173 Ok(CoreCompletion {
11174 replace_range: old_replace_start..old_replace_end,
11175 new_text: completion.new_text,
11176 source: match proto::completion::Source::from_i32(completion.source) {
11177 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
11178 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
11179 insert_range,
11180 server_id: LanguageServerId::from_proto(completion.server_id),
11181 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
11182 lsp_defaults: completion
11183 .lsp_defaults
11184 .as_deref()
11185 .map(serde_json::from_slice)
11186 .transpose()?,
11187 resolved: completion.resolved,
11188 },
11189 Some(proto::completion::Source::BufferWord) => {
11190 let word_range = completion
11191 .buffer_word_start
11192 .and_then(deserialize_anchor)
11193 .context("invalid buffer word start")?
11194 ..completion
11195 .buffer_word_end
11196 .and_then(deserialize_anchor)
11197 .context("invalid buffer word end")?;
11198 CompletionSource::BufferWord {
11199 word_range,
11200 resolved: completion.resolved,
11201 }
11202 }
11203 Some(proto::completion::Source::Dap) => CompletionSource::Dap {
11204 sort_text: completion
11205 .sort_text
11206 .context("expected sort text to exist")?,
11207 },
11208 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
11209 },
11210 })
11211 }
11212
11213 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
11214 let (kind, lsp_action) = match &action.lsp_action {
11215 LspAction::Action(code_action) => (
11216 proto::code_action::Kind::Action as i32,
11217 serde_json::to_vec(code_action).unwrap(),
11218 ),
11219 LspAction::Command(command) => (
11220 proto::code_action::Kind::Command as i32,
11221 serde_json::to_vec(command).unwrap(),
11222 ),
11223 LspAction::CodeLens(code_lens) => (
11224 proto::code_action::Kind::CodeLens as i32,
11225 serde_json::to_vec(code_lens).unwrap(),
11226 ),
11227 };
11228
11229 proto::CodeAction {
11230 server_id: action.server_id.0 as u64,
11231 start: Some(serialize_anchor(&action.range.start)),
11232 end: Some(serialize_anchor(&action.range.end)),
11233 lsp_action,
11234 kind,
11235 resolved: action.resolved,
11236 }
11237 }
11238
11239 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
11240 let start = action
11241 .start
11242 .and_then(deserialize_anchor)
11243 .context("invalid start")?;
11244 let end = action
11245 .end
11246 .and_then(deserialize_anchor)
11247 .context("invalid end")?;
11248 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
11249 Some(proto::code_action::Kind::Action) => {
11250 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
11251 }
11252 Some(proto::code_action::Kind::Command) => {
11253 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
11254 }
11255 Some(proto::code_action::Kind::CodeLens) => {
11256 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
11257 }
11258 None => anyhow::bail!("Unknown action kind {}", action.kind),
11259 };
11260 Ok(CodeAction {
11261 server_id: LanguageServerId(action.server_id as usize),
11262 range: start..end,
11263 resolved: action.resolved,
11264 lsp_action,
11265 })
11266 }
11267
11268 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
11269 match &formatting_result {
11270 Ok(_) => self.last_formatting_failure = None,
11271 Err(error) => {
11272 let error_string = format!("{error:#}");
11273 log::error!("Formatting failed: {error_string}");
11274 self.last_formatting_failure
11275 .replace(error_string.lines().join(" "));
11276 }
11277 }
11278 }
11279
11280 fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
11281 for buffer_lsp_data in self.lsp_data.values_mut() {
11282 buffer_lsp_data.colors.remove(&for_server);
11283 buffer_lsp_data.cache_version += 1;
11284 }
11285 if let Some(local) = self.as_local_mut() {
11286 local.buffer_pull_diagnostics_result_ids.remove(&for_server);
11287 for buffer_servers in local.buffers_opened_in_servers.values_mut() {
11288 buffer_servers.remove(&for_server);
11289 }
11290 }
11291 }
11292
11293 pub fn result_id(
11294 &self,
11295 server_id: LanguageServerId,
11296 buffer_id: BufferId,
11297 cx: &App,
11298 ) -> Option<String> {
11299 let abs_path = self
11300 .buffer_store
11301 .read(cx)
11302 .get(buffer_id)
11303 .and_then(|b| File::from_dyn(b.read(cx).file()))
11304 .map(|f| f.abs_path(cx))?;
11305 self.as_local()?
11306 .buffer_pull_diagnostics_result_ids
11307 .get(&server_id)?
11308 .get(&abs_path)?
11309 .clone()
11310 }
11311
11312 pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
11313 let Some(local) = self.as_local() else {
11314 return HashMap::default();
11315 };
11316 local
11317 .buffer_pull_diagnostics_result_ids
11318 .get(&server_id)
11319 .into_iter()
11320 .flatten()
11321 .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
11322 .collect()
11323 }
11324
11325 pub fn pull_workspace_diagnostics(&mut self, server_id: LanguageServerId) {
11326 if let Some(LanguageServerState::Running {
11327 workspace_refresh_task: Some(workspace_refresh_task),
11328 ..
11329 }) = self
11330 .as_local_mut()
11331 .and_then(|local| local.language_servers.get_mut(&server_id))
11332 {
11333 workspace_refresh_task.refresh_tx.try_send(()).ok();
11334 }
11335 }
11336
11337 pub fn pull_workspace_diagnostics_for_buffer(&mut self, buffer_id: BufferId, cx: &mut App) {
11338 let Some(buffer) = self.buffer_store().read(cx).get_existing(buffer_id).ok() else {
11339 return;
11340 };
11341 let Some(local) = self.as_local_mut() else {
11342 return;
11343 };
11344
11345 for server_id in buffer.update(cx, |buffer, cx| {
11346 local.language_server_ids_for_buffer(buffer, cx)
11347 }) {
11348 if let Some(LanguageServerState::Running {
11349 workspace_refresh_task: Some(workspace_refresh_task),
11350 ..
11351 }) = local.language_servers.get_mut(&server_id)
11352 {
11353 workspace_refresh_task.refresh_tx.try_send(()).ok();
11354 }
11355 }
11356 }
11357
11358 fn apply_workspace_diagnostic_report(
11359 &mut self,
11360 server_id: LanguageServerId,
11361 report: lsp::WorkspaceDiagnosticReportResult,
11362 cx: &mut Context<Self>,
11363 ) {
11364 let workspace_diagnostics =
11365 GetDocumentDiagnostics::deserialize_workspace_diagnostics_report(report, server_id);
11366 for workspace_diagnostics in workspace_diagnostics {
11367 let LspPullDiagnostics::Response {
11368 server_id,
11369 uri,
11370 diagnostics,
11371 } = workspace_diagnostics.diagnostics
11372 else {
11373 continue;
11374 };
11375
11376 let adapter = self.language_server_adapter_for_id(server_id);
11377 let disk_based_sources = adapter
11378 .as_ref()
11379 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
11380 .unwrap_or(&[]);
11381
11382 match diagnostics {
11383 PulledDiagnostics::Unchanged { result_id } => {
11384 self.merge_diagnostics(
11385 server_id,
11386 lsp::PublishDiagnosticsParams {
11387 uri: uri.clone(),
11388 diagnostics: Vec::new(),
11389 version: None,
11390 },
11391 Some(result_id),
11392 DiagnosticSourceKind::Pulled,
11393 disk_based_sources,
11394 |_, _, _| true,
11395 cx,
11396 )
11397 .log_err();
11398 }
11399 PulledDiagnostics::Changed {
11400 diagnostics,
11401 result_id,
11402 } => {
11403 self.merge_diagnostics(
11404 server_id,
11405 lsp::PublishDiagnosticsParams {
11406 uri: uri.clone(),
11407 diagnostics,
11408 version: workspace_diagnostics.version,
11409 },
11410 result_id,
11411 DiagnosticSourceKind::Pulled,
11412 disk_based_sources,
11413 |buffer, old_diagnostic, cx| match old_diagnostic.source_kind {
11414 DiagnosticSourceKind::Pulled => {
11415 let buffer_url = File::from_dyn(buffer.file())
11416 .map(|f| f.abs_path(cx))
11417 .and_then(|abs_path| file_path_to_lsp_url(&abs_path).ok());
11418 buffer_url.is_none_or(|buffer_url| buffer_url != uri)
11419 }
11420 DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => true,
11421 },
11422 cx,
11423 )
11424 .log_err();
11425 }
11426 }
11427 }
11428 }
11429}
11430
11431fn subscribe_to_binary_statuses(
11432 languages: &Arc<LanguageRegistry>,
11433 cx: &mut Context<'_, LspStore>,
11434) -> Task<()> {
11435 let mut server_statuses = languages.language_server_binary_statuses();
11436 cx.spawn(async move |lsp_store, cx| {
11437 while let Some((server_name, binary_status)) = server_statuses.next().await {
11438 if lsp_store
11439 .update(cx, |_, cx| {
11440 let mut message = None;
11441 let binary_status = match binary_status {
11442 BinaryStatus::None => proto::ServerBinaryStatus::None,
11443 BinaryStatus::CheckingForUpdate => {
11444 proto::ServerBinaryStatus::CheckingForUpdate
11445 }
11446 BinaryStatus::Downloading => proto::ServerBinaryStatus::Downloading,
11447 BinaryStatus::Starting => proto::ServerBinaryStatus::Starting,
11448 BinaryStatus::Stopping => proto::ServerBinaryStatus::Stopping,
11449 BinaryStatus::Stopped => proto::ServerBinaryStatus::Stopped,
11450 BinaryStatus::Failed { error } => {
11451 message = Some(error);
11452 proto::ServerBinaryStatus::Failed
11453 }
11454 };
11455 cx.emit(LspStoreEvent::LanguageServerUpdate {
11456 // Binary updates are about the binary that might not have any language server id at that point.
11457 // Reuse `LanguageServerUpdate` for them and provide a fake id that won't be used on the receiver side.
11458 language_server_id: LanguageServerId(0),
11459 name: Some(server_name),
11460 message: proto::update_language_server::Variant::StatusUpdate(
11461 proto::StatusUpdate {
11462 message,
11463 status: Some(proto::status_update::Status::Binary(
11464 binary_status as i32,
11465 )),
11466 },
11467 ),
11468 });
11469 })
11470 .is_err()
11471 {
11472 break;
11473 }
11474 }
11475 })
11476}
11477
11478fn lsp_workspace_diagnostics_refresh(
11479 server: Arc<LanguageServer>,
11480 cx: &mut Context<'_, LspStore>,
11481) -> Option<WorkspaceRefreshTask> {
11482 let identifier = match server.capabilities().diagnostic_provider? {
11483 lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {
11484 if !diagnostic_options.workspace_diagnostics {
11485 return None;
11486 }
11487 diagnostic_options.identifier
11488 }
11489 lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {
11490 let diagnostic_options = registration_options.diagnostic_options;
11491 if !diagnostic_options.workspace_diagnostics {
11492 return None;
11493 }
11494 diagnostic_options.identifier
11495 }
11496 };
11497
11498 let (progress_tx, mut progress_rx) = mpsc::channel(1);
11499 let (mut refresh_tx, mut refresh_rx) = mpsc::channel(1);
11500 refresh_tx.try_send(()).ok();
11501
11502 let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {
11503 let mut attempts = 0;
11504 let max_attempts = 50;
11505 let mut requests = 0;
11506
11507 loop {
11508 let Some(()) = refresh_rx.recv().await else {
11509 return;
11510 };
11511
11512 'request: loop {
11513 requests += 1;
11514 if attempts > max_attempts {
11515 log::error!(
11516 "Failed to pull workspace diagnostics {max_attempts} times, aborting"
11517 );
11518 return;
11519 }
11520 let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);
11521 cx.background_executor()
11522 .timer(Duration::from_millis(backoff_millis))
11523 .await;
11524 attempts += 1;
11525
11526 let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
11527 lsp_store
11528 .all_result_ids(server.server_id())
11529 .into_iter()
11530 .filter_map(|(abs_path, result_id)| {
11531 let uri = file_path_to_lsp_url(&abs_path).ok()?;
11532 Some(lsp::PreviousResultId {
11533 uri,
11534 value: result_id,
11535 })
11536 })
11537 .collect()
11538 }) else {
11539 return;
11540 };
11541
11542 let token = format!("workspace/diagnostic-{}-{}", server.server_id(), requests);
11543
11544 progress_rx.try_recv().ok();
11545 let timer =
11546 LanguageServer::default_request_timer(cx.background_executor().clone()).fuse();
11547 let progress = pin!(progress_rx.recv().fuse());
11548 let response_result = server
11549 .request_with_timer::<lsp::WorkspaceDiagnosticRequest, _>(
11550 lsp::WorkspaceDiagnosticParams {
11551 previous_result_ids,
11552 identifier: identifier.clone(),
11553 work_done_progress_params: Default::default(),
11554 partial_result_params: lsp::PartialResultParams {
11555 partial_result_token: Some(lsp::ProgressToken::String(token)),
11556 },
11557 },
11558 select(timer, progress).then(|either| match either {
11559 Either::Left((message, ..)) => ready(message).left_future(),
11560 Either::Right(..) => pending::<String>().right_future(),
11561 }),
11562 )
11563 .await;
11564
11565 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh
11566 // > If a server closes a workspace diagnostic pull request the client should re-trigger the request.
11567 match response_result {
11568 ConnectionResult::Timeout => {
11569 log::error!("Timeout during workspace diagnostics pull");
11570 continue 'request;
11571 }
11572 ConnectionResult::ConnectionReset => {
11573 log::error!("Server closed a workspace diagnostics pull request");
11574 continue 'request;
11575 }
11576 ConnectionResult::Result(Err(e)) => {
11577 log::error!("Error during workspace diagnostics pull: {e:#}");
11578 break 'request;
11579 }
11580 ConnectionResult::Result(Ok(pulled_diagnostics)) => {
11581 attempts = 0;
11582 if lsp_store
11583 .update(cx, |lsp_store, cx| {
11584 lsp_store.apply_workspace_diagnostic_report(
11585 server.server_id(),
11586 pulled_diagnostics,
11587 cx,
11588 )
11589 })
11590 .is_err()
11591 {
11592 return;
11593 }
11594 break 'request;
11595 }
11596 }
11597 }
11598 }
11599 });
11600
11601 Some(WorkspaceRefreshTask {
11602 refresh_tx,
11603 progress_tx,
11604 task: workspace_query_language_server,
11605 })
11606}
11607
11608fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
11609 let CompletionSource::BufferWord {
11610 word_range,
11611 resolved,
11612 } = &mut completion.source
11613 else {
11614 return;
11615 };
11616 if *resolved {
11617 return;
11618 }
11619
11620 if completion.new_text
11621 != snapshot
11622 .text_for_range(word_range.clone())
11623 .collect::<String>()
11624 {
11625 return;
11626 }
11627
11628 let mut offset = 0;
11629 for chunk in snapshot.chunks(word_range.clone(), true) {
11630 let end_offset = offset + chunk.text.len();
11631 if let Some(highlight_id) = chunk.syntax_highlight_id {
11632 completion
11633 .label
11634 .runs
11635 .push((offset..end_offset, highlight_id));
11636 }
11637 offset = end_offset;
11638 }
11639 *resolved = true;
11640}
11641
11642impl EventEmitter<LspStoreEvent> for LspStore {}
11643
11644fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11645 hover
11646 .contents
11647 .retain(|hover_block| !hover_block.text.trim().is_empty());
11648 if hover.contents.is_empty() {
11649 None
11650 } else {
11651 Some(hover)
11652 }
11653}
11654
11655async fn populate_labels_for_completions(
11656 new_completions: Vec<CoreCompletion>,
11657 language: Option<Arc<Language>>,
11658 lsp_adapter: Option<Arc<CachedLspAdapter>>,
11659) -> Vec<Completion> {
11660 let lsp_completions = new_completions
11661 .iter()
11662 .filter_map(|new_completion| {
11663 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
11664 Some(lsp_completion.into_owned())
11665 } else {
11666 None
11667 }
11668 })
11669 .collect::<Vec<_>>();
11670
11671 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
11672 lsp_adapter
11673 .labels_for_completions(&lsp_completions, language)
11674 .await
11675 .log_err()
11676 .unwrap_or_default()
11677 } else {
11678 Vec::new()
11679 }
11680 .into_iter()
11681 .fuse();
11682
11683 let mut completions = Vec::new();
11684 for completion in new_completions {
11685 match completion.source.lsp_completion(true) {
11686 Some(lsp_completion) => {
11687 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
11688 Some(docs.into())
11689 } else {
11690 None
11691 };
11692
11693 let mut label = labels.next().flatten().unwrap_or_else(|| {
11694 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
11695 });
11696 ensure_uniform_list_compatible_label(&mut label);
11697 completions.push(Completion {
11698 label,
11699 documentation,
11700 replace_range: completion.replace_range,
11701 new_text: completion.new_text,
11702 insert_text_mode: lsp_completion.insert_text_mode,
11703 source: completion.source,
11704 icon_path: None,
11705 confirm: None,
11706 });
11707 }
11708 None => {
11709 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
11710 ensure_uniform_list_compatible_label(&mut label);
11711 completions.push(Completion {
11712 label,
11713 documentation: None,
11714 replace_range: completion.replace_range,
11715 new_text: completion.new_text,
11716 source: completion.source,
11717 insert_text_mode: None,
11718 icon_path: None,
11719 confirm: None,
11720 });
11721 }
11722 }
11723 }
11724 completions
11725}
11726
11727#[derive(Debug)]
11728pub enum LanguageServerToQuery {
11729 /// Query language servers in order of users preference, up until one capable of handling the request is found.
11730 FirstCapable,
11731 /// Query a specific language server.
11732 Other(LanguageServerId),
11733}
11734
11735#[derive(Default)]
11736struct RenamePathsWatchedForServer {
11737 did_rename: Vec<RenameActionPredicate>,
11738 will_rename: Vec<RenameActionPredicate>,
11739}
11740
11741impl RenamePathsWatchedForServer {
11742 fn with_did_rename_patterns(
11743 mut self,
11744 did_rename: Option<&FileOperationRegistrationOptions>,
11745 ) -> Self {
11746 if let Some(did_rename) = did_rename {
11747 self.did_rename = did_rename
11748 .filters
11749 .iter()
11750 .filter_map(|filter| filter.try_into().log_err())
11751 .collect();
11752 }
11753 self
11754 }
11755 fn with_will_rename_patterns(
11756 mut self,
11757 will_rename: Option<&FileOperationRegistrationOptions>,
11758 ) -> Self {
11759 if let Some(will_rename) = will_rename {
11760 self.will_rename = will_rename
11761 .filters
11762 .iter()
11763 .filter_map(|filter| filter.try_into().log_err())
11764 .collect();
11765 }
11766 self
11767 }
11768
11769 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
11770 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
11771 }
11772 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
11773 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
11774 }
11775}
11776
11777impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
11778 type Error = globset::Error;
11779 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
11780 Ok(Self {
11781 kind: ops.pattern.matches.clone(),
11782 glob: GlobBuilder::new(&ops.pattern.glob)
11783 .case_insensitive(
11784 ops.pattern
11785 .options
11786 .as_ref()
11787 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
11788 )
11789 .build()?
11790 .compile_matcher(),
11791 })
11792 }
11793}
11794struct RenameActionPredicate {
11795 glob: GlobMatcher,
11796 kind: Option<FileOperationPatternKind>,
11797}
11798
11799impl RenameActionPredicate {
11800 // Returns true if language server should be notified
11801 fn eval(&self, path: &str, is_dir: bool) -> bool {
11802 self.kind.as_ref().map_or(true, |kind| {
11803 let expected_kind = if is_dir {
11804 FileOperationPatternKind::Folder
11805 } else {
11806 FileOperationPatternKind::File
11807 };
11808 kind == &expected_kind
11809 }) && self.glob.is_match(path)
11810 }
11811}
11812
11813#[derive(Default)]
11814struct LanguageServerWatchedPaths {
11815 worktree_paths: HashMap<WorktreeId, GlobSet>,
11816 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
11817}
11818
11819#[derive(Default)]
11820struct LanguageServerWatchedPathsBuilder {
11821 worktree_paths: HashMap<WorktreeId, GlobSet>,
11822 abs_paths: HashMap<Arc<Path>, GlobSet>,
11823}
11824
11825impl LanguageServerWatchedPathsBuilder {
11826 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
11827 self.worktree_paths.insert(worktree_id, glob_set);
11828 }
11829 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
11830 self.abs_paths.insert(path, glob_set);
11831 }
11832 fn build(
11833 self,
11834 fs: Arc<dyn Fs>,
11835 language_server_id: LanguageServerId,
11836 cx: &mut Context<LspStore>,
11837 ) -> LanguageServerWatchedPaths {
11838 let project = cx.weak_entity();
11839
11840 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
11841 let abs_paths = self
11842 .abs_paths
11843 .into_iter()
11844 .map(|(abs_path, globset)| {
11845 let task = cx.spawn({
11846 let abs_path = abs_path.clone();
11847 let fs = fs.clone();
11848
11849 let lsp_store = project.clone();
11850 async move |_, cx| {
11851 maybe!(async move {
11852 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
11853 while let Some(update) = push_updates.0.next().await {
11854 let action = lsp_store
11855 .update(cx, |this, _| {
11856 let Some(local) = this.as_local() else {
11857 return ControlFlow::Break(());
11858 };
11859 let Some(watcher) = local
11860 .language_server_watched_paths
11861 .get(&language_server_id)
11862 else {
11863 return ControlFlow::Break(());
11864 };
11865 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
11866 "Watched abs path is not registered with a watcher",
11867 );
11868 let matching_entries = update
11869 .into_iter()
11870 .filter(|event| globs.is_match(&event.path))
11871 .collect::<Vec<_>>();
11872 this.lsp_notify_abs_paths_changed(
11873 language_server_id,
11874 matching_entries,
11875 );
11876 ControlFlow::Continue(())
11877 })
11878 .ok()?;
11879
11880 if action.is_break() {
11881 break;
11882 }
11883 }
11884 Some(())
11885 })
11886 .await;
11887 }
11888 });
11889 (abs_path, (globset, task))
11890 })
11891 .collect();
11892 LanguageServerWatchedPaths {
11893 worktree_paths: self.worktree_paths,
11894 abs_paths,
11895 }
11896 }
11897}
11898
11899struct LspBufferSnapshot {
11900 version: i32,
11901 snapshot: TextBufferSnapshot,
11902}
11903
11904/// A prompt requested by LSP server.
11905#[derive(Clone, Debug)]
11906pub struct LanguageServerPromptRequest {
11907 pub level: PromptLevel,
11908 pub message: String,
11909 pub actions: Vec<MessageActionItem>,
11910 pub lsp_name: String,
11911 pub(crate) response_channel: Sender<MessageActionItem>,
11912}
11913
11914impl LanguageServerPromptRequest {
11915 pub async fn respond(self, index: usize) -> Option<()> {
11916 if let Some(response) = self.actions.into_iter().nth(index) {
11917 self.response_channel.send(response).await.ok()
11918 } else {
11919 None
11920 }
11921 }
11922}
11923impl PartialEq for LanguageServerPromptRequest {
11924 fn eq(&self, other: &Self) -> bool {
11925 self.message == other.message && self.actions == other.actions
11926 }
11927}
11928
11929#[derive(Clone, Debug, PartialEq)]
11930pub enum LanguageServerLogType {
11931 Log(MessageType),
11932 Trace(Option<String>),
11933}
11934
11935impl LanguageServerLogType {
11936 pub fn to_proto(&self) -> proto::language_server_log::LogType {
11937 match self {
11938 Self::Log(log_type) => {
11939 let message_type = match *log_type {
11940 MessageType::ERROR => 1,
11941 MessageType::WARNING => 2,
11942 MessageType::INFO => 3,
11943 MessageType::LOG => 4,
11944 other => {
11945 log::warn!("Unknown lsp log message type: {:?}", other);
11946 4
11947 }
11948 };
11949 proto::language_server_log::LogType::LogMessageType(message_type)
11950 }
11951 Self::Trace(message) => {
11952 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
11953 message: message.clone(),
11954 })
11955 }
11956 }
11957 }
11958
11959 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
11960 match log_type {
11961 proto::language_server_log::LogType::LogMessageType(message_type) => {
11962 Self::Log(match message_type {
11963 1 => MessageType::ERROR,
11964 2 => MessageType::WARNING,
11965 3 => MessageType::INFO,
11966 4 => MessageType::LOG,
11967 _ => MessageType::LOG,
11968 })
11969 }
11970 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
11971 }
11972 }
11973}
11974
11975pub struct WorkspaceRefreshTask {
11976 refresh_tx: mpsc::Sender<()>,
11977 progress_tx: mpsc::Sender<()>,
11978 #[allow(dead_code)]
11979 task: Task<()>,
11980}
11981
11982pub enum LanguageServerState {
11983 Starting {
11984 startup: Task<Option<Arc<LanguageServer>>>,
11985 /// List of language servers that will be added to the workspace once it's initialization completes.
11986 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
11987 },
11988
11989 Running {
11990 adapter: Arc<CachedLspAdapter>,
11991 server: Arc<LanguageServer>,
11992 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
11993 workspace_refresh_task: Option<WorkspaceRefreshTask>,
11994 },
11995}
11996
11997impl LanguageServerState {
11998 fn add_workspace_folder(&self, uri: Url) {
11999 match self {
12000 LanguageServerState::Starting {
12001 pending_workspace_folders,
12002 ..
12003 } => {
12004 pending_workspace_folders.lock().insert(uri);
12005 }
12006 LanguageServerState::Running { server, .. } => {
12007 server.add_workspace_folder(uri);
12008 }
12009 }
12010 }
12011 fn _remove_workspace_folder(&self, uri: Url) {
12012 match self {
12013 LanguageServerState::Starting {
12014 pending_workspace_folders,
12015 ..
12016 } => {
12017 pending_workspace_folders.lock().remove(&uri);
12018 }
12019 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
12020 }
12021 }
12022}
12023
12024impl std::fmt::Debug for LanguageServerState {
12025 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12026 match self {
12027 LanguageServerState::Starting { .. } => {
12028 f.debug_struct("LanguageServerState::Starting").finish()
12029 }
12030 LanguageServerState::Running { .. } => {
12031 f.debug_struct("LanguageServerState::Running").finish()
12032 }
12033 }
12034 }
12035}
12036
12037#[derive(Clone, Debug, Serialize)]
12038pub struct LanguageServerProgress {
12039 pub is_disk_based_diagnostics_progress: bool,
12040 pub is_cancellable: bool,
12041 pub title: Option<String>,
12042 pub message: Option<String>,
12043 pub percentage: Option<usize>,
12044 #[serde(skip_serializing)]
12045 pub last_update_at: Instant,
12046}
12047
12048#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
12049pub struct DiagnosticSummary {
12050 pub error_count: usize,
12051 pub warning_count: usize,
12052}
12053
12054impl DiagnosticSummary {
12055 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
12056 let mut this = Self {
12057 error_count: 0,
12058 warning_count: 0,
12059 };
12060
12061 for entry in diagnostics {
12062 if entry.diagnostic.is_primary {
12063 match entry.diagnostic.severity {
12064 DiagnosticSeverity::ERROR => this.error_count += 1,
12065 DiagnosticSeverity::WARNING => this.warning_count += 1,
12066 _ => {}
12067 }
12068 }
12069 }
12070
12071 this
12072 }
12073
12074 pub fn is_empty(&self) -> bool {
12075 self.error_count == 0 && self.warning_count == 0
12076 }
12077
12078 pub fn to_proto(
12079 &self,
12080 language_server_id: LanguageServerId,
12081 path: &Path,
12082 ) -> proto::DiagnosticSummary {
12083 proto::DiagnosticSummary {
12084 path: path.to_proto(),
12085 language_server_id: language_server_id.0 as u64,
12086 error_count: self.error_count as u32,
12087 warning_count: self.warning_count as u32,
12088 }
12089 }
12090}
12091
12092#[derive(Clone, Debug)]
12093pub enum CompletionDocumentation {
12094 /// There is no documentation for this completion.
12095 Undocumented,
12096 /// A single line of documentation.
12097 SingleLine(SharedString),
12098 /// Multiple lines of plain text documentation.
12099 MultiLinePlainText(SharedString),
12100 /// Markdown documentation.
12101 MultiLineMarkdown(SharedString),
12102 /// Both single line and multiple lines of plain text documentation.
12103 SingleLineAndMultiLinePlainText {
12104 single_line: SharedString,
12105 plain_text: Option<SharedString>,
12106 },
12107}
12108
12109impl From<lsp::Documentation> for CompletionDocumentation {
12110 fn from(docs: lsp::Documentation) -> Self {
12111 match docs {
12112 lsp::Documentation::String(text) => {
12113 if text.lines().count() <= 1 {
12114 CompletionDocumentation::SingleLine(text.into())
12115 } else {
12116 CompletionDocumentation::MultiLinePlainText(text.into())
12117 }
12118 }
12119
12120 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
12121 lsp::MarkupKind::PlainText => {
12122 if value.lines().count() <= 1 {
12123 CompletionDocumentation::SingleLine(value.into())
12124 } else {
12125 CompletionDocumentation::MultiLinePlainText(value.into())
12126 }
12127 }
12128
12129 lsp::MarkupKind::Markdown => {
12130 CompletionDocumentation::MultiLineMarkdown(value.into())
12131 }
12132 },
12133 }
12134 }
12135}
12136
12137fn glob_literal_prefix(glob: &Path) -> PathBuf {
12138 glob.components()
12139 .take_while(|component| match component {
12140 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
12141 _ => true,
12142 })
12143 .collect()
12144}
12145
12146pub struct SshLspAdapter {
12147 name: LanguageServerName,
12148 binary: LanguageServerBinary,
12149 initialization_options: Option<String>,
12150 code_action_kinds: Option<Vec<CodeActionKind>>,
12151}
12152
12153impl SshLspAdapter {
12154 pub fn new(
12155 name: LanguageServerName,
12156 binary: LanguageServerBinary,
12157 initialization_options: Option<String>,
12158 code_action_kinds: Option<String>,
12159 ) -> Self {
12160 Self {
12161 name,
12162 binary,
12163 initialization_options,
12164 code_action_kinds: code_action_kinds
12165 .as_ref()
12166 .and_then(|c| serde_json::from_str(c).ok()),
12167 }
12168 }
12169}
12170
12171#[async_trait(?Send)]
12172impl LspAdapter for SshLspAdapter {
12173 fn name(&self) -> LanguageServerName {
12174 self.name.clone()
12175 }
12176
12177 async fn initialization_options(
12178 self: Arc<Self>,
12179 _: &dyn Fs,
12180 _: &Arc<dyn LspAdapterDelegate>,
12181 ) -> Result<Option<serde_json::Value>> {
12182 let Some(options) = &self.initialization_options else {
12183 return Ok(None);
12184 };
12185 let result = serde_json::from_str(options)?;
12186 Ok(result)
12187 }
12188
12189 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
12190 self.code_action_kinds.clone()
12191 }
12192
12193 async fn check_if_user_installed(
12194 &self,
12195 _: &dyn LspAdapterDelegate,
12196 _: Arc<dyn LanguageToolchainStore>,
12197 _: &AsyncApp,
12198 ) -> Option<LanguageServerBinary> {
12199 Some(self.binary.clone())
12200 }
12201
12202 async fn cached_server_binary(
12203 &self,
12204 _: PathBuf,
12205 _: &dyn LspAdapterDelegate,
12206 ) -> Option<LanguageServerBinary> {
12207 None
12208 }
12209
12210 async fn fetch_latest_server_version(
12211 &self,
12212 _: &dyn LspAdapterDelegate,
12213 ) -> Result<Box<dyn 'static + Send + Any>> {
12214 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
12215 }
12216
12217 async fn fetch_server_binary(
12218 &self,
12219 _: Box<dyn 'static + Send + Any>,
12220 _: PathBuf,
12221 _: &dyn LspAdapterDelegate,
12222 ) -> Result<LanguageServerBinary> {
12223 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
12224 }
12225}
12226
12227pub fn language_server_settings<'a>(
12228 delegate: &'a dyn LspAdapterDelegate,
12229 language: &LanguageServerName,
12230 cx: &'a App,
12231) -> Option<&'a LspSettings> {
12232 language_server_settings_for(
12233 SettingsLocation {
12234 worktree_id: delegate.worktree_id(),
12235 path: delegate.worktree_root_path(),
12236 },
12237 language,
12238 cx,
12239 )
12240}
12241
12242pub(crate) fn language_server_settings_for<'a>(
12243 location: SettingsLocation<'a>,
12244 language: &LanguageServerName,
12245 cx: &'a App,
12246) -> Option<&'a LspSettings> {
12247 ProjectSettings::get(Some(location), cx).lsp.get(language)
12248}
12249
12250pub struct LocalLspAdapterDelegate {
12251 lsp_store: WeakEntity<LspStore>,
12252 worktree: worktree::Snapshot,
12253 fs: Arc<dyn Fs>,
12254 http_client: Arc<dyn HttpClient>,
12255 language_registry: Arc<LanguageRegistry>,
12256 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
12257}
12258
12259impl LocalLspAdapterDelegate {
12260 pub fn new(
12261 language_registry: Arc<LanguageRegistry>,
12262 environment: &Entity<ProjectEnvironment>,
12263 lsp_store: WeakEntity<LspStore>,
12264 worktree: &Entity<Worktree>,
12265 http_client: Arc<dyn HttpClient>,
12266 fs: Arc<dyn Fs>,
12267 cx: &mut App,
12268 ) -> Arc<Self> {
12269 let load_shell_env_task = environment.update(cx, |env, cx| {
12270 env.get_worktree_environment(worktree.clone(), cx)
12271 });
12272
12273 Arc::new(Self {
12274 lsp_store,
12275 worktree: worktree.read(cx).snapshot(),
12276 fs,
12277 http_client,
12278 language_registry,
12279 load_shell_env_task,
12280 })
12281 }
12282
12283 fn from_local_lsp(
12284 local: &LocalLspStore,
12285 worktree: &Entity<Worktree>,
12286 cx: &mut App,
12287 ) -> Arc<Self> {
12288 Self::new(
12289 local.languages.clone(),
12290 &local.environment,
12291 local.weak.clone(),
12292 worktree,
12293 local.http_client.clone(),
12294 local.fs.clone(),
12295 cx,
12296 )
12297 }
12298}
12299
12300#[async_trait]
12301impl LspAdapterDelegate for LocalLspAdapterDelegate {
12302 fn show_notification(&self, message: &str, cx: &mut App) {
12303 self.lsp_store
12304 .update(cx, |_, cx| {
12305 cx.emit(LspStoreEvent::Notification(message.to_owned()))
12306 })
12307 .ok();
12308 }
12309
12310 fn http_client(&self) -> Arc<dyn HttpClient> {
12311 self.http_client.clone()
12312 }
12313
12314 fn worktree_id(&self) -> WorktreeId {
12315 self.worktree.id()
12316 }
12317
12318 fn worktree_root_path(&self) -> &Path {
12319 self.worktree.abs_path().as_ref()
12320 }
12321
12322 async fn shell_env(&self) -> HashMap<String, String> {
12323 let task = self.load_shell_env_task.clone();
12324 task.await.unwrap_or_default()
12325 }
12326
12327 async fn npm_package_installed_version(
12328 &self,
12329 package_name: &str,
12330 ) -> Result<Option<(PathBuf, String)>> {
12331 let local_package_directory = self.worktree_root_path();
12332 let node_modules_directory = local_package_directory.join("node_modules");
12333
12334 if let Some(version) =
12335 read_package_installed_version(node_modules_directory.clone(), package_name).await?
12336 {
12337 return Ok(Some((node_modules_directory, version)));
12338 }
12339 let Some(npm) = self.which("npm".as_ref()).await else {
12340 log::warn!(
12341 "Failed to find npm executable for {:?}",
12342 local_package_directory
12343 );
12344 return Ok(None);
12345 };
12346
12347 let env = self.shell_env().await;
12348 let output = util::command::new_smol_command(&npm)
12349 .args(["root", "-g"])
12350 .envs(env)
12351 .current_dir(local_package_directory)
12352 .output()
12353 .await?;
12354 let global_node_modules =
12355 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
12356
12357 if let Some(version) =
12358 read_package_installed_version(global_node_modules.clone(), package_name).await?
12359 {
12360 return Ok(Some((global_node_modules, version)));
12361 }
12362 return Ok(None);
12363 }
12364
12365 #[cfg(not(target_os = "windows"))]
12366 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
12367 let worktree_abs_path = self.worktree.abs_path();
12368 let shell_path = self.shell_env().await.get("PATH").cloned();
12369 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
12370 }
12371
12372 #[cfg(target_os = "windows")]
12373 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
12374 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
12375 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
12376 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
12377 which::which(command).ok()
12378 }
12379
12380 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
12381 let working_dir = self.worktree_root_path();
12382 let output = util::command::new_smol_command(&command.path)
12383 .args(command.arguments)
12384 .envs(command.env.clone().unwrap_or_default())
12385 .current_dir(working_dir)
12386 .output()
12387 .await?;
12388
12389 anyhow::ensure!(
12390 output.status.success(),
12391 "{}, stdout: {:?}, stderr: {:?}",
12392 output.status,
12393 String::from_utf8_lossy(&output.stdout),
12394 String::from_utf8_lossy(&output.stderr)
12395 );
12396 Ok(())
12397 }
12398
12399 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
12400 self.language_registry
12401 .update_lsp_binary_status(server_name, status);
12402 }
12403
12404 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
12405 self.language_registry
12406 .all_lsp_adapters()
12407 .into_iter()
12408 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
12409 .collect()
12410 }
12411
12412 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
12413 let dir = self.language_registry.language_server_download_dir(name)?;
12414
12415 if !dir.exists() {
12416 smol::fs::create_dir_all(&dir)
12417 .await
12418 .context("failed to create container directory")
12419 .log_err()?;
12420 }
12421
12422 Some(dir)
12423 }
12424
12425 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
12426 let entry = self
12427 .worktree
12428 .entry_for_path(&path)
12429 .with_context(|| format!("no worktree entry for path {path:?}"))?;
12430 let abs_path = self
12431 .worktree
12432 .absolutize(&entry.path)
12433 .with_context(|| format!("cannot absolutize path {path:?}"))?;
12434
12435 self.fs.load(&abs_path).await
12436 }
12437}
12438
12439async fn populate_labels_for_symbols(
12440 symbols: Vec<CoreSymbol>,
12441 language_registry: &Arc<LanguageRegistry>,
12442 lsp_adapter: Option<Arc<CachedLspAdapter>>,
12443 output: &mut Vec<Symbol>,
12444) {
12445 #[allow(clippy::mutable_key_type)]
12446 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
12447
12448 let mut unknown_paths = BTreeSet::new();
12449 for symbol in symbols {
12450 let language = language_registry
12451 .language_for_file_path(&symbol.path.path)
12452 .await
12453 .ok()
12454 .or_else(|| {
12455 unknown_paths.insert(symbol.path.path.clone());
12456 None
12457 });
12458 symbols_by_language
12459 .entry(language)
12460 .or_default()
12461 .push(symbol);
12462 }
12463
12464 for unknown_path in unknown_paths {
12465 log::info!(
12466 "no language found for symbol path {}",
12467 unknown_path.display()
12468 );
12469 }
12470
12471 let mut label_params = Vec::new();
12472 for (language, mut symbols) in symbols_by_language {
12473 label_params.clear();
12474 label_params.extend(
12475 symbols
12476 .iter_mut()
12477 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
12478 );
12479
12480 let mut labels = Vec::new();
12481 if let Some(language) = language {
12482 let lsp_adapter = lsp_adapter.clone().or_else(|| {
12483 language_registry
12484 .lsp_adapters(&language.name())
12485 .first()
12486 .cloned()
12487 });
12488 if let Some(lsp_adapter) = lsp_adapter {
12489 labels = lsp_adapter
12490 .labels_for_symbols(&label_params, &language)
12491 .await
12492 .log_err()
12493 .unwrap_or_default();
12494 }
12495 }
12496
12497 for ((symbol, (name, _)), label) in symbols
12498 .into_iter()
12499 .zip(label_params.drain(..))
12500 .zip(labels.into_iter().chain(iter::repeat(None)))
12501 {
12502 output.push(Symbol {
12503 language_server_name: symbol.language_server_name,
12504 source_worktree_id: symbol.source_worktree_id,
12505 source_language_server_id: symbol.source_language_server_id,
12506 path: symbol.path,
12507 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
12508 name,
12509 kind: symbol.kind,
12510 range: symbol.range,
12511 signature: symbol.signature,
12512 });
12513 }
12514 }
12515}
12516
12517fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
12518 match server.capabilities().text_document_sync.as_ref()? {
12519 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
12520 lsp::TextDocumentSyncKind::NONE => None,
12521 lsp::TextDocumentSyncKind::FULL => Some(true),
12522 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
12523 _ => None,
12524 },
12525 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
12526 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
12527 if *supported {
12528 Some(true)
12529 } else {
12530 None
12531 }
12532 }
12533 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
12534 Some(save_options.include_text.unwrap_or(false))
12535 }
12536 },
12537 }
12538}
12539
12540/// Completion items are displayed in a `UniformList`.
12541/// Usually, those items are single-line strings, but in LSP responses,
12542/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
12543/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
12544/// 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,
12545/// breaking the completions menu presentation.
12546///
12547/// 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.
12548fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
12549 let mut new_text = String::with_capacity(label.text.len());
12550 let mut offset_map = vec![0; label.text.len() + 1];
12551 let mut last_char_was_space = false;
12552 let mut new_idx = 0;
12553 let mut chars = label.text.char_indices().fuse();
12554 let mut newlines_removed = false;
12555
12556 while let Some((idx, c)) = chars.next() {
12557 offset_map[idx] = new_idx;
12558
12559 match c {
12560 '\n' if last_char_was_space => {
12561 newlines_removed = true;
12562 }
12563 '\t' | ' ' if last_char_was_space => {}
12564 '\n' if !last_char_was_space => {
12565 new_text.push(' ');
12566 new_idx += 1;
12567 last_char_was_space = true;
12568 newlines_removed = true;
12569 }
12570 ' ' | '\t' => {
12571 new_text.push(' ');
12572 new_idx += 1;
12573 last_char_was_space = true;
12574 }
12575 _ => {
12576 new_text.push(c);
12577 new_idx += c.len_utf8();
12578 last_char_was_space = false;
12579 }
12580 }
12581 }
12582 offset_map[label.text.len()] = new_idx;
12583
12584 // Only modify the label if newlines were removed.
12585 if !newlines_removed {
12586 return;
12587 }
12588
12589 let last_index = new_idx;
12590 let mut run_ranges_errors = Vec::new();
12591 label.runs.retain_mut(|(range, _)| {
12592 match offset_map.get(range.start) {
12593 Some(&start) => range.start = start,
12594 None => {
12595 run_ranges_errors.push(range.clone());
12596 return false;
12597 }
12598 }
12599
12600 match offset_map.get(range.end) {
12601 Some(&end) => range.end = end,
12602 None => {
12603 run_ranges_errors.push(range.clone());
12604 range.end = last_index;
12605 }
12606 }
12607 true
12608 });
12609 if !run_ranges_errors.is_empty() {
12610 log::error!(
12611 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
12612 label.text
12613 );
12614 }
12615
12616 let mut wrong_filter_range = None;
12617 if label.filter_range == (0..label.text.len()) {
12618 label.filter_range = 0..new_text.len();
12619 } else {
12620 let mut original_filter_range = Some(label.filter_range.clone());
12621 match offset_map.get(label.filter_range.start) {
12622 Some(&start) => label.filter_range.start = start,
12623 None => {
12624 wrong_filter_range = original_filter_range.take();
12625 label.filter_range.start = last_index;
12626 }
12627 }
12628
12629 match offset_map.get(label.filter_range.end) {
12630 Some(&end) => label.filter_range.end = end,
12631 None => {
12632 wrong_filter_range = original_filter_range.take();
12633 label.filter_range.end = last_index;
12634 }
12635 }
12636 }
12637 if let Some(wrong_filter_range) = wrong_filter_range {
12638 log::error!(
12639 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
12640 label.text
12641 );
12642 }
12643
12644 label.text = new_text;
12645}
12646
12647#[cfg(test)]
12648mod tests {
12649 use language::HighlightId;
12650
12651 use super::*;
12652
12653 #[test]
12654 fn test_glob_literal_prefix() {
12655 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
12656 assert_eq!(
12657 glob_literal_prefix(Path::new("node_modules/**/*.js")),
12658 Path::new("node_modules")
12659 );
12660 assert_eq!(
12661 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12662 Path::new("foo")
12663 );
12664 assert_eq!(
12665 glob_literal_prefix(Path::new("foo/bar/baz.js")),
12666 Path::new("foo/bar/baz.js")
12667 );
12668
12669 #[cfg(target_os = "windows")]
12670 {
12671 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
12672 assert_eq!(
12673 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
12674 Path::new("node_modules")
12675 );
12676 assert_eq!(
12677 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12678 Path::new("foo")
12679 );
12680 assert_eq!(
12681 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
12682 Path::new("foo/bar/baz.js")
12683 );
12684 }
12685 }
12686
12687 #[test]
12688 fn test_multi_len_chars_normalization() {
12689 let mut label = CodeLabel {
12690 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
12691 runs: vec![(0..6, HighlightId(1))],
12692 filter_range: 0..6,
12693 };
12694 ensure_uniform_list_compatible_label(&mut label);
12695 assert_eq!(
12696 label,
12697 CodeLabel {
12698 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
12699 runs: vec![(0..6, HighlightId(1))],
12700 filter_range: 0..6,
12701 }
12702 );
12703 }
12704}