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