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