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