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