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