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