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