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