1pub mod clangd_ext;
2pub mod lsp_ext_command;
3pub mod rust_analyzer_ext;
4
5use crate::{
6 CodeAction, Completion, CompletionSource, CoreCompletion, Hover, InlayHint, LspAction,
7 ProjectItem, ProjectPath, ProjectTransaction, ResolveState, Symbol, ToolchainStore,
8 buffer_store::{BufferStore, BufferStoreEvent},
9 environment::ProjectEnvironment,
10 lsp_command::{self, *},
11 manifest_tree::{AdapterQuery, LanguageServerTree, LaunchDisposition, ManifestTree},
12 prettier_store::{self, PrettierStore, PrettierStoreEvent},
13 project_settings::{LspSettings, ProjectSettings},
14 relativize_path, resolve_path,
15 toolchain_store::{EmptyToolchainStore, ToolchainStoreEvent},
16 worktree_store::{WorktreeStore, WorktreeStoreEvent},
17 yarn::YarnPathStore,
18};
19use anyhow::{Context as _, Result, anyhow};
20use async_trait::async_trait;
21use client::{TypedEnvelope, proto};
22use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
23use futures::{
24 AsyncWriteExt, Future, FutureExt, StreamExt,
25 future::{Shared, join_all},
26 select, select_biased,
27 stream::FuturesUnordered,
28};
29use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
30use gpui::{
31 App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString, Task,
32 WeakEntity,
33};
34use http_client::HttpClient;
35use itertools::Itertools as _;
36use language::{
37 Bias, BinaryStatus, Buffer, BufferSnapshot, CachedLspAdapter, CodeLabel, Diagnostic,
38 DiagnosticEntry, DiagnosticSet, Diff, File as _, Language, LanguageRegistry,
39 LanguageToolchainStore, LocalFile, LspAdapter, LspAdapterDelegate, Patch, PointUtf16,
40 TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
41 language_settings::{
42 FormatOnSave, Formatter, LanguageSettings, SelectedFormatter, language_settings,
43 },
44 point_to_lsp,
45 proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
46 range_from_lsp, range_to_lsp,
47};
48use lsp::{
49 CodeActionKind, CompletionContext, DiagnosticSeverity, DiagnosticTag,
50 DidChangeWatchedFilesRegistrationOptions, Edit, FileOperationFilter, FileOperationPatternKind,
51 FileOperationRegistrationOptions, FileRename, FileSystemWatcher, LanguageServer,
52 LanguageServerBinary, LanguageServerBinaryOptions, LanguageServerId, LanguageServerName,
53 LspRequestFuture, MessageActionItem, MessageType, OneOf, RenameFilesParams, SymbolKind,
54 TextEdit, WillRenameFiles, WorkDoneProgressCancelParams, WorkspaceFolder,
55 notification::DidRenameFiles,
56};
57use node_runtime::read_package_installed_version;
58use parking_lot::Mutex;
59use postage::watch;
60use rand::prelude::*;
61
62use rpc::{
63 AnyProtoClient,
64 proto::{FromProto, ToProto},
65};
66use serde::Serialize;
67use settings::{Settings, SettingsLocation, SettingsStore};
68use sha2::{Digest, Sha256};
69use smol::channel::Sender;
70use snippet::Snippet;
71use std::{
72 any::Any,
73 borrow::Cow,
74 cell::RefCell,
75 cmp::Ordering,
76 convert::TryInto,
77 ffi::OsStr,
78 iter, mem,
79 ops::{ControlFlow, Range},
80 path::{self, Path, PathBuf},
81 rc::Rc,
82 sync::Arc,
83 time::{Duration, Instant},
84};
85use text::{Anchor, BufferId, LineEnding, OffsetRangeExt};
86use url::Url;
87use util::{
88 ResultExt, TryFutureExt as _, debug_panic, defer, maybe, merge_json_value_into,
89 paths::SanitizedPath, post_inc,
90};
91
92pub use fs::*;
93pub use language::Location;
94#[cfg(any(test, feature = "test-support"))]
95pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
96pub use worktree::{
97 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
98 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
99};
100
101const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
102pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum FormatTrigger {
106 Save,
107 Manual,
108}
109
110pub enum LspFormatTarget {
111 Buffers,
112 Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
113}
114
115pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
116
117impl FormatTrigger {
118 fn from_proto(value: i32) -> FormatTrigger {
119 match value {
120 0 => FormatTrigger::Save,
121 1 => FormatTrigger::Manual,
122 _ => FormatTrigger::Save,
123 }
124 }
125}
126
127pub struct LocalLspStore {
128 weak: WeakEntity<LspStore>,
129 worktree_store: Entity<WorktreeStore>,
130 toolchain_store: Entity<ToolchainStore>,
131 http_client: Arc<dyn HttpClient>,
132 environment: Entity<ProjectEnvironment>,
133 fs: Arc<dyn Fs>,
134 languages: Arc<LanguageRegistry>,
135 language_server_ids: HashMap<(WorktreeId, LanguageServerName), BTreeSet<LanguageServerId>>,
136 yarn: Entity<YarnPathStore>,
137 pub language_servers: HashMap<LanguageServerId, LanguageServerState>,
138 buffers_being_formatted: HashSet<BufferId>,
139 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
140 language_server_watched_paths: HashMap<LanguageServerId, LanguageServerWatchedPaths>,
141 language_server_paths_watched_for_rename:
142 HashMap<LanguageServerId, RenamePathsWatchedForServer>,
143 language_server_watcher_registrations:
144 HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
145 supplementary_language_servers:
146 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
147 prettier_store: Entity<PrettierStore>,
148 next_diagnostic_group_id: usize,
149 diagnostics: HashMap<
150 WorktreeId,
151 HashMap<
152 Arc<Path>,
153 Vec<(
154 LanguageServerId,
155 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
156 )>,
157 >,
158 >,
159 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
160 _subscription: gpui::Subscription,
161 lsp_tree: Entity<LanguageServerTree>,
162 registered_buffers: HashMap<BufferId, usize>,
163}
164
165impl LocalLspStore {
166 /// Returns the running language server for the given ID. Note if the language server is starting, it will not be returned.
167 pub fn running_language_server_for_id(
168 &self,
169 id: LanguageServerId,
170 ) -> Option<&Arc<LanguageServer>> {
171 let language_server_state = self.language_servers.get(&id)?;
172
173 match language_server_state {
174 LanguageServerState::Running { server, .. } => Some(server),
175 LanguageServerState::Starting { .. } => None,
176 }
177 }
178
179 fn start_language_server(
180 &mut self,
181 worktree_handle: &Entity<Worktree>,
182 delegate: Arc<LocalLspAdapterDelegate>,
183 adapter: Arc<CachedLspAdapter>,
184 settings: Arc<LspSettings>,
185 cx: &mut App,
186 ) -> LanguageServerId {
187 let worktree = worktree_handle.read(cx);
188 let worktree_id = worktree.id();
189 let root_path = worktree.abs_path();
190 let key = (worktree_id, adapter.name.clone());
191
192 let override_options = settings.initialization_options.clone();
193
194 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
195
196 let server_id = self.languages.next_language_server_id();
197 log::info!(
198 "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
199 adapter.name.0
200 );
201
202 let binary = self.get_language_server_binary(adapter.clone(), delegate.clone(), true, cx);
203 let pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
204 let pending_server = cx.spawn({
205 let adapter = adapter.clone();
206 let server_name = adapter.name.clone();
207 let stderr_capture = stderr_capture.clone();
208 #[cfg(any(test, feature = "test-support"))]
209 let lsp_store = self.weak.clone();
210 let pending_workspace_folders = pending_workspace_folders.clone();
211 async move |cx| {
212 let binary = binary.await?;
213 #[cfg(any(test, feature = "test-support"))]
214 if let Some(server) = lsp_store
215 .update(&mut cx.clone(), |this, cx| {
216 this.languages.create_fake_language_server(
217 server_id,
218 &server_name,
219 binary.clone(),
220 &mut cx.to_async(),
221 )
222 })
223 .ok()
224 .flatten()
225 {
226 return Ok(server);
227 }
228
229 lsp::LanguageServer::new(
230 stderr_capture,
231 server_id,
232 server_name,
233 binary,
234 &root_path,
235 adapter.code_action_kinds(),
236 pending_workspace_folders,
237 cx,
238 )
239 }
240 });
241
242 let startup = {
243 let server_name = adapter.name.0.clone();
244 let delegate = delegate as Arc<dyn LspAdapterDelegate>;
245 let key = key.clone();
246 let adapter = adapter.clone();
247 let this = self.weak.clone();
248 let pending_workspace_folders = pending_workspace_folders.clone();
249 let fs = self.fs.clone();
250 cx.spawn(async move |cx| {
251 let result = async {
252 let toolchains = this.update(cx, |this, cx| this.toolchain_store(cx))?;
253 let language_server = pending_server.await?;
254
255 let workspace_config = Self::workspace_configuration_for_adapter(
256 adapter.adapter.clone(),
257 fs.as_ref(),
258 &delegate,
259 toolchains.clone(),
260 cx,
261 )
262 .await?;
263
264 let mut initialization_options = Self::initialization_options_for_adapter(
265 adapter.adapter.clone(),
266 fs.as_ref(),
267 &delegate,
268 )
269 .await?;
270
271 match (&mut initialization_options, override_options) {
272 (Some(initialization_options), Some(override_options)) => {
273 merge_json_value_into(override_options, initialization_options);
274 }
275 (None, override_options) => initialization_options = override_options,
276 _ => {}
277 }
278
279 let initialization_params = cx.update(|cx| {
280 let mut params = language_server.default_initialize_params(cx);
281 params.initialization_options = initialization_options;
282 adapter.adapter.prepare_initialize_params(params, cx)
283 })??;
284
285 Self::setup_lsp_messages(
286 this.clone(),
287 fs,
288 &language_server,
289 delegate.clone(),
290 adapter.clone(),
291 );
292
293 let did_change_configuration_params =
294 Arc::new(lsp::DidChangeConfigurationParams {
295 settings: workspace_config,
296 });
297 let language_server = cx
298 .update(|cx| {
299 language_server.initialize(
300 initialization_params,
301 did_change_configuration_params.clone(),
302 cx,
303 )
304 })?
305 .await
306 .inspect_err(|_| {
307 if let Some(this) = this.upgrade() {
308 this.update(cx, |_, cx| {
309 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id))
310 })
311 .ok();
312 }
313 })?;
314
315 language_server
316 .notify::<lsp::notification::DidChangeConfiguration>(
317 &did_change_configuration_params,
318 )
319 .ok();
320
321 anyhow::Ok(language_server)
322 }
323 .await;
324
325 match result {
326 Ok(server) => {
327 this.update(cx, |this, mut cx| {
328 this.insert_newly_running_language_server(
329 adapter,
330 server.clone(),
331 server_id,
332 key,
333 pending_workspace_folders,
334 &mut cx,
335 );
336 })
337 .ok();
338 stderr_capture.lock().take();
339 Some(server)
340 }
341
342 Err(err) => {
343 let log = stderr_capture.lock().take().unwrap_or_default();
344 delegate.update_status(
345 adapter.name(),
346 BinaryStatus::Failed {
347 error: format!("{err}\n-- stderr--\n{}", log),
348 },
349 );
350 log::error!("Failed to start language server {server_name:?}: {err}");
351 log::error!("server stderr: {:?}", log);
352 None
353 }
354 }
355 })
356 };
357 let state = LanguageServerState::Starting {
358 startup,
359 pending_workspace_folders,
360 };
361
362 self.language_servers.insert(server_id, state);
363 self.language_server_ids
364 .entry(key)
365 .or_default()
366 .insert(server_id);
367 server_id
368 }
369
370 fn get_language_server_binary(
371 &self,
372 adapter: Arc<CachedLspAdapter>,
373 delegate: Arc<dyn LspAdapterDelegate>,
374 allow_binary_download: bool,
375 cx: &mut App,
376 ) -> Task<Result<LanguageServerBinary>> {
377 let settings = ProjectSettings::get(
378 Some(SettingsLocation {
379 worktree_id: delegate.worktree_id(),
380 path: Path::new(""),
381 }),
382 cx,
383 )
384 .lsp
385 .get(&adapter.name)
386 .and_then(|s| s.binary.clone());
387
388 if settings.as_ref().is_some_and(|b| b.path.is_some()) {
389 let settings = settings.unwrap();
390
391 return cx.spawn(async move |_| {
392 let mut env = delegate.shell_env().await;
393 env.extend(settings.env.unwrap_or_default());
394
395 Ok(LanguageServerBinary {
396 path: PathBuf::from(&settings.path.unwrap()),
397 env: Some(env),
398 arguments: settings
399 .arguments
400 .unwrap_or_default()
401 .iter()
402 .map(Into::into)
403 .collect(),
404 })
405 });
406 }
407 let lsp_binary_options = LanguageServerBinaryOptions {
408 allow_path_lookup: !settings
409 .as_ref()
410 .and_then(|b| b.ignore_system_version)
411 .unwrap_or_default(),
412 allow_binary_download,
413 };
414 let toolchains = self.toolchain_store.read(cx).as_language_toolchain_store();
415 cx.spawn(async move |cx| {
416 let binary_result = adapter
417 .clone()
418 .get_language_server_command(delegate.clone(), toolchains, lsp_binary_options, cx)
419 .await;
420
421 delegate.update_status(adapter.name.clone(), BinaryStatus::None);
422
423 let mut binary = binary_result?;
424 let mut shell_env = delegate.shell_env().await;
425
426 if let Some(settings) = settings {
427 if let Some(arguments) = settings.arguments {
428 binary.arguments = arguments.into_iter().map(Into::into).collect();
429 }
430 if let Some(env) = settings.env {
431 shell_env.extend(env);
432 }
433 }
434
435 binary.env = Some(shell_env);
436 Ok(binary)
437 })
438 }
439
440 fn setup_lsp_messages(
441 this: WeakEntity<LspStore>,
442 fs: Arc<dyn Fs>,
443 language_server: &LanguageServer,
444 delegate: Arc<dyn LspAdapterDelegate>,
445 adapter: Arc<CachedLspAdapter>,
446 ) {
447 let name = language_server.name();
448 let server_id = language_server.server_id();
449 language_server
450 .on_notification::<lsp::notification::PublishDiagnostics, _>({
451 let adapter = adapter.clone();
452 let this = this.clone();
453 move |mut params, cx| {
454 let adapter = adapter.clone();
455 if let Some(this) = this.upgrade() {
456 this.update(cx, |this, cx| {
457 {
458 let buffer = params
459 .uri
460 .to_file_path()
461 .map(|file_path| this.get_buffer(&file_path, cx))
462 .ok()
463 .flatten();
464 adapter.process_diagnostics(&mut params, server_id, buffer);
465 }
466
467 this.update_diagnostics(
468 server_id,
469 params,
470 &adapter.disk_based_diagnostic_sources,
471 cx,
472 )
473 .log_err();
474 })
475 .ok();
476 }
477 }
478 })
479 .detach();
480 language_server
481 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
482 let adapter = adapter.adapter.clone();
483 let delegate = delegate.clone();
484 let this = this.clone();
485 let fs = fs.clone();
486 move |params, cx| {
487 let adapter = adapter.clone();
488 let delegate = delegate.clone();
489 let this = this.clone();
490 let fs = fs.clone();
491 let mut cx = cx.clone();
492 async move {
493 let toolchains =
494 this.update(&mut cx, |this, cx| this.toolchain_store(cx))?;
495
496 let workspace_config = Self::workspace_configuration_for_adapter(
497 adapter.clone(),
498 fs.as_ref(),
499 &delegate,
500 toolchains.clone(),
501 &mut cx,
502 )
503 .await?;
504
505 Ok(params
506 .items
507 .into_iter()
508 .map(|item| {
509 if let Some(section) = &item.section {
510 workspace_config
511 .get(section)
512 .cloned()
513 .unwrap_or(serde_json::Value::Null)
514 } else {
515 workspace_config.clone()
516 }
517 })
518 .collect())
519 }
520 }
521 })
522 .detach();
523
524 language_server
525 .on_request::<lsp::request::WorkspaceFoldersRequest, _, _>({
526 let this = this.clone();
527 move |_, cx| {
528 let this = this.clone();
529 let mut cx = cx.clone();
530 async move {
531 let Some(server) =
532 this.update(&mut cx, |this, _| this.language_server_for_id(server_id))?
533 else {
534 return Ok(None);
535 };
536 let root = server.workspace_folders();
537 Ok(Some(
538 root.iter()
539 .cloned()
540 .map(|uri| WorkspaceFolder {
541 uri,
542 name: Default::default(),
543 })
544 .collect(),
545 ))
546 }
547 }
548 })
549 .detach();
550 // Even though we don't have handling for these requests, respond to them to
551 // avoid stalling any language server like `gopls` which waits for a response
552 // to these requests when initializing.
553 language_server
554 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
555 let this = this.clone();
556 move |params, cx| {
557 let this = this.clone();
558 let mut cx = cx.clone();
559 async move {
560 this.update(&mut cx, |this, _| {
561 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
562 {
563 if let lsp::NumberOrString::String(token) = params.token {
564 status.progress_tokens.insert(token);
565 }
566 }
567 })?;
568
569 Ok(())
570 }
571 }
572 })
573 .detach();
574
575 language_server
576 .on_request::<lsp::request::RegisterCapability, _, _>({
577 let this = this.clone();
578 move |params, cx| {
579 let this = this.clone();
580 let mut cx = cx.clone();
581 async move {
582 for reg in params.registrations {
583 match reg.method.as_str() {
584 "workspace/didChangeWatchedFiles" => {
585 if let Some(options) = reg.register_options {
586 let options = serde_json::from_value(options)?;
587 this.update(&mut cx, |this, cx| {
588 this.as_local_mut()?.on_lsp_did_change_watched_files(
589 server_id, ®.id, options, cx,
590 );
591 Some(())
592 })?;
593 }
594 }
595 "textDocument/rangeFormatting" => {
596 this.update(&mut cx, |this, _| {
597 if let Some(server) = this.language_server_for_id(server_id)
598 {
599 let options = reg
600 .register_options
601 .map(|options| {
602 serde_json::from_value::<
603 lsp::DocumentRangeFormattingOptions,
604 >(
605 options
606 )
607 })
608 .transpose()?;
609 let provider = match options {
610 None => OneOf::Left(true),
611 Some(options) => OneOf::Right(options),
612 };
613 server.update_capabilities(|capabilities| {
614 capabilities.document_range_formatting_provider =
615 Some(provider);
616 })
617 }
618 anyhow::Ok(())
619 })??;
620 }
621 "textDocument/onTypeFormatting" => {
622 this.update(&mut cx, |this, _| {
623 if let Some(server) = this.language_server_for_id(server_id)
624 {
625 let options = reg
626 .register_options
627 .map(|options| {
628 serde_json::from_value::<
629 lsp::DocumentOnTypeFormattingOptions,
630 >(
631 options
632 )
633 })
634 .transpose()?;
635 if let Some(options) = options {
636 server.update_capabilities(|capabilities| {
637 capabilities
638 .document_on_type_formatting_provider =
639 Some(options);
640 })
641 }
642 }
643 anyhow::Ok(())
644 })??;
645 }
646 "textDocument/formatting" => {
647 this.update(&mut cx, |this, _| {
648 if let Some(server) = this.language_server_for_id(server_id)
649 {
650 let options = reg
651 .register_options
652 .map(|options| {
653 serde_json::from_value::<
654 lsp::DocumentFormattingOptions,
655 >(
656 options
657 )
658 })
659 .transpose()?;
660 let provider = match options {
661 None => OneOf::Left(true),
662 Some(options) => OneOf::Right(options),
663 };
664 server.update_capabilities(|capabilities| {
665 capabilities.document_formatting_provider =
666 Some(provider);
667 })
668 }
669 anyhow::Ok(())
670 })??;
671 }
672 "workspace/didChangeConfiguration" => {
673 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
674 }
675 "textDocument/rename" => {
676 this.update(&mut cx, |this, _| {
677 if let Some(server) = this.language_server_for_id(server_id)
678 {
679 let options = reg
680 .register_options
681 .map(|options| {
682 serde_json::from_value::<lsp::RenameOptions>(
683 options,
684 )
685 })
686 .transpose()?;
687 let options = match options {
688 None => OneOf::Left(true),
689 Some(options) => OneOf::Right(options),
690 };
691
692 server.update_capabilities(|capabilities| {
693 capabilities.rename_provider = Some(options);
694 })
695 }
696 anyhow::Ok(())
697 })??;
698 }
699 _ => log::warn!("unhandled capability registration: {reg:?}"),
700 }
701 }
702 Ok(())
703 }
704 }
705 })
706 .detach();
707
708 language_server
709 .on_request::<lsp::request::UnregisterCapability, _, _>({
710 let this = this.clone();
711 move |params, cx| {
712 let this = this.clone();
713 let mut cx = cx.clone();
714 async move {
715 for unreg in params.unregisterations.iter() {
716 match unreg.method.as_str() {
717 "workspace/didChangeWatchedFiles" => {
718 this.update(&mut cx, |this, cx| {
719 this.as_local_mut()?
720 .on_lsp_unregister_did_change_watched_files(
721 server_id, &unreg.id, cx,
722 );
723 Some(())
724 })?;
725 }
726 "workspace/didChangeConfiguration" => {
727 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
728 }
729 "textDocument/rename" => {
730 this.update(&mut cx, |this, _| {
731 if let Some(server) = this.language_server_for_id(server_id)
732 {
733 server.update_capabilities(|capabilities| {
734 capabilities.rename_provider = None
735 })
736 }
737 })?;
738 }
739 "textDocument/rangeFormatting" => {
740 this.update(&mut cx, |this, _| {
741 if let Some(server) = this.language_server_for_id(server_id)
742 {
743 server.update_capabilities(|capabilities| {
744 capabilities.document_range_formatting_provider =
745 None
746 })
747 }
748 })?;
749 }
750 "textDocument/onTypeFormatting" => {
751 this.update(&mut cx, |this, _| {
752 if let Some(server) = this.language_server_for_id(server_id)
753 {
754 server.update_capabilities(|capabilities| {
755 capabilities.document_on_type_formatting_provider =
756 None;
757 })
758 }
759 })?;
760 }
761 "textDocument/formatting" => {
762 this.update(&mut cx, |this, _| {
763 if let Some(server) = this.language_server_for_id(server_id)
764 {
765 server.update_capabilities(|capabilities| {
766 capabilities.document_formatting_provider = None;
767 })
768 }
769 })?;
770 }
771 _ => log::warn!("unhandled capability unregistration: {unreg:?}"),
772 }
773 }
774 Ok(())
775 }
776 }
777 })
778 .detach();
779
780 language_server
781 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
782 let adapter = adapter.clone();
783 let this = this.clone();
784 move |params, cx| {
785 let mut cx = cx.clone();
786 let this = this.clone();
787 let adapter = adapter.clone();
788 async move {
789 LocalLspStore::on_lsp_workspace_edit(
790 this.clone(),
791 params,
792 server_id,
793 adapter.clone(),
794 &mut cx,
795 )
796 .await
797 }
798 }
799 })
800 .detach();
801
802 language_server
803 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
804 let this = this.clone();
805 move |(), cx| {
806 let this = this.clone();
807 let mut cx = cx.clone();
808 async move {
809 this.update(&mut cx, |this, cx| {
810 cx.emit(LspStoreEvent::RefreshInlayHints);
811 this.downstream_client.as_ref().map(|(client, project_id)| {
812 client.send(proto::RefreshInlayHints {
813 project_id: *project_id,
814 })
815 })
816 })?
817 .transpose()?;
818 Ok(())
819 }
820 }
821 })
822 .detach();
823
824 language_server
825 .on_request::<lsp::request::CodeLensRefresh, _, _>({
826 let this = this.clone();
827 move |(), cx| {
828 let this = this.clone();
829 let mut cx = cx.clone();
830 async move {
831 this.update(&mut cx, |this, cx| {
832 cx.emit(LspStoreEvent::RefreshCodeLens);
833 this.downstream_client.as_ref().map(|(client, project_id)| {
834 client.send(proto::RefreshCodeLens {
835 project_id: *project_id,
836 })
837 })
838 })?
839 .transpose()?;
840 Ok(())
841 }
842 }
843 })
844 .detach();
845
846 language_server
847 .on_request::<lsp::request::ShowMessageRequest, _, _>({
848 let this = this.clone();
849 let name = name.to_string();
850 move |params, cx| {
851 let this = this.clone();
852 let name = name.to_string();
853 let mut cx = cx.clone();
854 async move {
855 let actions = params.actions.unwrap_or_default();
856 let (tx, rx) = smol::channel::bounded(1);
857 let request = LanguageServerPromptRequest {
858 level: match params.typ {
859 lsp::MessageType::ERROR => PromptLevel::Critical,
860 lsp::MessageType::WARNING => PromptLevel::Warning,
861 _ => PromptLevel::Info,
862 },
863 message: params.message,
864 actions,
865 response_channel: tx,
866 lsp_name: name.clone(),
867 };
868
869 let did_update = this
870 .update(&mut cx, |_, cx| {
871 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
872 })
873 .is_ok();
874 if did_update {
875 let response = rx.recv().await.ok();
876 Ok(response)
877 } else {
878 Ok(None)
879 }
880 }
881 }
882 })
883 .detach();
884 language_server
885 .on_notification::<lsp::notification::ShowMessage, _>({
886 let this = this.clone();
887 let name = name.to_string();
888 move |params, cx| {
889 let this = this.clone();
890 let name = name.to_string();
891 let mut cx = cx.clone();
892
893 let (tx, _) = smol::channel::bounded(1);
894 let request = LanguageServerPromptRequest {
895 level: match params.typ {
896 lsp::MessageType::ERROR => PromptLevel::Critical,
897 lsp::MessageType::WARNING => PromptLevel::Warning,
898 _ => PromptLevel::Info,
899 },
900 message: params.message,
901 actions: vec![],
902 response_channel: tx,
903 lsp_name: name.clone(),
904 };
905
906 let _ = this.update(&mut cx, |_, cx| {
907 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
908 });
909 }
910 })
911 .detach();
912
913 let disk_based_diagnostics_progress_token =
914 adapter.disk_based_diagnostics_progress_token.clone();
915
916 language_server
917 .on_notification::<lsp::notification::Progress, _>({
918 let this = this.clone();
919 move |params, cx| {
920 if let Some(this) = this.upgrade() {
921 this.update(cx, |this, cx| {
922 this.on_lsp_progress(
923 params,
924 server_id,
925 disk_based_diagnostics_progress_token.clone(),
926 cx,
927 );
928 })
929 .ok();
930 }
931 }
932 })
933 .detach();
934
935 language_server
936 .on_notification::<lsp::notification::LogMessage, _>({
937 let this = this.clone();
938 move |params, cx| {
939 if let Some(this) = this.upgrade() {
940 this.update(cx, |_, cx| {
941 cx.emit(LspStoreEvent::LanguageServerLog(
942 server_id,
943 LanguageServerLogType::Log(params.typ),
944 params.message,
945 ));
946 })
947 .ok();
948 }
949 }
950 })
951 .detach();
952
953 language_server
954 .on_notification::<lsp::notification::LogTrace, _>({
955 let this = this.clone();
956 move |params, cx| {
957 let mut cx = cx.clone();
958 if let Some(this) = this.upgrade() {
959 this.update(&mut cx, |_, cx| {
960 cx.emit(LspStoreEvent::LanguageServerLog(
961 server_id,
962 LanguageServerLogType::Trace(params.verbose),
963 params.message,
964 ));
965 })
966 .ok();
967 }
968 }
969 })
970 .detach();
971
972 rust_analyzer_ext::register_notifications(this.clone(), language_server);
973 clangd_ext::register_notifications(this, language_server, adapter);
974 }
975
976 fn shutdown_language_servers(
977 &mut self,
978 _cx: &mut Context<LspStore>,
979 ) -> impl Future<Output = ()> + use<> {
980 let shutdown_futures = self
981 .language_servers
982 .drain()
983 .map(|(_, server_state)| async {
984 use LanguageServerState::*;
985 match server_state {
986 Running { server, .. } => server.shutdown()?.await,
987 Starting { startup, .. } => startup.await?.shutdown()?.await,
988 }
989 })
990 .collect::<Vec<_>>();
991
992 async move {
993 futures::future::join_all(shutdown_futures).await;
994 }
995 }
996
997 fn language_servers_for_worktree(
998 &self,
999 worktree_id: WorktreeId,
1000 ) -> impl Iterator<Item = &Arc<LanguageServer>> {
1001 self.language_server_ids
1002 .iter()
1003 .flat_map(move |((language_server_path, _), ids)| {
1004 ids.iter().filter_map(move |id| {
1005 if *language_server_path != worktree_id {
1006 return None;
1007 }
1008 if let Some(LanguageServerState::Running { server, .. }) =
1009 self.language_servers.get(id)
1010 {
1011 return Some(server);
1012 } else {
1013 None
1014 }
1015 })
1016 })
1017 }
1018
1019 fn language_server_ids_for_project_path(
1020 &self,
1021 project_path: ProjectPath,
1022 language: &Language,
1023 cx: &mut App,
1024 ) -> Vec<LanguageServerId> {
1025 let Some(worktree) = self
1026 .worktree_store
1027 .read(cx)
1028 .worktree_for_id(project_path.worktree_id, cx)
1029 else {
1030 return vec![];
1031 };
1032 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
1033 let root = self.lsp_tree.update(cx, |this, cx| {
1034 this.get(
1035 project_path,
1036 AdapterQuery::Language(&language.name()),
1037 delegate,
1038 cx,
1039 )
1040 .filter_map(|node| node.server_id())
1041 .collect::<Vec<_>>()
1042 });
1043
1044 root
1045 }
1046
1047 fn language_server_ids_for_buffer(
1048 &self,
1049 buffer: &Buffer,
1050 cx: &mut App,
1051 ) -> Vec<LanguageServerId> {
1052 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
1053 let worktree_id = file.worktree_id(cx);
1054
1055 let path: Arc<Path> = file
1056 .path()
1057 .parent()
1058 .map(Arc::from)
1059 .unwrap_or_else(|| file.path().clone());
1060 let worktree_path = ProjectPath { worktree_id, path };
1061 self.language_server_ids_for_project_path(worktree_path, language, cx)
1062 } else {
1063 Vec::new()
1064 }
1065 }
1066
1067 fn language_servers_for_buffer<'a>(
1068 &'a self,
1069 buffer: &'a Buffer,
1070 cx: &'a mut App,
1071 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1072 self.language_server_ids_for_buffer(buffer, cx)
1073 .into_iter()
1074 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
1075 LanguageServerState::Running {
1076 adapter, server, ..
1077 } => Some((adapter, server)),
1078 _ => None,
1079 })
1080 }
1081
1082 fn primary_language_server_for_buffer<'a>(
1083 &'a self,
1084 buffer: &'a Buffer,
1085 cx: &'a mut App,
1086 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1087 // The list of language servers is ordered based on the `language_servers` setting
1088 // for each language, thus we can consider the first one in the list to be the
1089 // primary one.
1090 self.language_servers_for_buffer(buffer, cx).next()
1091 }
1092
1093 async fn execute_code_action_kind_locally(
1094 lsp_store: WeakEntity<LspStore>,
1095 mut buffers: Vec<Entity<Buffer>>,
1096 kind: CodeActionKind,
1097 push_to_history: bool,
1098 cx: &mut AsyncApp,
1099 ) -> anyhow::Result<ProjectTransaction> {
1100 // Do not allow multiple concurrent code actions requests for the
1101 // same buffer.
1102 lsp_store.update(cx, |this, cx| {
1103 let this = this.as_local_mut().unwrap();
1104 buffers.retain(|buffer| {
1105 this.buffers_being_formatted
1106 .insert(buffer.read(cx).remote_id())
1107 });
1108 })?;
1109 let _cleanup = defer({
1110 let this = lsp_store.clone();
1111 let mut cx = cx.clone();
1112 let buffers = &buffers;
1113 move || {
1114 this.update(&mut cx, |this, cx| {
1115 let this = this.as_local_mut().unwrap();
1116 for buffer in buffers {
1117 this.buffers_being_formatted
1118 .remove(&buffer.read(cx).remote_id());
1119 }
1120 })
1121 .ok();
1122 }
1123 });
1124 let mut project_transaction = ProjectTransaction::default();
1125
1126 for buffer in &buffers {
1127 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1128 buffer.update(cx, |buffer, cx| {
1129 lsp_store
1130 .as_local()
1131 .unwrap()
1132 .language_servers_for_buffer(buffer, cx)
1133 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1134 .collect::<Vec<_>>()
1135 })
1136 })?;
1137 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
1138 let actions = Self::get_server_code_actions_from_action_kinds(
1139 &lsp_store,
1140 language_server.server_id(),
1141 vec![kind.clone()],
1142 buffer,
1143 cx,
1144 )
1145 .await?;
1146 Self::execute_code_actions_on_server(
1147 &lsp_store,
1148 language_server,
1149 lsp_adapter,
1150 actions,
1151 push_to_history,
1152 &mut project_transaction,
1153 cx,
1154 )
1155 .await?;
1156 }
1157 }
1158 Ok(project_transaction)
1159 }
1160
1161 async fn format_locally(
1162 lsp_store: WeakEntity<LspStore>,
1163 mut buffers: Vec<FormattableBuffer>,
1164 push_to_history: bool,
1165 trigger: FormatTrigger,
1166 logger: zlog::Logger,
1167 cx: &mut AsyncApp,
1168 ) -> anyhow::Result<ProjectTransaction> {
1169 // Do not allow multiple concurrent formatting requests for the
1170 // same buffer.
1171 lsp_store.update(cx, |this, cx| {
1172 let this = this.as_local_mut().unwrap();
1173 buffers.retain(|buffer| {
1174 this.buffers_being_formatted
1175 .insert(buffer.handle.read(cx).remote_id())
1176 });
1177 })?;
1178
1179 let _cleanup = defer({
1180 let this = lsp_store.clone();
1181 let mut cx = cx.clone();
1182 let buffers = &buffers;
1183 move || {
1184 this.update(&mut cx, |this, cx| {
1185 let this = this.as_local_mut().unwrap();
1186 for buffer in buffers {
1187 this.buffers_being_formatted
1188 .remove(&buffer.handle.read(cx).remote_id());
1189 }
1190 })
1191 .ok();
1192 }
1193 });
1194
1195 let mut project_transaction = ProjectTransaction::default();
1196
1197 for buffer in &buffers {
1198 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1199 buffer.handle.update(cx, |buffer, cx| {
1200 lsp_store
1201 .as_local()
1202 .unwrap()
1203 .language_servers_for_buffer(buffer, cx)
1204 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1205 .collect::<Vec<_>>()
1206 })
1207 })?;
1208
1209 let settings = buffer.handle.read_with(cx, |buffer, cx| {
1210 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
1211 .into_owned()
1212 })?;
1213
1214 let mut transaction_id_format = None;
1215
1216 // ensure no transactions created while formatting are
1217 // grouped with the previous transaction in the history
1218 // based on the transaction group interval
1219 buffer.handle.update(cx, |buffer, _| {
1220 buffer.finalize_last_transaction();
1221 })?;
1222
1223 // handle whitespace formatting
1224 {
1225 if settings.remove_trailing_whitespace_on_save {
1226 zlog::trace!(logger => "removing trailing whitespace");
1227 let diff = buffer
1228 .handle
1229 .read_with(cx, |buffer, cx| buffer.remove_trailing_whitespace(cx))?
1230 .await;
1231 buffer.handle.update(cx, |buffer, cx| {
1232 buffer.start_transaction();
1233 buffer.apply_diff(diff, cx);
1234 transaction_id_format =
1235 transaction_id_format.or(buffer.end_transaction(cx));
1236 if let Some(transaction_id) = transaction_id_format {
1237 buffer.group_until_transaction(transaction_id);
1238 }
1239 })?;
1240 }
1241
1242 if settings.ensure_final_newline_on_save {
1243 zlog::trace!(logger => "ensuring final newline");
1244 buffer.handle.update(cx, |buffer, cx| {
1245 buffer.start_transaction();
1246 buffer.ensure_final_newline(cx);
1247 transaction_id_format =
1248 transaction_id_format.or(buffer.end_transaction(cx));
1249 if let Some(transaction_id) = transaction_id_format {
1250 buffer.group_until_transaction(transaction_id);
1251 }
1252 })?;
1253 }
1254 }
1255
1256 // Formatter for `code_actions_on_format` that runs before
1257 // the rest of the formatters
1258 let code_actions_on_format_formatter = 'ca_formatter: {
1259 let should_run_code_actions_on_format = !matches!(
1260 (trigger, &settings.format_on_save),
1261 (FormatTrigger::Save, &FormatOnSave::Off)
1262 );
1263 let have_code_actions_to_run_on_format = settings
1264 .code_actions_on_format
1265 .values()
1266 .any(|enabled| *enabled);
1267
1268 if should_run_code_actions_on_format {
1269 if have_code_actions_to_run_on_format {
1270 zlog::trace!(logger => "going to run code actions on format");
1271 break 'ca_formatter Some(Formatter::CodeActions(
1272 settings.code_actions_on_format.clone(),
1273 ));
1274 }
1275 }
1276 break 'ca_formatter None;
1277 };
1278
1279 let formatters = match (trigger, &settings.format_on_save) {
1280 (FormatTrigger::Save, FormatOnSave::Off) => &[],
1281 (FormatTrigger::Save, FormatOnSave::List(formatters)) => formatters.as_ref(),
1282 (FormatTrigger::Manual, _) | (FormatTrigger::Save, FormatOnSave::On) => {
1283 match &settings.formatter {
1284 SelectedFormatter::Auto => {
1285 if settings.prettier.allowed {
1286 zlog::trace!(logger => "Formatter set to auto: defaulting to prettier");
1287 std::slice::from_ref(&Formatter::Prettier)
1288 } else {
1289 zlog::trace!(logger => "Formatter set to auto: defaulting to primary language server");
1290 std::slice::from_ref(&Formatter::LanguageServer { name: None })
1291 }
1292 }
1293 SelectedFormatter::List(formatter_list) => formatter_list.as_ref(),
1294 }
1295 }
1296 };
1297
1298 let formatters = code_actions_on_format_formatter.iter().chain(formatters);
1299
1300 // helper function to avoid duplicate logic between formatter handlers below
1301 // We want to avoid continuing to format the buffer if it has been edited since the start
1302 // so we check that the last transaction id on the undo stack matches the one we expect
1303 // This check should be done after each "gather" step where we generate a diff or edits to apply,
1304 // and before applying them to the buffer to avoid messing up the user's buffer
1305 fn err_if_buffer_edited_since_start(
1306 buffer: &FormattableBuffer,
1307 transaction_id_format: Option<text::TransactionId>,
1308 cx: &AsyncApp,
1309 ) -> Option<anyhow::Error> {
1310 let transaction_id_last = buffer
1311 .handle
1312 .read_with(cx, |buffer, _| {
1313 buffer.peek_undo_stack().map(|t| t.transaction_id())
1314 })
1315 .ok()
1316 .flatten();
1317 let should_continue_formatting = match (transaction_id_format, transaction_id_last)
1318 {
1319 (Some(format), Some(last)) => format == last,
1320 (Some(_), None) => false,
1321 (_, _) => true,
1322 };
1323 if !should_continue_formatting {
1324 return Some(anyhow::anyhow!("Buffer edited while formatting. Aborting"));
1325 }
1326 return None;
1327 }
1328
1329 // variable used to track errors that occur during the formatting process below,
1330 // but that need to not be returned right away (with `?` for example) because we
1331 // still need to clean up the transaction history and update the project transaction
1332 let mut result = anyhow::Ok(());
1333
1334 'formatters: for formatter in formatters {
1335 match formatter {
1336 Formatter::Prettier => {
1337 let logger = zlog::scoped!(logger => "prettier");
1338 zlog::trace!(logger => "formatting");
1339 let _timer = zlog::time!(logger => "Formatting buffer via prettier");
1340
1341 let prettier = lsp_store.read_with(cx, |lsp_store, _cx| {
1342 lsp_store.prettier_store().unwrap().downgrade()
1343 })?;
1344 let diff_result =
1345 prettier_store::format_with_prettier(&prettier, &buffer.handle, cx)
1346 .await
1347 .transpose();
1348 let Ok(diff) = diff_result else {
1349 result = Err(diff_result.unwrap_err());
1350 zlog::error!(logger => "failed, reason: {:?}", result.as_ref());
1351 break 'formatters;
1352 };
1353 let Some(diff) = diff else {
1354 zlog::trace!(logger => "No changes");
1355 continue 'formatters;
1356 };
1357 if let Some(err) =
1358 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1359 {
1360 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1361 result = Err(err);
1362 break 'formatters;
1363 }
1364 zlog::trace!(logger => "Applying changes");
1365 buffer.handle.update(cx, |buffer, cx| {
1366 buffer.start_transaction();
1367 buffer.apply_diff(diff, cx);
1368 transaction_id_format =
1369 transaction_id_format.or(buffer.end_transaction(cx));
1370 if let Some(transaction_id) = transaction_id_format {
1371 buffer.group_until_transaction(transaction_id);
1372 }
1373 })?;
1374 }
1375 Formatter::External { command, arguments } => {
1376 let logger = zlog::scoped!(logger => "command");
1377 zlog::trace!(logger => "formatting");
1378 let _timer =
1379 zlog::time!(logger => "Formatting buffer via external command");
1380
1381 let diff_result = Self::format_via_external_command(
1382 buffer,
1383 command.as_ref(),
1384 arguments.as_deref(),
1385 cx,
1386 )
1387 .await
1388 .with_context(|| {
1389 format!("Failed to format buffer via external command: {}", command)
1390 });
1391 let Ok(diff) = diff_result else {
1392 result = Err(diff_result.unwrap_err());
1393 zlog::error!(logger => "failed, reason: {:?}", result.as_ref());
1394 break 'formatters;
1395 };
1396 let Some(diff) = diff else {
1397 zlog::trace!(logger => "No changes");
1398 continue 'formatters;
1399 };
1400 if let Some(err) =
1401 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1402 {
1403 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1404 result = Err(err);
1405 break 'formatters;
1406 }
1407 zlog::trace!(logger => "Applying changes");
1408 buffer.handle.update(cx, |buffer, cx| {
1409 buffer.start_transaction();
1410 buffer.apply_diff(diff, cx);
1411 transaction_id_format =
1412 transaction_id_format.or(buffer.end_transaction(cx));
1413 if let Some(transaction_id) = transaction_id_format {
1414 buffer.group_until_transaction(transaction_id);
1415 }
1416 })?;
1417 }
1418 Formatter::LanguageServer { name } => {
1419 let logger = zlog::scoped!(logger => "language-server");
1420 zlog::trace!(logger => "formatting");
1421 let _timer =
1422 zlog::time!(logger => "Formatting buffer using language server");
1423
1424 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1425 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using language servers. Skipping");
1426 continue 'formatters;
1427 };
1428
1429 let language_server = 'language_server: {
1430 // if a name was provided, try to find the server with that name
1431 if let Some(name) = name.as_deref() {
1432 for (adapter, server) in &adapters_and_servers {
1433 if adapter.name.0.as_ref() == name {
1434 break 'language_server server.clone();
1435 }
1436 }
1437 }
1438
1439 // otherwise, fall back to the primary language server for the buffer if one exists
1440 let default_lsp = lsp_store.update(cx, |lsp_store, cx| {
1441 buffer.handle.update(cx, |buffer, cx| {
1442 lsp_store
1443 .as_local()
1444 .unwrap()
1445 .primary_language_server_for_buffer(buffer, cx)
1446 .map(|(_, lsp)| lsp.clone())
1447 })
1448 })?;
1449
1450 if let Some(default_lsp) = default_lsp {
1451 break 'language_server default_lsp;
1452 } else {
1453 log::warn!(
1454 "No language server found to format buffer '{:?}'. Skipping",
1455 buffer_path_abs.as_path().to_string_lossy()
1456 );
1457 continue 'formatters;
1458 }
1459 };
1460
1461 zlog::trace!(
1462 logger =>
1463 "Formatting buffer '{:?}' using language server '{:?}'",
1464 buffer_path_abs.as_path().to_string_lossy(),
1465 language_server.name()
1466 );
1467
1468 let edits_result = if let Some(ranges) = buffer.ranges.as_ref() {
1469 zlog::trace!(logger => "formatting ranges");
1470 Self::format_ranges_via_lsp(
1471 &lsp_store,
1472 &buffer.handle,
1473 ranges,
1474 buffer_path_abs,
1475 &language_server,
1476 &settings,
1477 cx,
1478 )
1479 .await
1480 .context("Failed to format ranges via language server")
1481 } else {
1482 zlog::trace!(logger => "formatting full");
1483 Self::format_via_lsp(
1484 &lsp_store,
1485 &buffer.handle,
1486 buffer_path_abs,
1487 &language_server,
1488 &settings,
1489 cx,
1490 )
1491 .await
1492 .context("failed to format via language server")
1493 };
1494
1495 let Ok(edits) = edits_result else {
1496 result = Err(edits_result.unwrap_err());
1497 zlog::error!(logger => "Failed, reason: {:?}", result.as_ref());
1498 break 'formatters;
1499 };
1500
1501 if edits.is_empty() {
1502 zlog::trace!(logger => "No changes");
1503 continue 'formatters;
1504 }
1505 if let Some(err) =
1506 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1507 {
1508 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1509 result = Err(err);
1510 break 'formatters;
1511 }
1512 zlog::trace!(logger => "Applying changes");
1513 buffer.handle.update(cx, |buffer, cx| {
1514 buffer.start_transaction();
1515 buffer.edit(edits, None, cx);
1516 transaction_id_format =
1517 transaction_id_format.or(buffer.end_transaction(cx));
1518 if let Some(transaction_id) = transaction_id_format {
1519 buffer.group_until_transaction(transaction_id);
1520 }
1521 })?;
1522 }
1523 Formatter::CodeActions(code_actions) => {
1524 let logger = zlog::scoped!(logger => "code-actions");
1525 zlog::trace!(logger => "formatting");
1526 let _timer = zlog::time!(logger => "Formatting buffer using code actions");
1527
1528 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1529 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using code actions. Skipping");
1530 continue 'formatters;
1531 };
1532 let code_action_kinds = code_actions
1533 .iter()
1534 .filter_map(|(action_kind, enabled)| {
1535 enabled.then_some(action_kind.clone().into())
1536 })
1537 .collect::<Vec<_>>();
1538 if code_action_kinds.is_empty() {
1539 zlog::trace!(logger => "No code action kinds enabled, skipping");
1540 continue 'formatters;
1541 }
1542
1543 let mut actions_and_servers = Vec::new();
1544
1545 for (index, (_, language_server)) in adapters_and_servers.iter().enumerate()
1546 {
1547 let actions_result = Self::get_server_code_actions_from_action_kinds(
1548 &lsp_store,
1549 language_server.server_id(),
1550 code_action_kinds.clone(),
1551 &buffer.handle,
1552 cx,
1553 )
1554 .await
1555 .with_context(
1556 || format!("Failed to resolve code actions with kinds {:?} for language server {}",
1557 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1558 language_server.name())
1559 );
1560 let Ok(actions) = actions_result else {
1561 // note: it may be better to set result to the error and break formatters here
1562 // but for now we try to execute the actions that we can resolve and skip the rest
1563 zlog::error!(
1564 logger =>
1565 "Failed to resolve code actions with kinds {:?} with language server {}",
1566 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1567 language_server.name()
1568 );
1569 continue;
1570 };
1571 for action in actions {
1572 actions_and_servers.push((action, index));
1573 }
1574 }
1575
1576 if actions_and_servers.is_empty() {
1577 zlog::trace!(logger => "No code actions were resolved, continuing");
1578 continue 'formatters;
1579 }
1580
1581 'actions: for (mut action, server_index) in actions_and_servers {
1582 let server = &adapters_and_servers[server_index].1;
1583
1584 let describe_code_action = |action: &CodeAction| {
1585 format!(
1586 "code action '{}' with title \"{}\"",
1587 action
1588 .lsp_action
1589 .action_kind()
1590 .unwrap_or("unknown".into())
1591 .as_str(),
1592 action.lsp_action.title()
1593 )
1594 };
1595
1596 zlog::trace!(logger => "Executing {}", describe_code_action(&action));
1597
1598 // NOTE: code below duplicated from `Self::deserialize_workspace_edit`
1599 // but filters out and logs warnings for code actions that cause unreasonably
1600 // difficult handling on our part, such as:
1601 // - applying edits that call commands
1602 // which can result in arbitrary workspace edits being sent from the server that
1603 // have no way of being tied back to the command that initiated them (i.e. we
1604 // can't know which edits are part of the format request, or if the server is done sending
1605 // actions in response to the command)
1606 // - actions that create/delete/modify/rename files other than the one we are formatting
1607 // as we then would need to handle such changes correctly in the local history as well
1608 // as the remote history through the ProjectTransaction
1609 // - actions with snippet edits, as these simply don't make sense in the context of a format request
1610 // Supporting these actions is not impossible, but not supported as of yet.
1611
1612 if let Err(err) =
1613 Self::try_resolve_code_action(server, &mut action).await
1614 {
1615 zlog::error!(
1616 logger =>
1617 "Failed to resolve {}. Error: {}",
1618 describe_code_action(&action),
1619 err
1620 );
1621 continue 'actions;
1622 }
1623 if let Some(_) = action.lsp_action.command() {
1624 zlog::warn!(
1625 logger =>
1626 "Code actions with commands are not supported while formatting. Skipping {}",
1627 describe_code_action(&action),
1628 );
1629 continue 'actions;
1630 }
1631 let Some(edit) = action.lsp_action.edit().cloned() else {
1632 zlog::warn!(
1633 logger =>
1634 "No edit found for while formatting. Skipping {}",
1635 describe_code_action(&action),
1636 );
1637 continue 'actions;
1638 };
1639
1640 if edit.changes.is_none() && edit.document_changes.is_none() {
1641 zlog::trace!(
1642 logger =>
1643 "No changes for code action. Skipping {}",
1644 describe_code_action(&action),
1645 );
1646 continue 'actions;
1647 }
1648
1649 let mut operations = Vec::new();
1650 if let Some(document_changes) = edit.document_changes {
1651 match document_changes {
1652 lsp::DocumentChanges::Edits(edits) => operations.extend(
1653 edits.into_iter().map(lsp::DocumentChangeOperation::Edit),
1654 ),
1655 lsp::DocumentChanges::Operations(ops) => operations = ops,
1656 }
1657 } else if let Some(changes) = edit.changes {
1658 operations.extend(changes.into_iter().map(|(uri, edits)| {
1659 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1660 text_document:
1661 lsp::OptionalVersionedTextDocumentIdentifier {
1662 uri,
1663 version: None,
1664 },
1665 edits: edits.into_iter().map(Edit::Plain).collect(),
1666 })
1667 }));
1668 }
1669
1670 let mut edits = Vec::with_capacity(operations.len());
1671
1672 if operations.is_empty() {
1673 zlog::trace!(
1674 logger =>
1675 "No changes for code action. Skipping {}",
1676 describe_code_action(&action),
1677 );
1678 continue 'actions;
1679 }
1680 for operation in operations {
1681 let op = match operation {
1682 lsp::DocumentChangeOperation::Edit(op) => op,
1683 lsp::DocumentChangeOperation::Op(_) => {
1684 zlog::warn!(
1685 logger =>
1686 "Code actions which create, delete, or rename files are not supported on format. Skipping {}",
1687 describe_code_action(&action),
1688 );
1689 continue 'actions;
1690 }
1691 };
1692 let Ok(file_path) = op.text_document.uri.to_file_path() else {
1693 zlog::warn!(
1694 logger =>
1695 "Failed to convert URI '{:?}' to file path. Skipping {}",
1696 &op.text_document.uri,
1697 describe_code_action(&action),
1698 );
1699 continue 'actions;
1700 };
1701 if &file_path != buffer_path_abs {
1702 zlog::warn!(
1703 logger =>
1704 "File path '{:?}' does not match buffer path '{:?}'. Skipping {}",
1705 file_path,
1706 buffer_path_abs,
1707 describe_code_action(&action),
1708 );
1709 continue 'actions;
1710 }
1711
1712 let mut lsp_edits = Vec::new();
1713 for edit in op.edits {
1714 match edit {
1715 Edit::Plain(edit) => {
1716 if !lsp_edits.contains(&edit) {
1717 lsp_edits.push(edit);
1718 }
1719 }
1720 Edit::Annotated(edit) => {
1721 if !lsp_edits.contains(&edit.text_edit) {
1722 lsp_edits.push(edit.text_edit);
1723 }
1724 }
1725 Edit::Snippet(_) => {
1726 zlog::warn!(
1727 logger =>
1728 "Code actions which produce snippet edits are not supported during formatting. Skipping {}",
1729 describe_code_action(&action),
1730 );
1731 continue 'actions;
1732 }
1733 }
1734 }
1735 let edits_result = lsp_store
1736 .update(cx, |lsp_store, cx| {
1737 lsp_store.as_local_mut().unwrap().edits_from_lsp(
1738 &buffer.handle,
1739 lsp_edits,
1740 server.server_id(),
1741 op.text_document.version,
1742 cx,
1743 )
1744 })?
1745 .await;
1746 let Ok(resolved_edits) = edits_result else {
1747 zlog::warn!(
1748 logger =>
1749 "Failed to resolve edits from LSP for buffer {:?} while handling {}",
1750 buffer_path_abs.as_path(),
1751 describe_code_action(&action),
1752 );
1753 continue 'actions;
1754 };
1755 edits.extend(resolved_edits);
1756 }
1757
1758 if edits.is_empty() {
1759 zlog::warn!(logger => "No edits resolved from LSP");
1760 continue 'actions;
1761 }
1762
1763 if let Some(err) =
1764 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1765 {
1766 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1767 result = Err(err);
1768 break 'formatters;
1769 }
1770 zlog::info!(logger => "Applying changes");
1771 buffer.handle.update(cx, |buffer, cx| {
1772 buffer.start_transaction();
1773 buffer.edit(edits, None, cx);
1774 transaction_id_format =
1775 transaction_id_format.or(buffer.end_transaction(cx));
1776 if let Some(transaction_id) = transaction_id_format {
1777 buffer.group_until_transaction(transaction_id);
1778 }
1779 })?;
1780 }
1781 }
1782 }
1783 }
1784
1785 let buffer_handle = buffer.handle.clone();
1786 buffer.handle.update(cx, |buffer, _| {
1787 let Some(transaction_id) = transaction_id_format else {
1788 zlog::trace!(logger => "No formatting transaction id");
1789 return result;
1790 };
1791 let Some(transaction_id_last) =
1792 buffer.peek_undo_stack().map(|t| t.transaction_id())
1793 else {
1794 // unwrapping should work here, how would we get a transaction id
1795 // with no transaction on the undo stack?
1796 // *but* it occasionally panics. Avoiding panics for now...
1797 zlog::warn!(logger => "No transaction present on undo stack, despite having a formatting transaction id?");
1798 return result;
1799 };
1800 if transaction_id_last != transaction_id {
1801 zlog::trace!(logger => "Last transaction on undo stack is not the formatting transaction, skipping finalization & update of project transaction");
1802 return result;
1803 }
1804 let transaction = buffer
1805 .finalize_last_transaction()
1806 .cloned()
1807 .expect("There is a transaction on the undo stack if we were able to peek it");
1808 // debug_assert_eq!(transaction.id, transaction_id);
1809 if !push_to_history {
1810 zlog::trace!(logger => "forgetting format transaction");
1811 buffer.forget_transaction(transaction.id);
1812 }
1813 project_transaction
1814 .0
1815 .insert(buffer_handle.clone(), transaction);
1816 return result;
1817 })??;
1818 }
1819
1820 return Ok(project_transaction);
1821 }
1822
1823 pub async fn format_ranges_via_lsp(
1824 this: &WeakEntity<LspStore>,
1825 buffer_handle: &Entity<Buffer>,
1826 ranges: &[Range<Anchor>],
1827 abs_path: &Path,
1828 language_server: &Arc<LanguageServer>,
1829 settings: &LanguageSettings,
1830 cx: &mut AsyncApp,
1831 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1832 let capabilities = &language_server.capabilities();
1833 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1834 if range_formatting_provider.map_or(false, |provider| provider == &OneOf::Left(false)) {
1835 return Err(anyhow!(
1836 "{} language server does not support range formatting",
1837 language_server.name()
1838 ));
1839 }
1840
1841 let uri = lsp::Url::from_file_path(abs_path)
1842 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
1843 let text_document = lsp::TextDocumentIdentifier::new(uri);
1844
1845 let lsp_edits = {
1846 let mut lsp_ranges = Vec::new();
1847 this.update(cx, |_this, cx| {
1848 // TODO(#22930): In the case of formatting multibuffer selections, this buffer may
1849 // not have been sent to the language server. This seems like a fairly systemic
1850 // issue, though, the resolution probably is not specific to formatting.
1851 //
1852 // TODO: Instead of using current snapshot, should use the latest snapshot sent to
1853 // LSP.
1854 let snapshot = buffer_handle.read(cx).snapshot();
1855 for range in ranges {
1856 lsp_ranges.push(range_to_lsp(range.to_point_utf16(&snapshot))?);
1857 }
1858 anyhow::Ok(())
1859 })??;
1860
1861 let mut edits = None;
1862 for range in lsp_ranges {
1863 if let Some(mut edit) = language_server
1864 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1865 text_document: text_document.clone(),
1866 range,
1867 options: lsp_command::lsp_formatting_options(settings),
1868 work_done_progress_params: Default::default(),
1869 })
1870 .await?
1871 {
1872 edits.get_or_insert_with(Vec::new).append(&mut edit);
1873 }
1874 }
1875 edits
1876 };
1877
1878 if let Some(lsp_edits) = lsp_edits {
1879 this.update(cx, |this, cx| {
1880 this.as_local_mut().unwrap().edits_from_lsp(
1881 &buffer_handle,
1882 lsp_edits,
1883 language_server.server_id(),
1884 None,
1885 cx,
1886 )
1887 })?
1888 .await
1889 } else {
1890 Ok(Vec::with_capacity(0))
1891 }
1892 }
1893
1894 async fn format_via_lsp(
1895 this: &WeakEntity<LspStore>,
1896 buffer: &Entity<Buffer>,
1897 abs_path: &Path,
1898 language_server: &Arc<LanguageServer>,
1899 settings: &LanguageSettings,
1900 cx: &mut AsyncApp,
1901 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1902 let logger = zlog::scoped!("lsp_format");
1903 zlog::info!(logger => "Formatting via LSP");
1904
1905 let uri = lsp::Url::from_file_path(abs_path)
1906 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
1907 let text_document = lsp::TextDocumentIdentifier::new(uri);
1908 let capabilities = &language_server.capabilities();
1909
1910 let formatting_provider = capabilities.document_formatting_provider.as_ref();
1911 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1912
1913 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
1914 let _timer = zlog::time!(logger => "format-full")
1915 .warn_if_gt(std::time::Duration::from_millis(0));
1916 language_server
1917 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
1918 text_document,
1919 options: lsp_command::lsp_formatting_options(settings),
1920 work_done_progress_params: Default::default(),
1921 })
1922 .await?
1923 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
1924 let _timer = zlog::time!(logger => "format-range")
1925 .warn_if_gt(std::time::Duration::from_millis(0));
1926 let buffer_start = lsp::Position::new(0, 0);
1927 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
1928 language_server
1929 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1930 text_document: text_document.clone(),
1931 range: lsp::Range::new(buffer_start, buffer_end),
1932 options: lsp_command::lsp_formatting_options(settings),
1933 work_done_progress_params: Default::default(),
1934 })
1935 .await?
1936 } else {
1937 None
1938 };
1939
1940 if let Some(lsp_edits) = lsp_edits {
1941 this.update(cx, |this, cx| {
1942 this.as_local_mut().unwrap().edits_from_lsp(
1943 buffer,
1944 lsp_edits,
1945 language_server.server_id(),
1946 None,
1947 cx,
1948 )
1949 })?
1950 .await
1951 } else {
1952 Ok(Vec::with_capacity(0))
1953 }
1954 }
1955
1956 async fn format_via_external_command(
1957 buffer: &FormattableBuffer,
1958 command: &str,
1959 arguments: Option<&[String]>,
1960 cx: &mut AsyncApp,
1961 ) -> Result<Option<Diff>> {
1962 let working_dir_path = buffer.handle.update(cx, |buffer, cx| {
1963 let file = File::from_dyn(buffer.file())?;
1964 let worktree = file.worktree.read(cx);
1965 let mut worktree_path = worktree.abs_path().to_path_buf();
1966 if worktree.root_entry()?.is_file() {
1967 worktree_path.pop();
1968 }
1969 Some(worktree_path)
1970 })?;
1971
1972 let mut child = util::command::new_smol_command(command);
1973
1974 if let Some(buffer_env) = buffer.env.as_ref() {
1975 child.envs(buffer_env);
1976 }
1977
1978 if let Some(working_dir_path) = working_dir_path {
1979 child.current_dir(working_dir_path);
1980 }
1981
1982 if let Some(arguments) = arguments {
1983 child.args(arguments.iter().map(|arg| {
1984 if let Some(buffer_abs_path) = buffer.abs_path.as_ref() {
1985 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
1986 } else {
1987 arg.replace("{buffer_path}", "Untitled")
1988 }
1989 }));
1990 }
1991
1992 let mut child = child
1993 .stdin(smol::process::Stdio::piped())
1994 .stdout(smol::process::Stdio::piped())
1995 .stderr(smol::process::Stdio::piped())
1996 .spawn()?;
1997
1998 let stdin = child
1999 .stdin
2000 .as_mut()
2001 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
2002 let text = buffer
2003 .handle
2004 .update(cx, |buffer, _| buffer.as_rope().clone())?;
2005 for chunk in text.chunks() {
2006 stdin.write_all(chunk.as_bytes()).await?;
2007 }
2008 stdin.flush().await?;
2009
2010 let output = child.output().await?;
2011 if !output.status.success() {
2012 return Err(anyhow!(
2013 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
2014 output.status.code(),
2015 String::from_utf8_lossy(&output.stdout),
2016 String::from_utf8_lossy(&output.stderr),
2017 ));
2018 }
2019
2020 let stdout = String::from_utf8(output.stdout)?;
2021 Ok(Some(
2022 buffer
2023 .handle
2024 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
2025 .await,
2026 ))
2027 }
2028
2029 async fn try_resolve_code_action(
2030 lang_server: &LanguageServer,
2031 action: &mut CodeAction,
2032 ) -> anyhow::Result<()> {
2033 match &mut action.lsp_action {
2034 LspAction::Action(lsp_action) => {
2035 if !action.resolved
2036 && GetCodeActions::can_resolve_actions(&lang_server.capabilities())
2037 && lsp_action.data.is_some()
2038 && (lsp_action.command.is_none() || lsp_action.edit.is_none())
2039 {
2040 *lsp_action = Box::new(
2041 lang_server
2042 .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
2043 .await?,
2044 );
2045 }
2046 }
2047 LspAction::CodeLens(lens) => {
2048 if !action.resolved && GetCodeLens::can_resolve_lens(&lang_server.capabilities()) {
2049 *lens = lang_server
2050 .request::<lsp::request::CodeLensResolve>(lens.clone())
2051 .await?;
2052 }
2053 }
2054 LspAction::Command(_) => {}
2055 }
2056
2057 action.resolved = true;
2058 anyhow::Ok(())
2059 }
2060
2061 fn initialize_buffer(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<LspStore>) {
2062 let buffer = buffer_handle.read(cx);
2063
2064 let file = buffer.file().cloned();
2065 let Some(file) = File::from_dyn(file.as_ref()) else {
2066 return;
2067 };
2068 if !file.is_local() {
2069 return;
2070 }
2071
2072 let worktree_id = file.worktree_id(cx);
2073 let language = buffer.language().cloned();
2074
2075 if let Some(diagnostics) = self.diagnostics.get(&worktree_id) {
2076 for (server_id, diagnostics) in
2077 diagnostics.get(file.path()).cloned().unwrap_or_default()
2078 {
2079 self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2080 .log_err();
2081 }
2082 }
2083 let Some(language) = language else {
2084 return;
2085 };
2086 for adapter in self.languages.lsp_adapters(&language.name()) {
2087 let servers = self
2088 .language_server_ids
2089 .get(&(worktree_id, adapter.name.clone()));
2090 if let Some(server_ids) = servers {
2091 for server_id in server_ids {
2092 let server = self
2093 .language_servers
2094 .get(server_id)
2095 .and_then(|server_state| {
2096 if let LanguageServerState::Running { server, .. } = server_state {
2097 Some(server.clone())
2098 } else {
2099 None
2100 }
2101 });
2102 let server = match server {
2103 Some(server) => server,
2104 None => continue,
2105 };
2106
2107 buffer_handle.update(cx, |buffer, cx| {
2108 buffer.set_completion_triggers(
2109 server.server_id(),
2110 server
2111 .capabilities()
2112 .completion_provider
2113 .as_ref()
2114 .and_then(|provider| {
2115 provider
2116 .trigger_characters
2117 .as_ref()
2118 .map(|characters| characters.iter().cloned().collect())
2119 })
2120 .unwrap_or_default(),
2121 cx,
2122 );
2123 });
2124 }
2125 }
2126 }
2127 }
2128
2129 pub(crate) fn reset_buffer(&mut self, buffer: &Entity<Buffer>, old_file: &File, cx: &mut App) {
2130 buffer.update(cx, |buffer, cx| {
2131 let Some(language) = buffer.language() else {
2132 return;
2133 };
2134 let path = ProjectPath {
2135 worktree_id: old_file.worktree_id(cx),
2136 path: old_file.path.clone(),
2137 };
2138 for server_id in self.language_server_ids_for_project_path(path, language, cx) {
2139 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
2140 buffer.set_completion_triggers(server_id, Default::default(), cx);
2141 }
2142 });
2143 }
2144
2145 fn update_buffer_diagnostics(
2146 &mut self,
2147 buffer: &Entity<Buffer>,
2148 server_id: LanguageServerId,
2149 version: Option<i32>,
2150 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2151 cx: &mut Context<LspStore>,
2152 ) -> Result<()> {
2153 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2154 Ordering::Equal
2155 .then_with(|| b.is_primary.cmp(&a.is_primary))
2156 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2157 .then_with(|| a.severity.cmp(&b.severity))
2158 .then_with(|| a.message.cmp(&b.message))
2159 }
2160
2161 diagnostics.sort_unstable_by(|a, b| {
2162 Ordering::Equal
2163 .then_with(|| a.range.start.cmp(&b.range.start))
2164 .then_with(|| b.range.end.cmp(&a.range.end))
2165 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2166 });
2167
2168 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
2169
2170 let edits_since_save = std::cell::LazyCell::new(|| {
2171 let saved_version = buffer.read(cx).saved_version();
2172 Patch::new(snapshot.edits_since::<PointUtf16>(saved_version).collect())
2173 });
2174
2175 let mut sanitized_diagnostics = Vec::with_capacity(diagnostics.len());
2176
2177 for entry in diagnostics {
2178 let start;
2179 let end;
2180 if entry.diagnostic.is_disk_based {
2181 // Some diagnostics are based on files on disk instead of buffers'
2182 // current contents. Adjust these diagnostics' ranges to reflect
2183 // any unsaved edits.
2184 start = Unclipped((*edits_since_save).old_to_new(entry.range.start.0));
2185 end = Unclipped((*edits_since_save).old_to_new(entry.range.end.0));
2186 } else {
2187 start = entry.range.start;
2188 end = entry.range.end;
2189 }
2190
2191 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2192 ..snapshot.clip_point_utf16(end, Bias::Right);
2193
2194 // Expand empty ranges by one codepoint
2195 if range.start == range.end {
2196 // This will be go to the next boundary when being clipped
2197 range.end.column += 1;
2198 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2199 if range.start == range.end && range.end.column > 0 {
2200 range.start.column -= 1;
2201 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
2202 }
2203 }
2204
2205 sanitized_diagnostics.push(DiagnosticEntry {
2206 range,
2207 diagnostic: entry.diagnostic,
2208 });
2209 }
2210 drop(edits_since_save);
2211
2212 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2213 buffer.update(cx, |buffer, cx| {
2214 buffer.update_diagnostics(server_id, set, cx)
2215 });
2216 Ok(())
2217 }
2218
2219 fn register_buffer_with_language_servers(
2220 &mut self,
2221 buffer_handle: &Entity<Buffer>,
2222 cx: &mut Context<LspStore>,
2223 ) {
2224 let buffer = buffer_handle.read(cx);
2225 let buffer_id = buffer.remote_id();
2226
2227 let Some(file) = File::from_dyn(buffer.file()) else {
2228 return;
2229 };
2230 if !file.is_local() {
2231 return;
2232 }
2233
2234 let abs_path = file.abs_path(cx);
2235 let Some(uri) = lsp::Url::from_file_path(&abs_path).log_err() else {
2236 return;
2237 };
2238 let initial_snapshot = buffer.text_snapshot();
2239 let worktree_id = file.worktree_id(cx);
2240
2241 let Some(language) = buffer.language().cloned() else {
2242 return;
2243 };
2244 let path: Arc<Path> = file
2245 .path()
2246 .parent()
2247 .map(Arc::from)
2248 .unwrap_or_else(|| file.path().clone());
2249 let Some(worktree) = self
2250 .worktree_store
2251 .read(cx)
2252 .worktree_for_id(worktree_id, cx)
2253 else {
2254 return;
2255 };
2256 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
2257 let servers = self.lsp_tree.clone().update(cx, |this, cx| {
2258 this.get(
2259 ProjectPath { worktree_id, path },
2260 AdapterQuery::Language(&language.name()),
2261 delegate.clone(),
2262 cx,
2263 )
2264 .collect::<Vec<_>>()
2265 });
2266 let servers = servers
2267 .into_iter()
2268 .filter_map(|server_node| {
2269 let server_id = server_node.server_id_or_init(
2270 |LaunchDisposition {
2271 server_name,
2272 attach,
2273 path,
2274 settings,
2275 }| match attach {
2276 language::Attach::InstancePerRoot => {
2277 // todo: handle instance per root proper.
2278 if let Some(server_ids) = self
2279 .language_server_ids
2280 .get(&(worktree_id, server_name.clone()))
2281 {
2282 server_ids.iter().cloned().next().unwrap()
2283 } else {
2284 let language_name = language.name();
2285
2286 self.start_language_server(
2287 &worktree,
2288 delegate.clone(),
2289 self.languages
2290 .lsp_adapters(&language_name)
2291 .into_iter()
2292 .find(|adapter| &adapter.name() == server_name)
2293 .expect("To find LSP adapter"),
2294 settings,
2295 cx,
2296 )
2297 }
2298 }
2299 language::Attach::Shared => {
2300 let uri = Url::from_file_path(
2301 worktree.read(cx).abs_path().join(&path.path),
2302 );
2303 let key = (worktree_id, server_name.clone());
2304 if !self.language_server_ids.contains_key(&key) {
2305 let language_name = language.name();
2306 self.start_language_server(
2307 &worktree,
2308 delegate.clone(),
2309 self.languages
2310 .lsp_adapters(&language_name)
2311 .into_iter()
2312 .find(|adapter| &adapter.name() == server_name)
2313 .expect("To find LSP adapter"),
2314 settings,
2315 cx,
2316 );
2317 }
2318 if let Some(server_ids) = self
2319 .language_server_ids
2320 .get(&key)
2321 {
2322 debug_assert_eq!(server_ids.len(), 1);
2323 let server_id = server_ids.iter().cloned().next().unwrap();
2324
2325 if let Some(state) = self.language_servers.get(&server_id) {
2326 if let Ok(uri) = uri {
2327 state.add_workspace_folder(uri);
2328 };
2329 }
2330 server_id
2331 } else {
2332 unreachable!("Language server ID should be available, as it's registered on demand")
2333 }
2334 }
2335 },
2336 )?;
2337 let server_state = self.language_servers.get(&server_id)?;
2338 if let LanguageServerState::Running { server, .. } = server_state {
2339 Some(server.clone())
2340 } else {
2341 None
2342 }
2343 })
2344 .collect::<Vec<_>>();
2345 for server in servers {
2346 buffer_handle.update(cx, |buffer, cx| {
2347 buffer.set_completion_triggers(
2348 server.server_id(),
2349 server
2350 .capabilities()
2351 .completion_provider
2352 .as_ref()
2353 .and_then(|provider| {
2354 provider
2355 .trigger_characters
2356 .as_ref()
2357 .map(|characters| characters.iter().cloned().collect())
2358 })
2359 .unwrap_or_default(),
2360 cx,
2361 );
2362 });
2363 }
2364 for adapter in self.languages.lsp_adapters(&language.name()) {
2365 let servers = self
2366 .language_server_ids
2367 .get(&(worktree_id, adapter.name.clone()))
2368 .map(|ids| {
2369 ids.iter().flat_map(|id| {
2370 self.language_servers.get(id).and_then(|server_state| {
2371 if let LanguageServerState::Running { server, .. } = server_state {
2372 Some(server.clone())
2373 } else {
2374 None
2375 }
2376 })
2377 })
2378 });
2379 let servers = match servers {
2380 Some(server) => server,
2381 None => continue,
2382 };
2383
2384 for server in servers {
2385 let snapshot = LspBufferSnapshot {
2386 version: 0,
2387 snapshot: initial_snapshot.clone(),
2388 };
2389 self.buffer_snapshots
2390 .entry(buffer_id)
2391 .or_default()
2392 .entry(server.server_id())
2393 .or_insert_with(|| {
2394 server.register_buffer(
2395 uri.clone(),
2396 adapter.language_id(&language.name()),
2397 0,
2398 initial_snapshot.text(),
2399 );
2400
2401 vec![snapshot]
2402 });
2403 }
2404 }
2405 }
2406
2407 pub(crate) fn unregister_old_buffer_from_language_servers(
2408 &mut self,
2409 buffer: &Entity<Buffer>,
2410 old_file: &File,
2411 cx: &mut App,
2412 ) {
2413 let old_path = match old_file.as_local() {
2414 Some(local) => local.abs_path(cx),
2415 None => return,
2416 };
2417
2418 let Ok(file_url) = lsp::Url::from_file_path(old_path.as_path()) else {
2419 debug_panic!(
2420 "`{}` is not parseable as an URI",
2421 old_path.to_string_lossy()
2422 );
2423 return;
2424 };
2425 self.unregister_buffer_from_language_servers(buffer, &file_url, cx);
2426 }
2427
2428 pub(crate) fn unregister_buffer_from_language_servers(
2429 &mut self,
2430 buffer: &Entity<Buffer>,
2431 file_url: &lsp::Url,
2432 cx: &mut App,
2433 ) {
2434 buffer.update(cx, |buffer, cx| {
2435 let _ = self.buffer_snapshots.remove(&buffer.remote_id());
2436
2437 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2438 language_server.unregister_buffer(file_url.clone());
2439 }
2440 });
2441 }
2442
2443 fn buffer_snapshot_for_lsp_version(
2444 &mut self,
2445 buffer: &Entity<Buffer>,
2446 server_id: LanguageServerId,
2447 version: Option<i32>,
2448 cx: &App,
2449 ) -> Result<TextBufferSnapshot> {
2450 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
2451
2452 if let Some(version) = version {
2453 let buffer_id = buffer.read(cx).remote_id();
2454 let snapshots = if let Some(snapshots) = self
2455 .buffer_snapshots
2456 .get_mut(&buffer_id)
2457 .and_then(|m| m.get_mut(&server_id))
2458 {
2459 snapshots
2460 } else if version == 0 {
2461 // Some language servers report version 0 even if the buffer hasn't been opened yet.
2462 // We detect this case and treat it as if the version was `None`.
2463 return Ok(buffer.read(cx).text_snapshot());
2464 } else {
2465 return Err(anyhow!(
2466 "no snapshots found for buffer {buffer_id} and server {server_id}"
2467 ));
2468 };
2469
2470 let found_snapshot = snapshots
2471 .binary_search_by_key(&version, |e| e.version)
2472 .map(|ix| snapshots[ix].snapshot.clone())
2473 .map_err(|_| {
2474 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
2475 })?;
2476
2477 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
2478 Ok(found_snapshot)
2479 } else {
2480 Ok((buffer.read(cx)).text_snapshot())
2481 }
2482 }
2483
2484 async fn get_server_code_actions_from_action_kinds(
2485 lsp_store: &WeakEntity<LspStore>,
2486 language_server_id: LanguageServerId,
2487 code_action_kinds: Vec<lsp::CodeActionKind>,
2488 buffer: &Entity<Buffer>,
2489 cx: &mut AsyncApp,
2490 ) -> Result<Vec<CodeAction>> {
2491 let actions = lsp_store
2492 .update(cx, move |this, cx| {
2493 let request = GetCodeActions {
2494 range: text::Anchor::MIN..text::Anchor::MAX,
2495 kinds: Some(code_action_kinds),
2496 };
2497 let server = LanguageServerToQuery::Other(language_server_id);
2498 this.request_lsp(buffer.clone(), server, request, cx)
2499 })?
2500 .await?;
2501 return Ok(actions);
2502 }
2503
2504 pub async fn execute_code_actions_on_server(
2505 lsp_store: &WeakEntity<LspStore>,
2506 language_server: &Arc<LanguageServer>,
2507 lsp_adapter: &Arc<CachedLspAdapter>,
2508 actions: Vec<CodeAction>,
2509 push_to_history: bool,
2510 project_transaction: &mut ProjectTransaction,
2511 cx: &mut AsyncApp,
2512 ) -> Result<(), anyhow::Error> {
2513 for mut action in actions {
2514 Self::try_resolve_code_action(language_server, &mut action)
2515 .await
2516 .context("resolving a formatting code action")?;
2517
2518 if let Some(edit) = action.lsp_action.edit() {
2519 if edit.changes.is_none() && edit.document_changes.is_none() {
2520 continue;
2521 }
2522
2523 let new = Self::deserialize_workspace_edit(
2524 lsp_store.upgrade().context("project dropped")?,
2525 edit.clone(),
2526 push_to_history,
2527 lsp_adapter.clone(),
2528 language_server.clone(),
2529 cx,
2530 )
2531 .await?;
2532 project_transaction.0.extend(new.0);
2533 }
2534
2535 if let Some(command) = action.lsp_action.command() {
2536 let server_capabilities = language_server.capabilities();
2537 let available_commands = server_capabilities
2538 .execute_command_provider
2539 .as_ref()
2540 .map(|options| options.commands.as_slice())
2541 .unwrap_or_default();
2542 if available_commands.contains(&command.command) {
2543 lsp_store.update(cx, |lsp_store, _| {
2544 if let LspStoreMode::Local(mode) = &mut lsp_store.mode {
2545 mode.last_workspace_edits_by_language_server
2546 .remove(&language_server.server_id());
2547 }
2548 })?;
2549
2550 language_server
2551 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
2552 command: command.command.clone(),
2553 arguments: command.arguments.clone().unwrap_or_default(),
2554 ..Default::default()
2555 })
2556 .await?;
2557
2558 lsp_store.update(cx, |this, _| {
2559 if let LspStoreMode::Local(mode) = &mut this.mode {
2560 project_transaction.0.extend(
2561 mode.last_workspace_edits_by_language_server
2562 .remove(&language_server.server_id())
2563 .unwrap_or_default()
2564 .0,
2565 )
2566 }
2567 })?;
2568 } else {
2569 log::warn!(
2570 "Cannot execute a command {} not listed in the language server capabilities",
2571 command.command
2572 )
2573 }
2574 }
2575 }
2576 return Ok(());
2577 }
2578
2579 pub async fn deserialize_text_edits(
2580 this: Entity<LspStore>,
2581 buffer_to_edit: Entity<Buffer>,
2582 edits: Vec<lsp::TextEdit>,
2583 push_to_history: bool,
2584 _: Arc<CachedLspAdapter>,
2585 language_server: Arc<LanguageServer>,
2586 cx: &mut AsyncApp,
2587 ) -> Result<Option<Transaction>> {
2588 let edits = this
2589 .update(cx, |this, cx| {
2590 this.as_local_mut().unwrap().edits_from_lsp(
2591 &buffer_to_edit,
2592 edits,
2593 language_server.server_id(),
2594 None,
2595 cx,
2596 )
2597 })?
2598 .await?;
2599
2600 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2601 buffer.finalize_last_transaction();
2602 buffer.start_transaction();
2603 for (range, text) in edits {
2604 buffer.edit([(range, text)], None, cx);
2605 }
2606
2607 if buffer.end_transaction(cx).is_some() {
2608 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2609 if !push_to_history {
2610 buffer.forget_transaction(transaction.id);
2611 }
2612 Some(transaction)
2613 } else {
2614 None
2615 }
2616 })?;
2617
2618 Ok(transaction)
2619 }
2620
2621 #[allow(clippy::type_complexity)]
2622 pub(crate) fn edits_from_lsp(
2623 &mut self,
2624 buffer: &Entity<Buffer>,
2625 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
2626 server_id: LanguageServerId,
2627 version: Option<i32>,
2628 cx: &mut Context<LspStore>,
2629 ) -> Task<Result<Vec<(Range<Anchor>, Arc<str>)>>> {
2630 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
2631 cx.background_spawn(async move {
2632 let snapshot = snapshot?;
2633 let mut lsp_edits = lsp_edits
2634 .into_iter()
2635 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
2636 .collect::<Vec<_>>();
2637
2638 lsp_edits.sort_by_key(|(range, _)| (range.start, range.end));
2639
2640 let mut lsp_edits = lsp_edits.into_iter().peekable();
2641 let mut edits = Vec::new();
2642 while let Some((range, mut new_text)) = lsp_edits.next() {
2643 // Clip invalid ranges provided by the language server.
2644 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
2645 ..snapshot.clip_point_utf16(range.end, Bias::Left);
2646
2647 // Combine any LSP edits that are adjacent.
2648 //
2649 // Also, combine LSP edits that are separated from each other by only
2650 // a newline. This is important because for some code actions,
2651 // Rust-analyzer rewrites the entire buffer via a series of edits that
2652 // are separated by unchanged newline characters.
2653 //
2654 // In order for the diffing logic below to work properly, any edits that
2655 // cancel each other out must be combined into one.
2656 while let Some((next_range, next_text)) = lsp_edits.peek() {
2657 if next_range.start.0 > range.end {
2658 if next_range.start.0.row > range.end.row + 1
2659 || next_range.start.0.column > 0
2660 || snapshot.clip_point_utf16(
2661 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
2662 Bias::Left,
2663 ) > range.end
2664 {
2665 break;
2666 }
2667 new_text.push('\n');
2668 }
2669 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
2670 new_text.push_str(next_text);
2671 lsp_edits.next();
2672 }
2673
2674 // For multiline edits, perform a diff of the old and new text so that
2675 // we can identify the changes more precisely, preserving the locations
2676 // of any anchors positioned in the unchanged regions.
2677 if range.end.row > range.start.row {
2678 let offset = range.start.to_offset(&snapshot);
2679 let old_text = snapshot.text_for_range(range).collect::<String>();
2680 let range_edits = language::text_diff(old_text.as_str(), &new_text);
2681 edits.extend(range_edits.into_iter().map(|(range, replacement)| {
2682 (
2683 snapshot.anchor_after(offset + range.start)
2684 ..snapshot.anchor_before(offset + range.end),
2685 replacement,
2686 )
2687 }));
2688 } else if range.end == range.start {
2689 let anchor = snapshot.anchor_after(range.start);
2690 edits.push((anchor..anchor, new_text.into()));
2691 } else {
2692 let edit_start = snapshot.anchor_after(range.start);
2693 let edit_end = snapshot.anchor_before(range.end);
2694 edits.push((edit_start..edit_end, new_text.into()));
2695 }
2696 }
2697
2698 Ok(edits)
2699 })
2700 }
2701
2702 pub(crate) async fn deserialize_workspace_edit(
2703 this: Entity<LspStore>,
2704 edit: lsp::WorkspaceEdit,
2705 push_to_history: bool,
2706 lsp_adapter: Arc<CachedLspAdapter>,
2707 language_server: Arc<LanguageServer>,
2708 cx: &mut AsyncApp,
2709 ) -> Result<ProjectTransaction> {
2710 let fs = this.read_with(cx, |this, _| this.as_local().unwrap().fs.clone())?;
2711
2712 let mut operations = Vec::new();
2713 if let Some(document_changes) = edit.document_changes {
2714 match document_changes {
2715 lsp::DocumentChanges::Edits(edits) => {
2716 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2717 }
2718 lsp::DocumentChanges::Operations(ops) => operations = ops,
2719 }
2720 } else if let Some(changes) = edit.changes {
2721 operations.extend(changes.into_iter().map(|(uri, edits)| {
2722 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2723 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2724 uri,
2725 version: None,
2726 },
2727 edits: edits.into_iter().map(Edit::Plain).collect(),
2728 })
2729 }));
2730 }
2731
2732 let mut project_transaction = ProjectTransaction::default();
2733 for operation in operations {
2734 match operation {
2735 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2736 let abs_path = op
2737 .uri
2738 .to_file_path()
2739 .map_err(|_| anyhow!("can't convert URI to path"))?;
2740
2741 if let Some(parent_path) = abs_path.parent() {
2742 fs.create_dir(parent_path).await?;
2743 }
2744 if abs_path.ends_with("/") {
2745 fs.create_dir(&abs_path).await?;
2746 } else {
2747 fs.create_file(
2748 &abs_path,
2749 op.options
2750 .map(|options| fs::CreateOptions {
2751 overwrite: options.overwrite.unwrap_or(false),
2752 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2753 })
2754 .unwrap_or_default(),
2755 )
2756 .await?;
2757 }
2758 }
2759
2760 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2761 let source_abs_path = op
2762 .old_uri
2763 .to_file_path()
2764 .map_err(|_| anyhow!("can't convert URI to path"))?;
2765 let target_abs_path = op
2766 .new_uri
2767 .to_file_path()
2768 .map_err(|_| anyhow!("can't convert URI to path"))?;
2769 fs.rename(
2770 &source_abs_path,
2771 &target_abs_path,
2772 op.options
2773 .map(|options| fs::RenameOptions {
2774 overwrite: options.overwrite.unwrap_or(false),
2775 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2776 })
2777 .unwrap_or_default(),
2778 )
2779 .await?;
2780 }
2781
2782 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2783 let abs_path = op
2784 .uri
2785 .to_file_path()
2786 .map_err(|_| anyhow!("can't convert URI to path"))?;
2787 let options = op
2788 .options
2789 .map(|options| fs::RemoveOptions {
2790 recursive: options.recursive.unwrap_or(false),
2791 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2792 })
2793 .unwrap_or_default();
2794 if abs_path.ends_with("/") {
2795 fs.remove_dir(&abs_path, options).await?;
2796 } else {
2797 fs.remove_file(&abs_path, options).await?;
2798 }
2799 }
2800
2801 lsp::DocumentChangeOperation::Edit(op) => {
2802 let buffer_to_edit = this
2803 .update(cx, |this, cx| {
2804 this.open_local_buffer_via_lsp(
2805 op.text_document.uri.clone(),
2806 language_server.server_id(),
2807 lsp_adapter.name.clone(),
2808 cx,
2809 )
2810 })?
2811 .await?;
2812
2813 let edits = this
2814 .update(cx, |this, cx| {
2815 let path = buffer_to_edit.read(cx).project_path(cx);
2816 let active_entry = this.active_entry;
2817 let is_active_entry = path.clone().map_or(false, |project_path| {
2818 this.worktree_store
2819 .read(cx)
2820 .entry_for_path(&project_path, cx)
2821 .map_or(false, |entry| Some(entry.id) == active_entry)
2822 });
2823 let local = this.as_local_mut().unwrap();
2824
2825 let (mut edits, mut snippet_edits) = (vec![], vec![]);
2826 for edit in op.edits {
2827 match edit {
2828 Edit::Plain(edit) => {
2829 if !edits.contains(&edit) {
2830 edits.push(edit)
2831 }
2832 }
2833 Edit::Annotated(edit) => {
2834 if !edits.contains(&edit.text_edit) {
2835 edits.push(edit.text_edit)
2836 }
2837 }
2838 Edit::Snippet(edit) => {
2839 let Ok(snippet) = Snippet::parse(&edit.snippet.value)
2840 else {
2841 continue;
2842 };
2843
2844 if is_active_entry {
2845 snippet_edits.push((edit.range, snippet));
2846 } else {
2847 // Since this buffer is not focused, apply a normal edit.
2848 let new_edit = TextEdit {
2849 range: edit.range,
2850 new_text: snippet.text,
2851 };
2852 if !edits.contains(&new_edit) {
2853 edits.push(new_edit);
2854 }
2855 }
2856 }
2857 }
2858 }
2859 if !snippet_edits.is_empty() {
2860 let buffer_id = buffer_to_edit.read(cx).remote_id();
2861 let version = if let Some(buffer_version) = op.text_document.version
2862 {
2863 local
2864 .buffer_snapshot_for_lsp_version(
2865 &buffer_to_edit,
2866 language_server.server_id(),
2867 Some(buffer_version),
2868 cx,
2869 )
2870 .ok()
2871 .map(|snapshot| snapshot.version)
2872 } else {
2873 Some(buffer_to_edit.read(cx).saved_version().clone())
2874 };
2875
2876 let most_recent_edit = version.and_then(|version| {
2877 version.iter().max_by_key(|timestamp| timestamp.value)
2878 });
2879 // Check if the edit that triggered that edit has been made by this participant.
2880
2881 if let Some(most_recent_edit) = most_recent_edit {
2882 cx.emit(LspStoreEvent::SnippetEdit {
2883 buffer_id,
2884 edits: snippet_edits,
2885 most_recent_edit,
2886 });
2887 }
2888 }
2889
2890 local.edits_from_lsp(
2891 &buffer_to_edit,
2892 edits,
2893 language_server.server_id(),
2894 op.text_document.version,
2895 cx,
2896 )
2897 })?
2898 .await?;
2899
2900 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2901 buffer.finalize_last_transaction();
2902 buffer.start_transaction();
2903 for (range, text) in edits {
2904 buffer.edit([(range, text)], None, cx);
2905 }
2906 let transaction = if buffer.end_transaction(cx).is_some() {
2907 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2908 if !push_to_history {
2909 buffer.forget_transaction(transaction.id);
2910 }
2911 Some(transaction)
2912 } else {
2913 None
2914 };
2915
2916 transaction
2917 })?;
2918 if let Some(transaction) = transaction {
2919 project_transaction.0.insert(buffer_to_edit, transaction);
2920 }
2921 }
2922 }
2923 }
2924
2925 Ok(project_transaction)
2926 }
2927
2928 async fn on_lsp_workspace_edit(
2929 this: WeakEntity<LspStore>,
2930 params: lsp::ApplyWorkspaceEditParams,
2931 server_id: LanguageServerId,
2932 adapter: Arc<CachedLspAdapter>,
2933 cx: &mut AsyncApp,
2934 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2935 let this = this
2936 .upgrade()
2937 .ok_or_else(|| anyhow!("project project closed"))?;
2938 let language_server = this
2939 .update(cx, |this, _| this.language_server_for_id(server_id))?
2940 .ok_or_else(|| anyhow!("language server not found"))?;
2941 let transaction = Self::deserialize_workspace_edit(
2942 this.clone(),
2943 params.edit,
2944 true,
2945 adapter.clone(),
2946 language_server.clone(),
2947 cx,
2948 )
2949 .await
2950 .log_err();
2951 this.update(cx, |this, _| {
2952 if let Some(transaction) = transaction {
2953 this.as_local_mut()
2954 .unwrap()
2955 .last_workspace_edits_by_language_server
2956 .insert(server_id, transaction);
2957 }
2958 })?;
2959 Ok(lsp::ApplyWorkspaceEditResponse {
2960 applied: true,
2961 failed_change: None,
2962 failure_reason: None,
2963 })
2964 }
2965
2966 fn remove_worktree(
2967 &mut self,
2968 id_to_remove: WorktreeId,
2969 cx: &mut Context<LspStore>,
2970 ) -> Vec<LanguageServerId> {
2971 self.diagnostics.remove(&id_to_remove);
2972 self.prettier_store.update(cx, |prettier_store, cx| {
2973 prettier_store.remove_worktree(id_to_remove, cx);
2974 });
2975
2976 let mut servers_to_remove = BTreeMap::default();
2977 let mut servers_to_preserve = HashSet::default();
2978 for ((path, server_name), ref server_ids) in &self.language_server_ids {
2979 if *path == id_to_remove {
2980 servers_to_remove.extend(server_ids.iter().map(|id| (*id, server_name.clone())));
2981 } else {
2982 servers_to_preserve.extend(server_ids.iter().cloned());
2983 }
2984 }
2985 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
2986
2987 for (server_id_to_remove, _) in &servers_to_remove {
2988 self.language_server_ids
2989 .values_mut()
2990 .for_each(|server_ids| {
2991 server_ids.remove(server_id_to_remove);
2992 });
2993 self.language_server_watched_paths
2994 .remove(&server_id_to_remove);
2995 self.language_server_paths_watched_for_rename
2996 .remove(&server_id_to_remove);
2997 self.last_workspace_edits_by_language_server
2998 .remove(&server_id_to_remove);
2999 self.language_servers.remove(&server_id_to_remove);
3000 cx.emit(LspStoreEvent::LanguageServerRemoved(*server_id_to_remove));
3001 }
3002 servers_to_remove.into_keys().collect()
3003 }
3004
3005 fn rebuild_watched_paths_inner<'a>(
3006 &'a self,
3007 language_server_id: LanguageServerId,
3008 watchers: impl Iterator<Item = &'a FileSystemWatcher>,
3009 cx: &mut Context<LspStore>,
3010 ) -> LanguageServerWatchedPathsBuilder {
3011 let worktrees = self
3012 .worktree_store
3013 .read(cx)
3014 .worktrees()
3015 .filter_map(|worktree| {
3016 self.language_servers_for_worktree(worktree.read(cx).id())
3017 .find(|server| server.server_id() == language_server_id)
3018 .map(|_| worktree)
3019 })
3020 .collect::<Vec<_>>();
3021
3022 let mut worktree_globs = HashMap::default();
3023 let mut abs_globs = HashMap::default();
3024 log::trace!(
3025 "Processing new watcher paths for language server with id {}",
3026 language_server_id
3027 );
3028
3029 for watcher in watchers {
3030 if let Some((worktree, literal_prefix, pattern)) =
3031 self.worktree_and_path_for_file_watcher(&worktrees, &watcher, cx)
3032 {
3033 worktree.update(cx, |worktree, _| {
3034 if let Some((tree, glob)) =
3035 worktree.as_local_mut().zip(Glob::new(&pattern).log_err())
3036 {
3037 tree.add_path_prefix_to_scan(literal_prefix.into());
3038 worktree_globs
3039 .entry(tree.id())
3040 .or_insert_with(GlobSetBuilder::new)
3041 .add(glob);
3042 }
3043 });
3044 } else {
3045 let (path, pattern) = match &watcher.glob_pattern {
3046 lsp::GlobPattern::String(s) => {
3047 let watcher_path = SanitizedPath::from(s);
3048 let path = glob_literal_prefix(watcher_path.as_path());
3049 let pattern = watcher_path
3050 .as_path()
3051 .strip_prefix(&path)
3052 .map(|p| p.to_string_lossy().to_string())
3053 .unwrap_or_else(|e| {
3054 debug_panic!(
3055 "Failed to strip prefix for string pattern: {}, with prefix: {}, with error: {}",
3056 s,
3057 path.display(),
3058 e
3059 );
3060 watcher_path.as_path().to_string_lossy().to_string()
3061 });
3062 (path, pattern)
3063 }
3064 lsp::GlobPattern::Relative(rp) => {
3065 let Ok(mut base_uri) = match &rp.base_uri {
3066 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3067 lsp::OneOf::Right(base_uri) => base_uri,
3068 }
3069 .to_file_path() else {
3070 continue;
3071 };
3072
3073 let path = glob_literal_prefix(Path::new(&rp.pattern));
3074 let pattern = Path::new(&rp.pattern)
3075 .strip_prefix(&path)
3076 .map(|p| p.to_string_lossy().to_string())
3077 .unwrap_or_else(|e| {
3078 debug_panic!(
3079 "Failed to strip prefix for relative pattern: {}, with prefix: {}, with error: {}",
3080 rp.pattern,
3081 path.display(),
3082 e
3083 );
3084 rp.pattern.clone()
3085 });
3086 base_uri.push(path);
3087 (base_uri, pattern)
3088 }
3089 };
3090
3091 if let Some(glob) = Glob::new(&pattern).log_err() {
3092 if !path
3093 .components()
3094 .any(|c| matches!(c, path::Component::Normal(_)))
3095 {
3096 // For an unrooted glob like `**/Cargo.toml`, watch it within each worktree,
3097 // rather than adding a new watcher for `/`.
3098 for worktree in &worktrees {
3099 worktree_globs
3100 .entry(worktree.read(cx).id())
3101 .or_insert_with(GlobSetBuilder::new)
3102 .add(glob.clone());
3103 }
3104 } else {
3105 abs_globs
3106 .entry(path.into())
3107 .or_insert_with(GlobSetBuilder::new)
3108 .add(glob);
3109 }
3110 }
3111 }
3112 }
3113
3114 let mut watch_builder = LanguageServerWatchedPathsBuilder::default();
3115 for (worktree_id, builder) in worktree_globs {
3116 if let Ok(globset) = builder.build() {
3117 watch_builder.watch_worktree(worktree_id, globset);
3118 }
3119 }
3120 for (abs_path, builder) in abs_globs {
3121 if let Ok(globset) = builder.build() {
3122 watch_builder.watch_abs_path(abs_path, globset);
3123 }
3124 }
3125 watch_builder
3126 }
3127
3128 fn worktree_and_path_for_file_watcher(
3129 &self,
3130 worktrees: &[Entity<Worktree>],
3131 watcher: &FileSystemWatcher,
3132 cx: &App,
3133 ) -> Option<(Entity<Worktree>, PathBuf, String)> {
3134 worktrees.iter().find_map(|worktree| {
3135 let tree = worktree.read(cx);
3136 let worktree_root_path = tree.abs_path();
3137 match &watcher.glob_pattern {
3138 lsp::GlobPattern::String(s) => {
3139 let watcher_path = SanitizedPath::from(s);
3140 let relative = watcher_path
3141 .as_path()
3142 .strip_prefix(&worktree_root_path)
3143 .ok()?;
3144 let literal_prefix = glob_literal_prefix(relative);
3145 Some((
3146 worktree.clone(),
3147 literal_prefix,
3148 relative.to_string_lossy().to_string(),
3149 ))
3150 }
3151 lsp::GlobPattern::Relative(rp) => {
3152 let base_uri = match &rp.base_uri {
3153 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3154 lsp::OneOf::Right(base_uri) => base_uri,
3155 }
3156 .to_file_path()
3157 .ok()?;
3158 let relative = base_uri.strip_prefix(&worktree_root_path).ok()?;
3159 let mut literal_prefix = relative.to_owned();
3160 literal_prefix.push(glob_literal_prefix(Path::new(&rp.pattern)));
3161 Some((worktree.clone(), literal_prefix, rp.pattern.clone()))
3162 }
3163 }
3164 })
3165 }
3166
3167 fn rebuild_watched_paths(
3168 &mut self,
3169 language_server_id: LanguageServerId,
3170 cx: &mut Context<LspStore>,
3171 ) {
3172 let Some(watchers) = self
3173 .language_server_watcher_registrations
3174 .get(&language_server_id)
3175 else {
3176 return;
3177 };
3178
3179 let watch_builder =
3180 self.rebuild_watched_paths_inner(language_server_id, watchers.values().flatten(), cx);
3181 let watcher = watch_builder.build(self.fs.clone(), language_server_id, cx);
3182 self.language_server_watched_paths
3183 .insert(language_server_id, watcher);
3184
3185 cx.notify();
3186 }
3187
3188 fn on_lsp_did_change_watched_files(
3189 &mut self,
3190 language_server_id: LanguageServerId,
3191 registration_id: &str,
3192 params: DidChangeWatchedFilesRegistrationOptions,
3193 cx: &mut Context<LspStore>,
3194 ) {
3195 let registrations = self
3196 .language_server_watcher_registrations
3197 .entry(language_server_id)
3198 .or_default();
3199
3200 registrations.insert(registration_id.to_string(), params.watchers);
3201
3202 self.rebuild_watched_paths(language_server_id, cx);
3203 }
3204
3205 fn on_lsp_unregister_did_change_watched_files(
3206 &mut self,
3207 language_server_id: LanguageServerId,
3208 registration_id: &str,
3209 cx: &mut Context<LspStore>,
3210 ) {
3211 let registrations = self
3212 .language_server_watcher_registrations
3213 .entry(language_server_id)
3214 .or_default();
3215
3216 if registrations.remove(registration_id).is_some() {
3217 log::info!(
3218 "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
3219 language_server_id,
3220 registration_id
3221 );
3222 } else {
3223 log::warn!(
3224 "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
3225 language_server_id,
3226 registration_id
3227 );
3228 }
3229
3230 self.rebuild_watched_paths(language_server_id, cx);
3231 }
3232
3233 async fn initialization_options_for_adapter(
3234 adapter: Arc<dyn LspAdapter>,
3235 fs: &dyn Fs,
3236 delegate: &Arc<dyn LspAdapterDelegate>,
3237 ) -> Result<Option<serde_json::Value>> {
3238 let Some(mut initialization_config) =
3239 adapter.clone().initialization_options(fs, delegate).await?
3240 else {
3241 return Ok(None);
3242 };
3243
3244 for other_adapter in delegate.registered_lsp_adapters() {
3245 if other_adapter.name() == adapter.name() {
3246 continue;
3247 }
3248 if let Ok(Some(target_config)) = other_adapter
3249 .clone()
3250 .additional_initialization_options(adapter.name(), fs, delegate)
3251 .await
3252 {
3253 merge_json_value_into(target_config.clone(), &mut initialization_config);
3254 }
3255 }
3256
3257 Ok(Some(initialization_config))
3258 }
3259
3260 async fn workspace_configuration_for_adapter(
3261 adapter: Arc<dyn LspAdapter>,
3262 fs: &dyn Fs,
3263 delegate: &Arc<dyn LspAdapterDelegate>,
3264 toolchains: Arc<dyn LanguageToolchainStore>,
3265 cx: &mut AsyncApp,
3266 ) -> Result<serde_json::Value> {
3267 let mut workspace_config = adapter
3268 .clone()
3269 .workspace_configuration(fs, delegate, toolchains.clone(), cx)
3270 .await?;
3271
3272 for other_adapter in delegate.registered_lsp_adapters() {
3273 if other_adapter.name() == adapter.name() {
3274 continue;
3275 }
3276 if let Ok(Some(target_config)) = other_adapter
3277 .clone()
3278 .additional_workspace_configuration(
3279 adapter.name(),
3280 fs,
3281 delegate,
3282 toolchains.clone(),
3283 cx,
3284 )
3285 .await
3286 {
3287 merge_json_value_into(target_config.clone(), &mut workspace_config);
3288 }
3289 }
3290
3291 Ok(workspace_config)
3292 }
3293}
3294
3295#[derive(Debug)]
3296pub struct FormattableBuffer {
3297 handle: Entity<Buffer>,
3298 abs_path: Option<PathBuf>,
3299 env: Option<HashMap<String, String>>,
3300 ranges: Option<Vec<Range<Anchor>>>,
3301}
3302
3303pub struct RemoteLspStore {
3304 upstream_client: Option<AnyProtoClient>,
3305 upstream_project_id: u64,
3306}
3307
3308#[allow(clippy::large_enum_variant)]
3309pub(crate) enum LspStoreMode {
3310 Local(LocalLspStore), // ssh host and collab host
3311 Remote(RemoteLspStore), // collab guest
3312}
3313
3314impl LspStoreMode {
3315 fn is_local(&self) -> bool {
3316 matches!(self, LspStoreMode::Local(_))
3317 }
3318}
3319
3320pub struct LspStore {
3321 mode: LspStoreMode,
3322 last_formatting_failure: Option<String>,
3323 downstream_client: Option<(AnyProtoClient, u64)>,
3324 nonce: u128,
3325 buffer_store: Entity<BufferStore>,
3326 worktree_store: Entity<WorktreeStore>,
3327 toolchain_store: Option<Entity<ToolchainStore>>,
3328 pub languages: Arc<LanguageRegistry>,
3329 pub language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3330 active_entry: Option<ProjectEntryId>,
3331 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3332 _maintain_buffer_languages: Task<()>,
3333 diagnostic_summaries:
3334 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3335}
3336
3337pub enum LspStoreEvent {
3338 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3339 LanguageServerRemoved(LanguageServerId),
3340 LanguageServerUpdate {
3341 language_server_id: LanguageServerId,
3342 message: proto::update_language_server::Variant,
3343 },
3344 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3345 LanguageServerPrompt(LanguageServerPromptRequest),
3346 LanguageDetected {
3347 buffer: Entity<Buffer>,
3348 new_language: Option<Arc<Language>>,
3349 },
3350 Notification(String),
3351 RefreshInlayHints,
3352 RefreshCodeLens,
3353 DiagnosticsUpdated {
3354 language_server_id: LanguageServerId,
3355 path: ProjectPath,
3356 },
3357 DiskBasedDiagnosticsStarted {
3358 language_server_id: LanguageServerId,
3359 },
3360 DiskBasedDiagnosticsFinished {
3361 language_server_id: LanguageServerId,
3362 },
3363 SnippetEdit {
3364 buffer_id: BufferId,
3365 edits: Vec<(lsp::Range, Snippet)>,
3366 most_recent_edit: clock::Lamport,
3367 },
3368}
3369
3370#[derive(Clone, Debug, Serialize)]
3371pub struct LanguageServerStatus {
3372 pub name: String,
3373 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3374 pub has_pending_diagnostic_updates: bool,
3375 progress_tokens: HashSet<String>,
3376}
3377
3378#[derive(Clone, Debug)]
3379struct CoreSymbol {
3380 pub language_server_name: LanguageServerName,
3381 pub source_worktree_id: WorktreeId,
3382 pub source_language_server_id: LanguageServerId,
3383 pub path: ProjectPath,
3384 pub name: String,
3385 pub kind: lsp::SymbolKind,
3386 pub range: Range<Unclipped<PointUtf16>>,
3387 pub signature: [u8; 32],
3388}
3389
3390impl LspStore {
3391 pub fn init(client: &AnyProtoClient) {
3392 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3393 client.add_entity_request_handler(Self::handle_restart_language_servers);
3394 client.add_entity_request_handler(Self::handle_stop_language_servers);
3395 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3396 client.add_entity_message_handler(Self::handle_start_language_server);
3397 client.add_entity_message_handler(Self::handle_update_language_server);
3398 client.add_entity_message_handler(Self::handle_language_server_log);
3399 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3400 client.add_entity_request_handler(Self::handle_format_buffers);
3401 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3402 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3403 client.add_entity_request_handler(Self::handle_apply_code_action);
3404 client.add_entity_request_handler(Self::handle_inlay_hints);
3405 client.add_entity_request_handler(Self::handle_get_project_symbols);
3406 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3407 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3408 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3409 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3410 client.add_entity_request_handler(Self::handle_on_type_formatting);
3411 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3412 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3413 client.add_entity_request_handler(Self::handle_rename_project_entry);
3414 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3415 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3416 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3417 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3418 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3419 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3420 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3421 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3422 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3423 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3424 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3425 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3426 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3427
3428 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3429 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3430 client.add_entity_request_handler(
3431 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3432 );
3433 client.add_entity_request_handler(
3434 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3435 );
3436 }
3437
3438 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3439 match &self.mode {
3440 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3441 _ => None,
3442 }
3443 }
3444
3445 pub fn as_local(&self) -> Option<&LocalLspStore> {
3446 match &self.mode {
3447 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3448 _ => None,
3449 }
3450 }
3451
3452 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3453 match &mut self.mode {
3454 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3455 _ => None,
3456 }
3457 }
3458
3459 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3460 match &self.mode {
3461 LspStoreMode::Remote(RemoteLspStore {
3462 upstream_client: Some(upstream_client),
3463 upstream_project_id,
3464 ..
3465 }) => Some((upstream_client.clone(), *upstream_project_id)),
3466
3467 LspStoreMode::Remote(RemoteLspStore {
3468 upstream_client: None,
3469 ..
3470 }) => None,
3471 LspStoreMode::Local(_) => None,
3472 }
3473 }
3474
3475 pub fn new_local(
3476 buffer_store: Entity<BufferStore>,
3477 worktree_store: Entity<WorktreeStore>,
3478 prettier_store: Entity<PrettierStore>,
3479 toolchain_store: Entity<ToolchainStore>,
3480 environment: Entity<ProjectEnvironment>,
3481 languages: Arc<LanguageRegistry>,
3482 http_client: Arc<dyn HttpClient>,
3483 fs: Arc<dyn Fs>,
3484 cx: &mut Context<Self>,
3485 ) -> Self {
3486 let yarn = YarnPathStore::new(fs.clone(), cx);
3487 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3488 .detach();
3489 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3490 .detach();
3491 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3492 .detach();
3493 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3494 .detach();
3495 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3496 cx.subscribe(
3497 extension_events,
3498 Self::reload_zed_json_schemas_on_extensions_changed,
3499 )
3500 .detach();
3501 } else {
3502 log::info!("No extension events global found. Skipping JSON schema auto-reload setup");
3503 }
3504 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3505 .detach();
3506
3507 let _maintain_workspace_config = {
3508 let (sender, receiver) = watch::channel();
3509 (
3510 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3511 sender,
3512 )
3513 };
3514 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
3515 Self {
3516 mode: LspStoreMode::Local(LocalLspStore {
3517 weak: cx.weak_entity(),
3518 worktree_store: worktree_store.clone(),
3519 toolchain_store: toolchain_store.clone(),
3520 supplementary_language_servers: Default::default(),
3521 languages: languages.clone(),
3522 language_server_ids: Default::default(),
3523 language_servers: Default::default(),
3524 last_workspace_edits_by_language_server: Default::default(),
3525 language_server_watched_paths: Default::default(),
3526 language_server_paths_watched_for_rename: Default::default(),
3527 language_server_watcher_registrations: Default::default(),
3528 buffers_being_formatted: Default::default(),
3529 buffer_snapshots: Default::default(),
3530 prettier_store,
3531 environment,
3532 http_client,
3533 fs,
3534 yarn,
3535 next_diagnostic_group_id: Default::default(),
3536 diagnostics: Default::default(),
3537 _subscription: cx.on_app_quit(|this, cx| {
3538 this.as_local_mut().unwrap().shutdown_language_servers(cx)
3539 }),
3540 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3541 registered_buffers: Default::default(),
3542 }),
3543 last_formatting_failure: None,
3544 downstream_client: None,
3545 buffer_store,
3546 worktree_store,
3547 toolchain_store: Some(toolchain_store),
3548 languages: languages.clone(),
3549 language_server_statuses: Default::default(),
3550 nonce: StdRng::from_entropy().r#gen(),
3551 diagnostic_summaries: Default::default(),
3552 active_entry: None,
3553
3554 _maintain_workspace_config,
3555 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3556 }
3557 }
3558
3559 fn send_lsp_proto_request<R: LspCommand>(
3560 &self,
3561 buffer: Entity<Buffer>,
3562 client: AnyProtoClient,
3563 upstream_project_id: u64,
3564 request: R,
3565 cx: &mut Context<LspStore>,
3566 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3567 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3568 cx.spawn(async move |this, cx| {
3569 let response = client.request(message).await?;
3570 let this = this.upgrade().context("project dropped")?;
3571 request
3572 .response_from_proto(response, this, buffer, cx.clone())
3573 .await
3574 })
3575 }
3576
3577 pub(super) fn new_remote(
3578 buffer_store: Entity<BufferStore>,
3579 worktree_store: Entity<WorktreeStore>,
3580 toolchain_store: Option<Entity<ToolchainStore>>,
3581 languages: Arc<LanguageRegistry>,
3582 upstream_client: AnyProtoClient,
3583 project_id: u64,
3584 fs: Arc<dyn Fs>,
3585 cx: &mut Context<Self>,
3586 ) -> Self {
3587 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3588 .detach();
3589 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3590 .detach();
3591 let _maintain_workspace_config = {
3592 let (sender, receiver) = watch::channel();
3593 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3594 };
3595 Self {
3596 mode: LspStoreMode::Remote(RemoteLspStore {
3597 upstream_client: Some(upstream_client),
3598 upstream_project_id: project_id,
3599 }),
3600 downstream_client: None,
3601 last_formatting_failure: None,
3602 buffer_store,
3603 worktree_store,
3604 languages: languages.clone(),
3605 language_server_statuses: Default::default(),
3606 nonce: StdRng::from_entropy().r#gen(),
3607 diagnostic_summaries: Default::default(),
3608 active_entry: None,
3609 toolchain_store,
3610 _maintain_workspace_config,
3611 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3612 }
3613 }
3614
3615 fn on_buffer_store_event(
3616 &mut self,
3617 _: Entity<BufferStore>,
3618 event: &BufferStoreEvent,
3619 cx: &mut Context<Self>,
3620 ) {
3621 match event {
3622 BufferStoreEvent::BufferAdded(buffer) => {
3623 self.on_buffer_added(buffer, cx).log_err();
3624 }
3625 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3626 let buffer_id = buffer.read(cx).remote_id();
3627 if let Some(local) = self.as_local_mut() {
3628 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3629 local.reset_buffer(buffer, old_file, cx);
3630
3631 if local.registered_buffers.contains_key(&buffer_id) {
3632 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3633 }
3634 }
3635 }
3636
3637 self.detect_language_for_buffer(buffer, cx);
3638 if let Some(local) = self.as_local_mut() {
3639 local.initialize_buffer(buffer, cx);
3640 if local.registered_buffers.contains_key(&buffer_id) {
3641 local.register_buffer_with_language_servers(buffer, cx);
3642 }
3643 }
3644 }
3645 _ => {}
3646 }
3647 }
3648
3649 fn on_worktree_store_event(
3650 &mut self,
3651 _: Entity<WorktreeStore>,
3652 event: &WorktreeStoreEvent,
3653 cx: &mut Context<Self>,
3654 ) {
3655 match event {
3656 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3657 if !worktree.read(cx).is_local() {
3658 return;
3659 }
3660 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3661 worktree::Event::UpdatedEntries(changes) => {
3662 this.update_local_worktree_language_servers(&worktree, changes, cx);
3663 }
3664 worktree::Event::UpdatedGitRepositories(_)
3665 | worktree::Event::DeletedEntry(_) => {}
3666 })
3667 .detach()
3668 }
3669 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3670 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3671 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3672 }
3673 WorktreeStoreEvent::WorktreeReleased(..)
3674 | WorktreeStoreEvent::WorktreeOrderChanged
3675 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3676 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3677 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3678 }
3679 }
3680
3681 fn on_prettier_store_event(
3682 &mut self,
3683 _: Entity<PrettierStore>,
3684 event: &PrettierStoreEvent,
3685 cx: &mut Context<Self>,
3686 ) {
3687 match event {
3688 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3689 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3690 }
3691 PrettierStoreEvent::LanguageServerAdded {
3692 new_server_id,
3693 name,
3694 prettier_server,
3695 } => {
3696 self.register_supplementary_language_server(
3697 *new_server_id,
3698 name.clone(),
3699 prettier_server.clone(),
3700 cx,
3701 );
3702 }
3703 }
3704 }
3705
3706 fn on_toolchain_store_event(
3707 &mut self,
3708 _: Entity<ToolchainStore>,
3709 event: &ToolchainStoreEvent,
3710 _: &mut Context<Self>,
3711 ) {
3712 match event {
3713 ToolchainStoreEvent::ToolchainActivated { .. } => {
3714 self.request_workspace_config_refresh()
3715 }
3716 }
3717 }
3718
3719 fn request_workspace_config_refresh(&mut self) {
3720 *self._maintain_workspace_config.1.borrow_mut() = ();
3721 }
3722
3723 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3724 self.as_local().map(|local| local.prettier_store.clone())
3725 }
3726
3727 fn on_buffer_event(
3728 &mut self,
3729 buffer: Entity<Buffer>,
3730 event: &language::BufferEvent,
3731 cx: &mut Context<Self>,
3732 ) {
3733 match event {
3734 language::BufferEvent::Edited { .. } => {
3735 self.on_buffer_edited(buffer, cx);
3736 }
3737
3738 language::BufferEvent::Saved => {
3739 self.on_buffer_saved(buffer, cx);
3740 }
3741
3742 _ => {}
3743 }
3744 }
3745
3746 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3747 buffer.update(cx, |buffer, _| {
3748 buffer.set_language_registry(self.languages.clone())
3749 });
3750
3751 cx.subscribe(buffer, |this, buffer, event, cx| {
3752 this.on_buffer_event(buffer, event, cx);
3753 })
3754 .detach();
3755
3756 self.detect_language_for_buffer(buffer, cx);
3757 if let Some(local) = self.as_local_mut() {
3758 local.initialize_buffer(buffer, cx);
3759 }
3760
3761 Ok(())
3762 }
3763
3764 pub fn reload_zed_json_schemas_on_extensions_changed(
3765 &mut self,
3766 _: Entity<extension::ExtensionEvents>,
3767 evt: &extension::Event,
3768 cx: &mut Context<Self>,
3769 ) {
3770 #[expect(
3771 irrefutable_let_patterns,
3772 reason = "Make sure to handle new event types in extension properly"
3773 )]
3774 let extension::Event::ExtensionsInstalledChanged = evt else {
3775 return;
3776 };
3777 if self.as_local().is_none() {
3778 return;
3779 }
3780 cx.spawn(async move |this, cx| {
3781 let weak_ref = this.clone();
3782
3783 let servers = this
3784 .update(cx, |this, cx| {
3785 let local = this.as_local()?;
3786
3787 let mut servers = Vec::new();
3788 for ((worktree_id, _), server_ids) in &local.language_server_ids {
3789 for server_id in server_ids {
3790 let Some(states) = local.language_servers.get(server_id) else {
3791 continue;
3792 };
3793 let (json_adapter, json_server) = match states {
3794 LanguageServerState::Running {
3795 adapter, server, ..
3796 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
3797 (adapter.adapter.clone(), server.clone())
3798 }
3799 _ => continue,
3800 };
3801
3802 let Some(worktree) = this
3803 .worktree_store
3804 .read(cx)
3805 .worktree_for_id(*worktree_id, cx)
3806 else {
3807 continue;
3808 };
3809 let json_delegate: Arc<dyn LspAdapterDelegate> =
3810 LocalLspAdapterDelegate::new(
3811 local.languages.clone(),
3812 &local.environment,
3813 weak_ref.clone(),
3814 &worktree,
3815 local.http_client.clone(),
3816 local.fs.clone(),
3817 cx,
3818 );
3819
3820 servers.push((json_adapter, json_server, json_delegate));
3821 }
3822 }
3823 return Some(servers);
3824 })
3825 .ok()
3826 .flatten();
3827
3828 let Some(servers) = servers else {
3829 return;
3830 };
3831
3832 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
3833 let local = this.as_local()?;
3834 let toolchain_store = this.toolchain_store(cx);
3835 return Some((local.fs.clone(), toolchain_store));
3836 }) else {
3837 return;
3838 };
3839 for (adapter, server, delegate) in servers {
3840 adapter.clear_zed_json_schema_cache().await;
3841
3842 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
3843 adapter,
3844 fs.as_ref(),
3845 &delegate,
3846 toolchain_store.clone(),
3847 cx,
3848 )
3849 .await
3850 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
3851 .ok()
3852 else {
3853 continue;
3854 };
3855 server
3856 .notify::<lsp::notification::DidChangeConfiguration>(
3857 &lsp::DidChangeConfigurationParams {
3858 settings: json_workspace_config,
3859 },
3860 )
3861 .ok();
3862 }
3863 })
3864 .detach();
3865 }
3866
3867 pub(crate) fn register_buffer_with_language_servers(
3868 &mut self,
3869 buffer: &Entity<Buffer>,
3870 ignore_refcounts: bool,
3871 cx: &mut Context<Self>,
3872 ) -> OpenLspBufferHandle {
3873 let buffer_id = buffer.read(cx).remote_id();
3874 let handle = cx.new(|_| buffer.clone());
3875 if let Some(local) = self.as_local_mut() {
3876 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
3877 return handle;
3878 };
3879 if !file.is_local() {
3880 return handle;
3881 }
3882
3883 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
3884 if !ignore_refcounts {
3885 *refcount += 1;
3886 }
3887
3888 if ignore_refcounts || *refcount == 1 {
3889 local.register_buffer_with_language_servers(buffer, cx);
3890 }
3891 if !ignore_refcounts {
3892 cx.observe_release(&handle, move |this, buffer, cx| {
3893 let local = this.as_local_mut().unwrap();
3894 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
3895 debug_panic!("bad refcounting");
3896 return;
3897 };
3898
3899 *refcount -= 1;
3900 if *refcount == 0 {
3901 local.registered_buffers.remove(&buffer_id);
3902 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
3903 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
3904 }
3905 }
3906 })
3907 .detach();
3908 }
3909 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
3910 let buffer_id = buffer.read(cx).remote_id().to_proto();
3911 cx.background_spawn(async move {
3912 upstream_client
3913 .request(proto::RegisterBufferWithLanguageServers {
3914 project_id: upstream_project_id,
3915 buffer_id,
3916 })
3917 .await
3918 })
3919 .detach();
3920 } else {
3921 panic!("oops!");
3922 }
3923 handle
3924 }
3925
3926 fn maintain_buffer_languages(
3927 languages: Arc<LanguageRegistry>,
3928 cx: &mut Context<Self>,
3929 ) -> Task<()> {
3930 let mut subscription = languages.subscribe();
3931 let mut prev_reload_count = languages.reload_count();
3932 cx.spawn(async move |this, cx| {
3933 while let Some(()) = subscription.next().await {
3934 if let Some(this) = this.upgrade() {
3935 // If the language registry has been reloaded, then remove and
3936 // re-assign the languages on all open buffers.
3937 let reload_count = languages.reload_count();
3938 if reload_count > prev_reload_count {
3939 prev_reload_count = reload_count;
3940 this.update(cx, |this, cx| {
3941 this.buffer_store.clone().update(cx, |buffer_store, cx| {
3942 for buffer in buffer_store.buffers() {
3943 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
3944 {
3945 buffer
3946 .update(cx, |buffer, cx| buffer.set_language(None, cx));
3947 if let Some(local) = this.as_local_mut() {
3948 local.reset_buffer(&buffer, &f, cx);
3949
3950 if local
3951 .registered_buffers
3952 .contains_key(&buffer.read(cx).remote_id())
3953 {
3954 if let Some(file_url) =
3955 lsp::Url::from_file_path(&f.abs_path(cx))
3956 .log_err()
3957 {
3958 local.unregister_buffer_from_language_servers(
3959 &buffer, &file_url, cx,
3960 );
3961 }
3962 }
3963 }
3964 }
3965 }
3966 });
3967 })
3968 .ok();
3969 }
3970
3971 this.update(cx, |this, cx| {
3972 let mut plain_text_buffers = Vec::new();
3973 let mut buffers_with_unknown_injections = Vec::new();
3974 for handle in this.buffer_store.read(cx).buffers() {
3975 let buffer = handle.read(cx);
3976 if buffer.language().is_none()
3977 || buffer.language() == Some(&*language::PLAIN_TEXT)
3978 {
3979 plain_text_buffers.push(handle);
3980 } else if buffer.contains_unknown_injections() {
3981 buffers_with_unknown_injections.push(handle);
3982 }
3983 }
3984 for buffer in plain_text_buffers {
3985 this.detect_language_for_buffer(&buffer, cx);
3986 if let Some(local) = this.as_local_mut() {
3987 local.initialize_buffer(&buffer, cx);
3988 if local
3989 .registered_buffers
3990 .contains_key(&buffer.read(cx).remote_id())
3991 {
3992 local.register_buffer_with_language_servers(&buffer, cx);
3993 }
3994 }
3995 }
3996
3997 for buffer in buffers_with_unknown_injections {
3998 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
3999 }
4000 })
4001 .ok();
4002 }
4003 }
4004 })
4005 }
4006
4007 fn detect_language_for_buffer(
4008 &mut self,
4009 buffer_handle: &Entity<Buffer>,
4010 cx: &mut Context<Self>,
4011 ) -> Option<language::AvailableLanguage> {
4012 // If the buffer has a language, set it and start the language server if we haven't already.
4013 let buffer = buffer_handle.read(cx);
4014 let file = buffer.file()?;
4015
4016 let content = buffer.as_rope();
4017 let available_language = self.languages.language_for_file(file, Some(content), cx);
4018 if let Some(available_language) = &available_language {
4019 if let Some(Ok(Ok(new_language))) = self
4020 .languages
4021 .load_language(available_language)
4022 .now_or_never()
4023 {
4024 self.set_language_for_buffer(buffer_handle, new_language, cx);
4025 }
4026 } else {
4027 cx.emit(LspStoreEvent::LanguageDetected {
4028 buffer: buffer_handle.clone(),
4029 new_language: None,
4030 });
4031 }
4032
4033 available_language
4034 }
4035
4036 pub(crate) fn set_language_for_buffer(
4037 &mut self,
4038 buffer_entity: &Entity<Buffer>,
4039 new_language: Arc<Language>,
4040 cx: &mut Context<Self>,
4041 ) {
4042 let buffer = buffer_entity.read(cx);
4043 let buffer_file = buffer.file().cloned();
4044 let buffer_id = buffer.remote_id();
4045 if let Some(local_store) = self.as_local_mut() {
4046 if local_store.registered_buffers.contains_key(&buffer_id) {
4047 if let Some(abs_path) =
4048 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4049 {
4050 if let Some(file_url) = lsp::Url::from_file_path(&abs_path).log_err() {
4051 local_store.unregister_buffer_from_language_servers(
4052 buffer_entity,
4053 &file_url,
4054 cx,
4055 );
4056 }
4057 }
4058 }
4059 }
4060 buffer_entity.update(cx, |buffer, cx| {
4061 if buffer.language().map_or(true, |old_language| {
4062 !Arc::ptr_eq(old_language, &new_language)
4063 }) {
4064 buffer.set_language(Some(new_language.clone()), cx);
4065 }
4066 });
4067
4068 let settings =
4069 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4070 let buffer_file = File::from_dyn(buffer_file.as_ref());
4071
4072 let worktree_id = if let Some(file) = buffer_file {
4073 let worktree = file.worktree.clone();
4074
4075 if let Some(local) = self.as_local_mut() {
4076 if local.registered_buffers.contains_key(&buffer_id) {
4077 local.register_buffer_with_language_servers(buffer_entity, cx);
4078 }
4079 }
4080 Some(worktree.read(cx).id())
4081 } else {
4082 None
4083 };
4084
4085 if settings.prettier.allowed {
4086 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4087 {
4088 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4089 if let Some(prettier_store) = prettier_store {
4090 prettier_store.update(cx, |prettier_store, cx| {
4091 prettier_store.install_default_prettier(
4092 worktree_id,
4093 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4094 cx,
4095 )
4096 })
4097 }
4098 }
4099 }
4100
4101 cx.emit(LspStoreEvent::LanguageDetected {
4102 buffer: buffer_entity.clone(),
4103 new_language: Some(new_language),
4104 })
4105 }
4106
4107 pub fn buffer_store(&self) -> Entity<BufferStore> {
4108 self.buffer_store.clone()
4109 }
4110
4111 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4112 self.active_entry = active_entry;
4113 }
4114
4115 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4116 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4117 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4118 for (path, summaries) in summaries {
4119 for (&server_id, summary) in summaries {
4120 client
4121 .send(proto::UpdateDiagnosticSummary {
4122 project_id: downstream_project_id,
4123 worktree_id: worktree.id().to_proto(),
4124 summary: Some(summary.to_proto(server_id, path)),
4125 })
4126 .log_err();
4127 }
4128 }
4129 }
4130 }
4131 }
4132
4133 pub fn request_lsp<R: LspCommand>(
4134 &mut self,
4135 buffer_handle: Entity<Buffer>,
4136 server: LanguageServerToQuery,
4137 request: R,
4138 cx: &mut Context<Self>,
4139 ) -> Task<Result<R::Response>>
4140 where
4141 <R::LspRequest as lsp::request::Request>::Result: Send,
4142 <R::LspRequest as lsp::request::Request>::Params: Send,
4143 {
4144 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4145 return self.send_lsp_proto_request(
4146 buffer_handle,
4147 upstream_client,
4148 upstream_project_id,
4149 request,
4150 cx,
4151 );
4152 }
4153
4154 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4155 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4156 local
4157 .language_servers_for_buffer(buffer, cx)
4158 .find(|(_, server)| {
4159 request.check_capabilities(server.adapter_server_capabilities())
4160 })
4161 .map(|(_, server)| server.clone())
4162 }),
4163 LanguageServerToQuery::Other(id) => self
4164 .language_server_for_local_buffer(buffer, id, cx)
4165 .and_then(|(_, server)| {
4166 request
4167 .check_capabilities(server.adapter_server_capabilities())
4168 .then(|| Arc::clone(server))
4169 }),
4170 }) else {
4171 return Task::ready(Ok(Default::default()));
4172 };
4173
4174 let buffer = buffer_handle.read(cx);
4175 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4176
4177 let Some(file) = file else {
4178 return Task::ready(Ok(Default::default()));
4179 };
4180
4181 let lsp_params = match request.to_lsp_params_or_response(
4182 &file.abs_path(cx),
4183 buffer,
4184 &language_server,
4185 cx,
4186 ) {
4187 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4188 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4189
4190 Err(err) => {
4191 let message = format!(
4192 "{} via {} failed: {}",
4193 request.display_name(),
4194 language_server.name(),
4195 err
4196 );
4197 log::warn!("{}", message);
4198 return Task::ready(Err(anyhow!(message)));
4199 }
4200 };
4201
4202 let status = request.status();
4203 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4204 return Task::ready(Ok(Default::default()));
4205 }
4206 return cx.spawn(async move |this, cx| {
4207 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4208
4209 let id = lsp_request.id();
4210 let _cleanup = if status.is_some() {
4211 cx.update(|cx| {
4212 this.update(cx, |this, cx| {
4213 this.on_lsp_work_start(
4214 language_server.server_id(),
4215 id.to_string(),
4216 LanguageServerProgress {
4217 is_disk_based_diagnostics_progress: false,
4218 is_cancellable: false,
4219 title: None,
4220 message: status.clone(),
4221 percentage: None,
4222 last_update_at: cx.background_executor().now(),
4223 },
4224 cx,
4225 );
4226 })
4227 })
4228 .log_err();
4229
4230 Some(defer(|| {
4231 cx.update(|cx| {
4232 this.update(cx, |this, cx| {
4233 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4234 })
4235 })
4236 .log_err();
4237 }))
4238 } else {
4239 None
4240 };
4241
4242 let result = lsp_request.await;
4243
4244 let response = result.map_err(|err| {
4245 let message = format!(
4246 "{} via {} failed: {}",
4247 request.display_name(),
4248 language_server.name(),
4249 err
4250 );
4251 log::warn!("{}", message);
4252 anyhow!(message)
4253 })?;
4254
4255 let response = request
4256 .response_from_lsp(
4257 response,
4258 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
4259 buffer_handle,
4260 language_server.server_id(),
4261 cx.clone(),
4262 )
4263 .await;
4264 response
4265 });
4266 }
4267
4268 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4269 let mut language_formatters_to_check = Vec::new();
4270 for buffer in self.buffer_store.read(cx).buffers() {
4271 let buffer = buffer.read(cx);
4272 let buffer_file = File::from_dyn(buffer.file());
4273 let buffer_language = buffer.language();
4274 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4275 if buffer_language.is_some() {
4276 language_formatters_to_check.push((
4277 buffer_file.map(|f| f.worktree_id(cx)),
4278 settings.into_owned(),
4279 ));
4280 }
4281 }
4282
4283 self.refresh_server_tree(cx);
4284
4285 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4286 prettier_store.update(cx, |prettier_store, cx| {
4287 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4288 })
4289 }
4290
4291 cx.notify();
4292 }
4293
4294 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4295 let buffer_store = self.buffer_store.clone();
4296 if let Some(local) = self.as_local_mut() {
4297 let mut adapters = BTreeMap::default();
4298 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4299 let get_adapter = {
4300 let languages = local.languages.clone();
4301 let environment = local.environment.clone();
4302 let weak = local.weak.clone();
4303 let worktree_store = local.worktree_store.clone();
4304 let http_client = local.http_client.clone();
4305 let fs = local.fs.clone();
4306 move |worktree_id, cx: &mut App| {
4307 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4308 Some(LocalLspAdapterDelegate::new(
4309 languages.clone(),
4310 &environment,
4311 weak.clone(),
4312 &worktree,
4313 http_client.clone(),
4314 fs.clone(),
4315 cx,
4316 ))
4317 }
4318 };
4319
4320 let mut rebase = lsp_tree.rebase();
4321 for buffer in buffer_store.read(cx).buffers().collect::<Vec<_>>() {
4322 let buffer = buffer.read(cx);
4323 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4324 continue;
4325 }
4326 if let Some((file, language)) = File::from_dyn(buffer.file())
4327 .cloned()
4328 .zip(buffer.language().map(|l| l.name()))
4329 {
4330 let worktree_id = file.worktree_id(cx);
4331 let Some(worktree) = local
4332 .worktree_store
4333 .read(cx)
4334 .worktree_for_id(worktree_id, cx)
4335 else {
4336 continue;
4337 };
4338 let path: Arc<Path> = file
4339 .path()
4340 .parent()
4341 .map(Arc::from)
4342 .unwrap_or_else(|| file.path().clone());
4343 let worktree_path = ProjectPath { worktree_id, path };
4344
4345 let Some(delegate) = adapters
4346 .entry(worktree_id)
4347 .or_insert_with(|| get_adapter(worktree_id, cx))
4348 .clone()
4349 else {
4350 continue;
4351 };
4352 let nodes = rebase.get(
4353 worktree_path,
4354 AdapterQuery::Language(&language),
4355 delegate.clone(),
4356 cx,
4357 );
4358 for node in nodes {
4359 node.server_id_or_init(
4360 |LaunchDisposition {
4361 server_name,
4362 attach,
4363 path,
4364 settings,
4365 }| match attach {
4366 language::Attach::InstancePerRoot => {
4367 // todo: handle instance per root proper.
4368 if let Some(server_ids) = local
4369 .language_server_ids
4370 .get(&(worktree_id, server_name.clone()))
4371 {
4372 server_ids.iter().cloned().next().unwrap()
4373 } else {
4374 local.start_language_server(
4375 &worktree,
4376 delegate.clone(),
4377 local
4378 .languages
4379 .lsp_adapters(&language)
4380 .into_iter()
4381 .find(|adapter| &adapter.name() == server_name)
4382 .expect("To find LSP adapter"),
4383 settings,
4384 cx,
4385 )
4386 }
4387 }
4388 language::Attach::Shared => {
4389 let uri = Url::from_file_path(
4390 worktree.read(cx).abs_path().join(&path.path),
4391 );
4392 let key = (worktree_id, server_name.clone());
4393 local.language_server_ids.remove(&key);
4394
4395 let server_id = local.start_language_server(
4396 &worktree,
4397 delegate.clone(),
4398 local
4399 .languages
4400 .lsp_adapters(&language)
4401 .into_iter()
4402 .find(|adapter| &adapter.name() == server_name)
4403 .expect("To find LSP adapter"),
4404 settings,
4405 cx,
4406 );
4407 if let Some(state) = local.language_servers.get(&server_id)
4408 {
4409 if let Ok(uri) = uri {
4410 state.add_workspace_folder(uri);
4411 };
4412 }
4413 server_id
4414 }
4415 },
4416 );
4417 }
4418 }
4419 }
4420 rebase.finish()
4421 });
4422 for (id, name) in to_stop {
4423 self.stop_local_language_server(id, name, cx).detach();
4424 }
4425 }
4426 }
4427
4428 pub fn apply_code_action(
4429 &self,
4430 buffer_handle: Entity<Buffer>,
4431 mut action: CodeAction,
4432 push_to_history: bool,
4433 cx: &mut Context<Self>,
4434 ) -> Task<Result<ProjectTransaction>> {
4435 if let Some((upstream_client, project_id)) = self.upstream_client() {
4436 let request = proto::ApplyCodeAction {
4437 project_id,
4438 buffer_id: buffer_handle.read(cx).remote_id().into(),
4439 action: Some(Self::serialize_code_action(&action)),
4440 };
4441 let buffer_store = self.buffer_store();
4442 cx.spawn(async move |_, cx| {
4443 let response = upstream_client
4444 .request(request)
4445 .await?
4446 .transaction
4447 .ok_or_else(|| anyhow!("missing transaction"))?;
4448
4449 buffer_store
4450 .update(cx, |buffer_store, cx| {
4451 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4452 })?
4453 .await
4454 })
4455 } else if self.mode.is_local() {
4456 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4457 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4458 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4459 }) else {
4460 return Task::ready(Ok(ProjectTransaction::default()));
4461 };
4462 cx.spawn(async move |this, cx| {
4463 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4464 .await
4465 .context("resolving a code action")?;
4466 if let Some(edit) = action.lsp_action.edit() {
4467 if edit.changes.is_some() || edit.document_changes.is_some() {
4468 return LocalLspStore::deserialize_workspace_edit(
4469 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
4470 edit.clone(),
4471 push_to_history,
4472 lsp_adapter.clone(),
4473 lang_server.clone(),
4474 cx,
4475 )
4476 .await;
4477 }
4478 }
4479
4480 if let Some(command) = action.lsp_action.command() {
4481 let server_capabilities = lang_server.capabilities();
4482 let available_commands = server_capabilities
4483 .execute_command_provider
4484 .as_ref()
4485 .map(|options| options.commands.as_slice())
4486 .unwrap_or_default();
4487 if available_commands.contains(&command.command) {
4488 this.update(cx, |this, _| {
4489 this.as_local_mut()
4490 .unwrap()
4491 .last_workspace_edits_by_language_server
4492 .remove(&lang_server.server_id());
4493 })?;
4494
4495 let result = lang_server
4496 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4497 command: command.command.clone(),
4498 arguments: command.arguments.clone().unwrap_or_default(),
4499 ..Default::default()
4500 })
4501 .await;
4502
4503 result?;
4504
4505 return this.update(cx, |this, _| {
4506 this.as_local_mut()
4507 .unwrap()
4508 .last_workspace_edits_by_language_server
4509 .remove(&lang_server.server_id())
4510 .unwrap_or_default()
4511 });
4512 } else {
4513 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4514 }
4515 }
4516
4517 Ok(ProjectTransaction::default())
4518 })
4519 } else {
4520 Task::ready(Err(anyhow!("no upstream client and not local")))
4521 }
4522 }
4523
4524 pub fn apply_code_action_kind(
4525 &mut self,
4526 buffers: HashSet<Entity<Buffer>>,
4527 kind: CodeActionKind,
4528 push_to_history: bool,
4529 cx: &mut Context<Self>,
4530 ) -> Task<anyhow::Result<ProjectTransaction>> {
4531 if let Some(_) = self.as_local() {
4532 cx.spawn(async move |lsp_store, cx| {
4533 let buffers = buffers.into_iter().collect::<Vec<_>>();
4534 let result = LocalLspStore::execute_code_action_kind_locally(
4535 lsp_store.clone(),
4536 buffers,
4537 kind,
4538 push_to_history,
4539 cx,
4540 )
4541 .await;
4542 lsp_store.update(cx, |lsp_store, _| {
4543 lsp_store.update_last_formatting_failure(&result);
4544 })?;
4545 result
4546 })
4547 } else if let Some((client, project_id)) = self.upstream_client() {
4548 let buffer_store = self.buffer_store();
4549 cx.spawn(async move |lsp_store, cx| {
4550 let result = client
4551 .request(proto::ApplyCodeActionKind {
4552 project_id,
4553 kind: kind.as_str().to_owned(),
4554 buffer_ids: buffers
4555 .iter()
4556 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
4557 .collect::<Result<_>>()?,
4558 })
4559 .await
4560 .and_then(|result| result.transaction.context("missing transaction"));
4561 lsp_store.update(cx, |lsp_store, _| {
4562 lsp_store.update_last_formatting_failure(&result);
4563 })?;
4564
4565 let transaction_response = result?;
4566 buffer_store
4567 .update(cx, |buffer_store, cx| {
4568 buffer_store.deserialize_project_transaction(
4569 transaction_response,
4570 push_to_history,
4571 cx,
4572 )
4573 })?
4574 .await
4575 })
4576 } else {
4577 Task::ready(Ok(ProjectTransaction::default()))
4578 }
4579 }
4580
4581 pub fn resolve_inlay_hint(
4582 &self,
4583 hint: InlayHint,
4584 buffer_handle: Entity<Buffer>,
4585 server_id: LanguageServerId,
4586 cx: &mut Context<Self>,
4587 ) -> Task<anyhow::Result<InlayHint>> {
4588 if let Some((upstream_client, project_id)) = self.upstream_client() {
4589 let request = proto::ResolveInlayHint {
4590 project_id,
4591 buffer_id: buffer_handle.read(cx).remote_id().into(),
4592 language_server_id: server_id.0 as u64,
4593 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4594 };
4595 cx.spawn(async move |_, _| {
4596 let response = upstream_client
4597 .request(request)
4598 .await
4599 .context("inlay hints proto request")?;
4600 match response.hint {
4601 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4602 .context("inlay hints proto resolve response conversion"),
4603 None => Ok(hint),
4604 }
4605 })
4606 } else {
4607 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4608 self.language_server_for_local_buffer(buffer, server_id, cx)
4609 .map(|(_, server)| server.clone())
4610 }) else {
4611 return Task::ready(Ok(hint));
4612 };
4613 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4614 return Task::ready(Ok(hint));
4615 }
4616 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4617 cx.spawn(async move |_, cx| {
4618 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4619 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4620 );
4621 let resolved_hint = resolve_task
4622 .await
4623 .context("inlay hint resolve LSP request")?;
4624 let resolved_hint = InlayHints::lsp_to_project_hint(
4625 resolved_hint,
4626 &buffer_handle,
4627 server_id,
4628 ResolveState::Resolved,
4629 false,
4630 cx,
4631 )
4632 .await?;
4633 Ok(resolved_hint)
4634 })
4635 }
4636 }
4637
4638 pub(crate) fn linked_edit(
4639 &mut self,
4640 buffer: &Entity<Buffer>,
4641 position: Anchor,
4642 cx: &mut Context<Self>,
4643 ) -> Task<Result<Vec<Range<Anchor>>>> {
4644 let snapshot = buffer.read(cx).snapshot();
4645 let scope = snapshot.language_scope_at(position);
4646 let Some(server_id) = self
4647 .as_local()
4648 .and_then(|local| {
4649 buffer.update(cx, |buffer, cx| {
4650 local
4651 .language_servers_for_buffer(buffer, cx)
4652 .filter(|(_, server)| {
4653 server
4654 .capabilities()
4655 .linked_editing_range_provider
4656 .is_some()
4657 })
4658 .filter(|(adapter, _)| {
4659 scope
4660 .as_ref()
4661 .map(|scope| scope.language_allowed(&adapter.name))
4662 .unwrap_or(true)
4663 })
4664 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
4665 .next()
4666 })
4667 })
4668 .or_else(|| {
4669 self.upstream_client()
4670 .is_some()
4671 .then_some(LanguageServerToQuery::FirstCapable)
4672 })
4673 .filter(|_| {
4674 maybe!({
4675 let language = buffer.read(cx).language_at(position)?;
4676 Some(
4677 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
4678 .linked_edits,
4679 )
4680 }) == Some(true)
4681 })
4682 else {
4683 return Task::ready(Ok(vec![]));
4684 };
4685
4686 self.request_lsp(
4687 buffer.clone(),
4688 server_id,
4689 LinkedEditingRange { position },
4690 cx,
4691 )
4692 }
4693
4694 fn apply_on_type_formatting(
4695 &mut self,
4696 buffer: Entity<Buffer>,
4697 position: Anchor,
4698 trigger: String,
4699 cx: &mut Context<Self>,
4700 ) -> Task<Result<Option<Transaction>>> {
4701 if let Some((client, project_id)) = self.upstream_client() {
4702 let request = proto::OnTypeFormatting {
4703 project_id,
4704 buffer_id: buffer.read(cx).remote_id().into(),
4705 position: Some(serialize_anchor(&position)),
4706 trigger,
4707 version: serialize_version(&buffer.read(cx).version()),
4708 };
4709 cx.spawn(async move |_, _| {
4710 client
4711 .request(request)
4712 .await?
4713 .transaction
4714 .map(language::proto::deserialize_transaction)
4715 .transpose()
4716 })
4717 } else if let Some(local) = self.as_local_mut() {
4718 let buffer_id = buffer.read(cx).remote_id();
4719 local.buffers_being_formatted.insert(buffer_id);
4720 cx.spawn(async move |this, cx| {
4721 let _cleanup = defer({
4722 let this = this.clone();
4723 let mut cx = cx.clone();
4724 move || {
4725 this.update(&mut cx, |this, _| {
4726 if let Some(local) = this.as_local_mut() {
4727 local.buffers_being_formatted.remove(&buffer_id);
4728 }
4729 })
4730 .ok();
4731 }
4732 });
4733
4734 buffer
4735 .update(cx, |buffer, _| {
4736 buffer.wait_for_edits(Some(position.timestamp))
4737 })?
4738 .await?;
4739 this.update(cx, |this, cx| {
4740 let position = position.to_point_utf16(buffer.read(cx));
4741 this.on_type_format(buffer, position, trigger, false, cx)
4742 })?
4743 .await
4744 })
4745 } else {
4746 Task::ready(Err(anyhow!("No upstream client or local language server")))
4747 }
4748 }
4749
4750 pub fn on_type_format<T: ToPointUtf16>(
4751 &mut self,
4752 buffer: Entity<Buffer>,
4753 position: T,
4754 trigger: String,
4755 push_to_history: bool,
4756 cx: &mut Context<Self>,
4757 ) -> Task<Result<Option<Transaction>>> {
4758 let position = position.to_point_utf16(buffer.read(cx));
4759 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
4760 }
4761
4762 fn on_type_format_impl(
4763 &mut self,
4764 buffer: Entity<Buffer>,
4765 position: PointUtf16,
4766 trigger: String,
4767 push_to_history: bool,
4768 cx: &mut Context<Self>,
4769 ) -> Task<Result<Option<Transaction>>> {
4770 let options = buffer.update(cx, |buffer, cx| {
4771 lsp_command::lsp_formatting_options(
4772 language_settings(
4773 buffer.language_at(position).map(|l| l.name()),
4774 buffer.file(),
4775 cx,
4776 )
4777 .as_ref(),
4778 )
4779 });
4780 self.request_lsp(
4781 buffer.clone(),
4782 LanguageServerToQuery::FirstCapable,
4783 OnTypeFormatting {
4784 position,
4785 trigger,
4786 options,
4787 push_to_history,
4788 },
4789 cx,
4790 )
4791 }
4792
4793 pub fn code_actions(
4794 &mut self,
4795 buffer_handle: &Entity<Buffer>,
4796 range: Range<Anchor>,
4797 kinds: Option<Vec<CodeActionKind>>,
4798 cx: &mut Context<Self>,
4799 ) -> Task<Result<Vec<CodeAction>>> {
4800 if let Some((upstream_client, project_id)) = self.upstream_client() {
4801 let request_task = upstream_client.request(proto::MultiLspQuery {
4802 buffer_id: buffer_handle.read(cx).remote_id().into(),
4803 version: serialize_version(&buffer_handle.read(cx).version()),
4804 project_id,
4805 strategy: Some(proto::multi_lsp_query::Strategy::All(
4806 proto::AllLanguageServers {},
4807 )),
4808 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
4809 GetCodeActions {
4810 range: range.clone(),
4811 kinds: kinds.clone(),
4812 }
4813 .to_proto(project_id, buffer_handle.read(cx)),
4814 )),
4815 });
4816 let buffer = buffer_handle.clone();
4817 cx.spawn(async move |weak_project, cx| {
4818 let Some(project) = weak_project.upgrade() else {
4819 return Ok(Vec::new());
4820 };
4821 let responses = request_task.await?.responses;
4822 let actions = join_all(
4823 responses
4824 .into_iter()
4825 .filter_map(|lsp_response| match lsp_response.response? {
4826 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
4827 Some(response)
4828 }
4829 unexpected => {
4830 debug_panic!("Unexpected response: {unexpected:?}");
4831 None
4832 }
4833 })
4834 .map(|code_actions_response| {
4835 GetCodeActions {
4836 range: range.clone(),
4837 kinds: kinds.clone(),
4838 }
4839 .response_from_proto(
4840 code_actions_response,
4841 project.clone(),
4842 buffer.clone(),
4843 cx.clone(),
4844 )
4845 }),
4846 )
4847 .await;
4848
4849 Ok(actions
4850 .into_iter()
4851 .collect::<Result<Vec<Vec<_>>>>()?
4852 .into_iter()
4853 .flatten()
4854 .collect())
4855 })
4856 } else {
4857 let all_actions_task = self.request_multiple_lsp_locally(
4858 buffer_handle,
4859 Some(range.start),
4860 GetCodeActions {
4861 range: range.clone(),
4862 kinds: kinds.clone(),
4863 },
4864 cx,
4865 );
4866 cx.spawn(async move |_, _| Ok(all_actions_task.await.into_iter().flatten().collect()))
4867 }
4868 }
4869
4870 pub fn code_lens(
4871 &mut self,
4872 buffer_handle: &Entity<Buffer>,
4873 cx: &mut Context<Self>,
4874 ) -> Task<Result<Vec<CodeAction>>> {
4875 if let Some((upstream_client, project_id)) = self.upstream_client() {
4876 let request_task = upstream_client.request(proto::MultiLspQuery {
4877 buffer_id: buffer_handle.read(cx).remote_id().into(),
4878 version: serialize_version(&buffer_handle.read(cx).version()),
4879 project_id,
4880 strategy: Some(proto::multi_lsp_query::Strategy::All(
4881 proto::AllLanguageServers {},
4882 )),
4883 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
4884 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
4885 )),
4886 });
4887 let buffer = buffer_handle.clone();
4888 cx.spawn(async move |weak_project, cx| {
4889 let Some(project) = weak_project.upgrade() else {
4890 return Ok(Vec::new());
4891 };
4892 let responses = request_task.await?.responses;
4893 let code_lens = join_all(
4894 responses
4895 .into_iter()
4896 .filter_map(|lsp_response| match lsp_response.response? {
4897 proto::lsp_response::Response::GetCodeLensResponse(response) => {
4898 Some(response)
4899 }
4900 unexpected => {
4901 debug_panic!("Unexpected response: {unexpected:?}");
4902 None
4903 }
4904 })
4905 .map(|code_lens_response| {
4906 GetCodeLens.response_from_proto(
4907 code_lens_response,
4908 project.clone(),
4909 buffer.clone(),
4910 cx.clone(),
4911 )
4912 }),
4913 )
4914 .await;
4915
4916 Ok(code_lens
4917 .into_iter()
4918 .collect::<Result<Vec<Vec<_>>>>()?
4919 .into_iter()
4920 .flatten()
4921 .collect())
4922 })
4923 } else {
4924 let code_lens_task =
4925 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
4926 cx.spawn(async move |_, _| Ok(code_lens_task.await.into_iter().flatten().collect()))
4927 }
4928 }
4929
4930 #[inline(never)]
4931 pub fn completions(
4932 &self,
4933 buffer: &Entity<Buffer>,
4934 position: PointUtf16,
4935 context: CompletionContext,
4936 cx: &mut Context<Self>,
4937 ) -> Task<Result<Option<Vec<Completion>>>> {
4938 let language_registry = self.languages.clone();
4939
4940 if let Some((upstream_client, project_id)) = self.upstream_client() {
4941 let task = self.send_lsp_proto_request(
4942 buffer.clone(),
4943 upstream_client,
4944 project_id,
4945 GetCompletions { position, context },
4946 cx,
4947 );
4948 let language = buffer.read(cx).language().cloned();
4949
4950 // In the future, we should provide project guests with the names of LSP adapters,
4951 // so that they can use the correct LSP adapter when computing labels. For now,
4952 // guests just use the first LSP adapter associated with the buffer's language.
4953 let lsp_adapter = language.as_ref().and_then(|language| {
4954 language_registry
4955 .lsp_adapters(&language.name())
4956 .first()
4957 .cloned()
4958 });
4959
4960 cx.foreground_executor().spawn(async move {
4961 let completions = task.await?;
4962 let mut result = Vec::new();
4963 populate_labels_for_completions(completions, language, lsp_adapter, &mut result)
4964 .await;
4965 Ok(Some(result))
4966 })
4967 } else if let Some(local) = self.as_local() {
4968 let snapshot = buffer.read(cx).snapshot();
4969 let offset = position.to_offset(&snapshot);
4970 let scope = snapshot.language_scope_at(offset);
4971 let language = snapshot.language().cloned();
4972 let completion_settings = language_settings(
4973 language.as_ref().map(|language| language.name()),
4974 buffer.read(cx).file(),
4975 cx,
4976 )
4977 .completions;
4978 if !completion_settings.lsp {
4979 return Task::ready(Ok(None));
4980 }
4981
4982 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
4983 local
4984 .language_servers_for_buffer(buffer, cx)
4985 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4986 .filter(|(adapter, _)| {
4987 scope
4988 .as_ref()
4989 .map(|scope| scope.language_allowed(&adapter.name))
4990 .unwrap_or(true)
4991 })
4992 .map(|(_, server)| server.server_id())
4993 .collect()
4994 });
4995
4996 let buffer = buffer.clone();
4997 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
4998 let lsp_timeout = if lsp_timeout > 0 {
4999 Some(Duration::from_millis(lsp_timeout))
5000 } else {
5001 None
5002 };
5003 cx.spawn(async move |this, cx| {
5004 let mut tasks = Vec::with_capacity(server_ids.len());
5005 this.update(cx, |lsp_store, cx| {
5006 for server_id in server_ids {
5007 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5008 let lsp_timeout = lsp_timeout
5009 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5010 let mut timeout = cx.background_spawn(async move {
5011 match lsp_timeout {
5012 Some(lsp_timeout) => {
5013 lsp_timeout.await;
5014 true
5015 },
5016 None => false,
5017 }
5018 }).fuse();
5019 let mut lsp_request = lsp_store.request_lsp(
5020 buffer.clone(),
5021 LanguageServerToQuery::Other(server_id),
5022 GetCompletions {
5023 position,
5024 context: context.clone(),
5025 },
5026 cx,
5027 ).fuse();
5028 let new_task = cx.background_spawn(async move {
5029 select_biased! {
5030 response = lsp_request => anyhow::Ok(Some(response?)),
5031 timeout_happened = timeout => {
5032 if timeout_happened {
5033 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5034 Ok(None)
5035 } else {
5036 let completions = lsp_request.await?;
5037 Ok(Some(completions))
5038 }
5039 },
5040 }
5041 });
5042 tasks.push((lsp_adapter, new_task));
5043 }
5044 })?;
5045
5046 let mut has_completions_returned = false;
5047 let mut completions = Vec::new();
5048 for (lsp_adapter, task) in tasks {
5049 if let Ok(Some(new_completions)) = task.await {
5050 has_completions_returned = true;
5051 populate_labels_for_completions(
5052 new_completions,
5053 language.clone(),
5054 lsp_adapter,
5055 &mut completions,
5056 )
5057 .await;
5058 }
5059 }
5060 if has_completions_returned {
5061 Ok(Some(completions))
5062 } else {
5063 Ok(None)
5064 }
5065 })
5066 } else {
5067 Task::ready(Err(anyhow!("No upstream client or local language server")))
5068 }
5069 }
5070
5071 pub fn resolve_completions(
5072 &self,
5073 buffer: Entity<Buffer>,
5074 completion_indices: Vec<usize>,
5075 completions: Rc<RefCell<Box<[Completion]>>>,
5076 cx: &mut Context<Self>,
5077 ) -> Task<Result<bool>> {
5078 let client = self.upstream_client();
5079
5080 let buffer_id = buffer.read(cx).remote_id();
5081 let buffer_snapshot = buffer.read(cx).snapshot();
5082
5083 cx.spawn(async move |this, cx| {
5084 let mut did_resolve = false;
5085 if let Some((client, project_id)) = client {
5086 for completion_index in completion_indices {
5087 let server_id = {
5088 let completion = &completions.borrow()[completion_index];
5089 completion.source.server_id()
5090 };
5091 if let Some(server_id) = server_id {
5092 if Self::resolve_completion_remote(
5093 project_id,
5094 server_id,
5095 buffer_id,
5096 completions.clone(),
5097 completion_index,
5098 client.clone(),
5099 )
5100 .await
5101 .log_err()
5102 .is_some()
5103 {
5104 did_resolve = true;
5105 }
5106 } else {
5107 resolve_word_completion(
5108 &buffer_snapshot,
5109 &mut completions.borrow_mut()[completion_index],
5110 );
5111 }
5112 }
5113 } else {
5114 for completion_index in completion_indices {
5115 let server_id = {
5116 let completion = &completions.borrow()[completion_index];
5117 completion.source.server_id()
5118 };
5119 if let Some(server_id) = server_id {
5120 let server_and_adapter = this
5121 .read_with(cx, |lsp_store, _| {
5122 let server = lsp_store.language_server_for_id(server_id)?;
5123 let adapter =
5124 lsp_store.language_server_adapter_for_id(server.server_id())?;
5125 Some((server, adapter))
5126 })
5127 .ok()
5128 .flatten();
5129 let Some((server, adapter)) = server_and_adapter else {
5130 continue;
5131 };
5132
5133 let resolved = Self::resolve_completion_local(
5134 server,
5135 &buffer_snapshot,
5136 completions.clone(),
5137 completion_index,
5138 )
5139 .await
5140 .log_err()
5141 .is_some();
5142 if resolved {
5143 Self::regenerate_completion_labels(
5144 adapter,
5145 &buffer_snapshot,
5146 completions.clone(),
5147 completion_index,
5148 )
5149 .await
5150 .log_err();
5151 did_resolve = true;
5152 }
5153 } else {
5154 resolve_word_completion(
5155 &buffer_snapshot,
5156 &mut completions.borrow_mut()[completion_index],
5157 );
5158 }
5159 }
5160 }
5161
5162 Ok(did_resolve)
5163 })
5164 }
5165
5166 async fn resolve_completion_local(
5167 server: Arc<lsp::LanguageServer>,
5168 snapshot: &BufferSnapshot,
5169 completions: Rc<RefCell<Box<[Completion]>>>,
5170 completion_index: usize,
5171 ) -> Result<()> {
5172 let server_id = server.server_id();
5173 let can_resolve = server
5174 .capabilities()
5175 .completion_provider
5176 .as_ref()
5177 .and_then(|options| options.resolve_provider)
5178 .unwrap_or(false);
5179 if !can_resolve {
5180 return Ok(());
5181 }
5182
5183 let request = {
5184 let completion = &completions.borrow()[completion_index];
5185 match &completion.source {
5186 CompletionSource::Lsp {
5187 lsp_completion,
5188 resolved,
5189 server_id: completion_server_id,
5190 ..
5191 } => {
5192 if *resolved {
5193 return Ok(());
5194 }
5195 anyhow::ensure!(
5196 server_id == *completion_server_id,
5197 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5198 );
5199 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5200 }
5201 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5202 return Ok(());
5203 }
5204 }
5205 };
5206 let resolved_completion = request.await?;
5207
5208 let mut updated_insert_range = None;
5209 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5210 // Technically we don't have to parse the whole `text_edit`, since the only
5211 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5212 // is `typescript-language-server` and they only update `text_edit.new_text`.
5213 // But we should not rely on that.
5214 let edit = parse_completion_text_edit(text_edit, snapshot);
5215
5216 if let Some(mut parsed_edit) = edit {
5217 LineEnding::normalize(&mut parsed_edit.new_text);
5218
5219 let mut completions = completions.borrow_mut();
5220 let completion = &mut completions[completion_index];
5221
5222 completion.new_text = parsed_edit.new_text;
5223 completion.replace_range = parsed_edit.replace_range;
5224
5225 updated_insert_range = parsed_edit.insert_range;
5226 }
5227 }
5228
5229 let mut completions = completions.borrow_mut();
5230 let completion = &mut completions[completion_index];
5231 if let CompletionSource::Lsp {
5232 insert_range,
5233 lsp_completion,
5234 resolved,
5235 server_id: completion_server_id,
5236 ..
5237 } = &mut completion.source
5238 {
5239 *insert_range = updated_insert_range;
5240 if *resolved {
5241 return Ok(());
5242 }
5243 anyhow::ensure!(
5244 server_id == *completion_server_id,
5245 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5246 );
5247 *lsp_completion = Box::new(resolved_completion);
5248 *resolved = true;
5249 }
5250 Ok(())
5251 }
5252
5253 async fn regenerate_completion_labels(
5254 adapter: Arc<CachedLspAdapter>,
5255 snapshot: &BufferSnapshot,
5256 completions: Rc<RefCell<Box<[Completion]>>>,
5257 completion_index: usize,
5258 ) -> Result<()> {
5259 let completion_item = completions.borrow()[completion_index]
5260 .source
5261 .lsp_completion(true)
5262 .map(Cow::into_owned);
5263 if let Some(lsp_documentation) = completion_item
5264 .as_ref()
5265 .and_then(|completion_item| completion_item.documentation.clone())
5266 {
5267 let mut completions = completions.borrow_mut();
5268 let completion = &mut completions[completion_index];
5269 completion.documentation = Some(lsp_documentation.into());
5270 } else {
5271 let mut completions = completions.borrow_mut();
5272 let completion = &mut completions[completion_index];
5273 completion.documentation = Some(CompletionDocumentation::Undocumented);
5274 }
5275
5276 let mut new_label = match completion_item {
5277 Some(completion_item) => {
5278 // 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
5279 // So we have to update the label here anyway...
5280 let language = snapshot.language();
5281 match language {
5282 Some(language) => {
5283 adapter
5284 .labels_for_completions(&[completion_item.clone()], language)
5285 .await?
5286 }
5287 None => Vec::new(),
5288 }
5289 .pop()
5290 .flatten()
5291 .unwrap_or_else(|| {
5292 CodeLabel::fallback_for_completion(
5293 &completion_item,
5294 language.map(|language| language.as_ref()),
5295 )
5296 })
5297 }
5298 None => CodeLabel::plain(
5299 completions.borrow()[completion_index].new_text.clone(),
5300 None,
5301 ),
5302 };
5303 ensure_uniform_list_compatible_label(&mut new_label);
5304
5305 let mut completions = completions.borrow_mut();
5306 let completion = &mut completions[completion_index];
5307 if completion.label.filter_text() == new_label.filter_text() {
5308 completion.label = new_label;
5309 } else {
5310 log::error!(
5311 "Resolved completion changed display label from {} to {}. \
5312 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5313 completion.label.text(),
5314 new_label.text(),
5315 completion.label.filter_text(),
5316 new_label.filter_text()
5317 );
5318 }
5319
5320 Ok(())
5321 }
5322
5323 async fn resolve_completion_remote(
5324 project_id: u64,
5325 server_id: LanguageServerId,
5326 buffer_id: BufferId,
5327 completions: Rc<RefCell<Box<[Completion]>>>,
5328 completion_index: usize,
5329 client: AnyProtoClient,
5330 ) -> Result<()> {
5331 let lsp_completion = {
5332 let completion = &completions.borrow()[completion_index];
5333 match &completion.source {
5334 CompletionSource::Lsp {
5335 lsp_completion,
5336 resolved,
5337 server_id: completion_server_id,
5338 ..
5339 } => {
5340 anyhow::ensure!(
5341 server_id == *completion_server_id,
5342 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5343 );
5344 if *resolved {
5345 return Ok(());
5346 }
5347 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5348 }
5349 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5350 return Ok(());
5351 }
5352 }
5353 };
5354 let request = proto::ResolveCompletionDocumentation {
5355 project_id,
5356 language_server_id: server_id.0 as u64,
5357 lsp_completion,
5358 buffer_id: buffer_id.into(),
5359 };
5360
5361 let response = client
5362 .request(request)
5363 .await
5364 .context("completion documentation resolve proto request")?;
5365 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5366
5367 let documentation = if response.documentation.is_empty() {
5368 CompletionDocumentation::Undocumented
5369 } else if response.documentation_is_markdown {
5370 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5371 } else if response.documentation.lines().count() <= 1 {
5372 CompletionDocumentation::SingleLine(response.documentation.into())
5373 } else {
5374 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5375 };
5376
5377 let mut completions = completions.borrow_mut();
5378 let completion = &mut completions[completion_index];
5379 completion.documentation = Some(documentation);
5380 if let CompletionSource::Lsp {
5381 insert_range,
5382 lsp_completion,
5383 resolved,
5384 server_id: completion_server_id,
5385 lsp_defaults: _,
5386 } = &mut completion.source
5387 {
5388 let completion_insert_range = response
5389 .old_insert_start
5390 .and_then(deserialize_anchor)
5391 .zip(response.old_insert_end.and_then(deserialize_anchor));
5392 *insert_range = completion_insert_range.map(|(start, end)| start..end);
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 replace_range = response
5406 .old_replace_start
5407 .and_then(deserialize_anchor)
5408 .zip(response.old_replace_end.and_then(deserialize_anchor));
5409 if let Some((old_replace_start, old_replace_end)) = replace_range {
5410 if !response.new_text.is_empty() {
5411 completion.new_text = response.new_text;
5412 completion.replace_range = old_replace_start..old_replace_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 replace_range: completion.replace_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.replace_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_replace_start = None;
7713 let mut old_replace_end = None;
7714 let mut old_insert_start = None;
7715 let mut old_insert_end = None;
7716 let mut new_text = String::default();
7717 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
7718 let buffer_snapshot = this.update(&mut cx, |this, cx| {
7719 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7720 anyhow::Ok(buffer.read(cx).snapshot())
7721 })??;
7722
7723 if let Some(text_edit) = completion.text_edit.as_ref() {
7724 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
7725
7726 if let Some(mut edit) = edit {
7727 LineEnding::normalize(&mut edit.new_text);
7728
7729 new_text = edit.new_text;
7730 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
7731 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
7732 if let Some(insert_range) = edit.insert_range {
7733 old_insert_start = Some(serialize_anchor(&insert_range.start));
7734 old_insert_end = Some(serialize_anchor(&insert_range.end));
7735 }
7736 }
7737 }
7738 }
7739
7740 Ok(proto::ResolveCompletionDocumentationResponse {
7741 documentation,
7742 documentation_is_markdown,
7743 old_replace_start,
7744 old_replace_end,
7745 new_text,
7746 lsp_completion,
7747 old_insert_start,
7748 old_insert_end,
7749 })
7750 }
7751
7752 async fn handle_on_type_formatting(
7753 this: Entity<Self>,
7754 envelope: TypedEnvelope<proto::OnTypeFormatting>,
7755 mut cx: AsyncApp,
7756 ) -> Result<proto::OnTypeFormattingResponse> {
7757 let on_type_formatting = this.update(&mut cx, |this, cx| {
7758 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7759 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7760 let position = envelope
7761 .payload
7762 .position
7763 .and_then(deserialize_anchor)
7764 .ok_or_else(|| anyhow!("invalid position"))?;
7765 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7766 buffer,
7767 position,
7768 envelope.payload.trigger.clone(),
7769 cx,
7770 ))
7771 })??;
7772
7773 let transaction = on_type_formatting
7774 .await?
7775 .as_ref()
7776 .map(language::proto::serialize_transaction);
7777 Ok(proto::OnTypeFormattingResponse { transaction })
7778 }
7779
7780 async fn handle_refresh_inlay_hints(
7781 this: Entity<Self>,
7782 _: TypedEnvelope<proto::RefreshInlayHints>,
7783 mut cx: AsyncApp,
7784 ) -> Result<proto::Ack> {
7785 this.update(&mut cx, |_, cx| {
7786 cx.emit(LspStoreEvent::RefreshInlayHints);
7787 })?;
7788 Ok(proto::Ack {})
7789 }
7790
7791 async fn handle_inlay_hints(
7792 this: Entity<Self>,
7793 envelope: TypedEnvelope<proto::InlayHints>,
7794 mut cx: AsyncApp,
7795 ) -> Result<proto::InlayHintsResponse> {
7796 let sender_id = envelope.original_sender_id().unwrap_or_default();
7797 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7798 let buffer = this.update(&mut cx, |this, cx| {
7799 this.buffer_store.read(cx).get_existing(buffer_id)
7800 })??;
7801 buffer
7802 .update(&mut cx, |buffer, _| {
7803 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7804 })?
7805 .await
7806 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
7807
7808 let start = envelope
7809 .payload
7810 .start
7811 .and_then(deserialize_anchor)
7812 .context("missing range start")?;
7813 let end = envelope
7814 .payload
7815 .end
7816 .and_then(deserialize_anchor)
7817 .context("missing range end")?;
7818 let buffer_hints = this
7819 .update(&mut cx, |lsp_store, cx| {
7820 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
7821 })?
7822 .await
7823 .context("inlay hints fetch")?;
7824
7825 this.update(&mut cx, |project, cx| {
7826 InlayHints::response_to_proto(
7827 buffer_hints,
7828 project,
7829 sender_id,
7830 &buffer.read(cx).version(),
7831 cx,
7832 )
7833 })
7834 }
7835
7836 async fn handle_resolve_inlay_hint(
7837 this: Entity<Self>,
7838 envelope: TypedEnvelope<proto::ResolveInlayHint>,
7839 mut cx: AsyncApp,
7840 ) -> Result<proto::ResolveInlayHintResponse> {
7841 let proto_hint = envelope
7842 .payload
7843 .hint
7844 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7845 let hint = InlayHints::proto_to_project_hint(proto_hint)
7846 .context("resolved proto inlay hint conversion")?;
7847 let buffer = this.update(&mut cx, |this, cx| {
7848 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7849 this.buffer_store.read(cx).get_existing(buffer_id)
7850 })??;
7851 let response_hint = this
7852 .update(&mut cx, |this, cx| {
7853 this.resolve_inlay_hint(
7854 hint,
7855 buffer,
7856 LanguageServerId(envelope.payload.language_server_id as usize),
7857 cx,
7858 )
7859 })?
7860 .await
7861 .context("inlay hints fetch")?;
7862 Ok(proto::ResolveInlayHintResponse {
7863 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7864 })
7865 }
7866
7867 async fn handle_refresh_code_lens(
7868 this: Entity<Self>,
7869 _: TypedEnvelope<proto::RefreshCodeLens>,
7870 mut cx: AsyncApp,
7871 ) -> Result<proto::Ack> {
7872 this.update(&mut cx, |_, cx| {
7873 cx.emit(LspStoreEvent::RefreshCodeLens);
7874 })?;
7875 Ok(proto::Ack {})
7876 }
7877
7878 async fn handle_open_buffer_for_symbol(
7879 this: Entity<Self>,
7880 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7881 mut cx: AsyncApp,
7882 ) -> Result<proto::OpenBufferForSymbolResponse> {
7883 let peer_id = envelope.original_sender_id().unwrap_or_default();
7884 let symbol = envelope
7885 .payload
7886 .symbol
7887 .ok_or_else(|| anyhow!("invalid symbol"))?;
7888 let symbol = Self::deserialize_symbol(symbol)?;
7889 let symbol = this.update(&mut cx, |this, _| {
7890 let signature = this.symbol_signature(&symbol.path);
7891 if signature == symbol.signature {
7892 Ok(symbol)
7893 } else {
7894 Err(anyhow!("invalid symbol signature"))
7895 }
7896 })??;
7897 let buffer = this
7898 .update(&mut cx, |this, cx| {
7899 this.open_buffer_for_symbol(
7900 &Symbol {
7901 language_server_name: symbol.language_server_name,
7902 source_worktree_id: symbol.source_worktree_id,
7903 source_language_server_id: symbol.source_language_server_id,
7904 path: symbol.path,
7905 name: symbol.name,
7906 kind: symbol.kind,
7907 range: symbol.range,
7908 signature: symbol.signature,
7909 label: CodeLabel {
7910 text: Default::default(),
7911 runs: Default::default(),
7912 filter_range: Default::default(),
7913 },
7914 },
7915 cx,
7916 )
7917 })?
7918 .await?;
7919
7920 this.update(&mut cx, |this, cx| {
7921 let is_private = buffer
7922 .read(cx)
7923 .file()
7924 .map(|f| f.is_private())
7925 .unwrap_or_default();
7926 if is_private {
7927 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
7928 } else {
7929 this.buffer_store
7930 .update(cx, |buffer_store, cx| {
7931 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
7932 })
7933 .detach_and_log_err(cx);
7934 let buffer_id = buffer.read(cx).remote_id().to_proto();
7935 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
7936 }
7937 })?
7938 }
7939
7940 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7941 let mut hasher = Sha256::new();
7942 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7943 hasher.update(project_path.path.to_string_lossy().as_bytes());
7944 hasher.update(self.nonce.to_be_bytes());
7945 hasher.finalize().as_slice().try_into().unwrap()
7946 }
7947
7948 pub async fn handle_get_project_symbols(
7949 this: Entity<Self>,
7950 envelope: TypedEnvelope<proto::GetProjectSymbols>,
7951 mut cx: AsyncApp,
7952 ) -> Result<proto::GetProjectSymbolsResponse> {
7953 let symbols = this
7954 .update(&mut cx, |this, cx| {
7955 this.symbols(&envelope.payload.query, cx)
7956 })?
7957 .await?;
7958
7959 Ok(proto::GetProjectSymbolsResponse {
7960 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
7961 })
7962 }
7963
7964 pub async fn handle_restart_language_servers(
7965 this: Entity<Self>,
7966 envelope: TypedEnvelope<proto::RestartLanguageServers>,
7967 mut cx: AsyncApp,
7968 ) -> Result<proto::Ack> {
7969 this.update(&mut cx, |this, cx| {
7970 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
7971 this.restart_language_servers_for_buffers(buffers, cx);
7972 })?;
7973
7974 Ok(proto::Ack {})
7975 }
7976
7977 pub async fn handle_stop_language_servers(
7978 this: Entity<Self>,
7979 envelope: TypedEnvelope<proto::StopLanguageServers>,
7980 mut cx: AsyncApp,
7981 ) -> Result<proto::Ack> {
7982 this.update(&mut cx, |this, cx| {
7983 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
7984 this.stop_language_servers_for_buffers(buffers, cx);
7985 })?;
7986
7987 Ok(proto::Ack {})
7988 }
7989
7990 pub async fn handle_cancel_language_server_work(
7991 this: Entity<Self>,
7992 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
7993 mut cx: AsyncApp,
7994 ) -> Result<proto::Ack> {
7995 this.update(&mut cx, |this, cx| {
7996 if let Some(work) = envelope.payload.work {
7997 match work {
7998 proto::cancel_language_server_work::Work::Buffers(buffers) => {
7999 let buffers =
8000 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
8001 this.cancel_language_server_work_for_buffers(buffers, cx);
8002 }
8003 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
8004 let server_id = LanguageServerId::from_proto(work.language_server_id);
8005 this.cancel_language_server_work(server_id, work.token, cx);
8006 }
8007 }
8008 }
8009 })?;
8010
8011 Ok(proto::Ack {})
8012 }
8013
8014 fn buffer_ids_to_buffers(
8015 &mut self,
8016 buffer_ids: impl Iterator<Item = u64>,
8017 cx: &mut Context<Self>,
8018 ) -> Vec<Entity<Buffer>> {
8019 buffer_ids
8020 .into_iter()
8021 .flat_map(|buffer_id| {
8022 self.buffer_store
8023 .read(cx)
8024 .get(BufferId::new(buffer_id).log_err()?)
8025 })
8026 .collect::<Vec<_>>()
8027 }
8028
8029 async fn handle_apply_additional_edits_for_completion(
8030 this: Entity<Self>,
8031 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8032 mut cx: AsyncApp,
8033 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8034 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8035 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8036 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8037 let completion = Self::deserialize_completion(
8038 envelope
8039 .payload
8040 .completion
8041 .ok_or_else(|| anyhow!("invalid completion"))?,
8042 )?;
8043 anyhow::Ok((buffer, completion))
8044 })??;
8045
8046 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8047 this.apply_additional_edits_for_completion(
8048 buffer,
8049 Rc::new(RefCell::new(Box::new([Completion {
8050 replace_range: completion.replace_range,
8051 new_text: completion.new_text,
8052 source: completion.source,
8053 documentation: None,
8054 label: CodeLabel {
8055 text: Default::default(),
8056 runs: Default::default(),
8057 filter_range: Default::default(),
8058 },
8059 insert_text_mode: None,
8060 icon_path: None,
8061 confirm: None,
8062 }]))),
8063 0,
8064 false,
8065 cx,
8066 )
8067 })?;
8068
8069 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8070 transaction: apply_additional_edits
8071 .await?
8072 .as_ref()
8073 .map(language::proto::serialize_transaction),
8074 })
8075 }
8076
8077 pub fn last_formatting_failure(&self) -> Option<&str> {
8078 self.last_formatting_failure.as_deref()
8079 }
8080
8081 pub fn reset_last_formatting_failure(&mut self) {
8082 self.last_formatting_failure = None;
8083 }
8084
8085 pub fn environment_for_buffer(
8086 &self,
8087 buffer: &Entity<Buffer>,
8088 cx: &mut Context<Self>,
8089 ) -> Shared<Task<Option<HashMap<String, String>>>> {
8090 let worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
8091 let worktree_abs_path = worktree_id.and_then(|worktree_id| {
8092 self.worktree_store
8093 .read(cx)
8094 .worktree_for_id(worktree_id, cx)
8095 .map(|entry| entry.read(cx).abs_path().clone())
8096 });
8097
8098 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
8099 environment.update(cx, |env, cx| env.get_environment(worktree_abs_path, cx))
8100 } else {
8101 Task::ready(None).shared()
8102 }
8103 }
8104
8105 pub fn format(
8106 &mut self,
8107 buffers: HashSet<Entity<Buffer>>,
8108 target: LspFormatTarget,
8109 push_to_history: bool,
8110 trigger: FormatTrigger,
8111 cx: &mut Context<Self>,
8112 ) -> Task<anyhow::Result<ProjectTransaction>> {
8113 let logger = zlog::scoped!("format");
8114 if let Some(_) = self.as_local() {
8115 zlog::trace!(logger => "Formatting locally");
8116 let logger = zlog::scoped!(logger => "local");
8117 let buffers = buffers
8118 .into_iter()
8119 .map(|buffer_handle| {
8120 let buffer = buffer_handle.read(cx);
8121 let buffer_abs_path = File::from_dyn(buffer.file())
8122 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
8123
8124 (buffer_handle, buffer_abs_path, buffer.remote_id())
8125 })
8126 .collect::<Vec<_>>();
8127
8128 cx.spawn(async move |lsp_store, cx| {
8129 let mut formattable_buffers = Vec::with_capacity(buffers.len());
8130
8131 for (handle, abs_path, id) in buffers {
8132 let env = lsp_store
8133 .update(cx, |lsp_store, cx| {
8134 lsp_store.environment_for_buffer(&handle, cx)
8135 })?
8136 .await;
8137
8138 let ranges = match &target {
8139 LspFormatTarget::Buffers => None,
8140 LspFormatTarget::Ranges(ranges) => {
8141 let Some(ranges) = ranges.get(&id) else {
8142 return Err(anyhow!("No format ranges provided for buffer"));
8143 };
8144 Some(ranges.clone())
8145 }
8146 };
8147
8148 formattable_buffers.push(FormattableBuffer {
8149 handle,
8150 abs_path,
8151 env,
8152 ranges,
8153 });
8154 }
8155 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
8156
8157 let format_timer = zlog::time!(logger => "Formatting buffers");
8158 let result = LocalLspStore::format_locally(
8159 lsp_store.clone(),
8160 formattable_buffers,
8161 push_to_history,
8162 trigger,
8163 logger,
8164 cx,
8165 )
8166 .await;
8167 format_timer.end();
8168
8169 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
8170
8171 lsp_store.update(cx, |lsp_store, _| {
8172 lsp_store.update_last_formatting_failure(&result);
8173 })?;
8174
8175 result
8176 })
8177 } else if let Some((client, project_id)) = self.upstream_client() {
8178 zlog::trace!(logger => "Formatting remotely");
8179 let logger = zlog::scoped!(logger => "remote");
8180 // Don't support formatting ranges via remote
8181 match target {
8182 LspFormatTarget::Buffers => {}
8183 LspFormatTarget::Ranges(_) => {
8184 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
8185 return Task::ready(Ok(ProjectTransaction::default()));
8186 }
8187 }
8188
8189 let buffer_store = self.buffer_store();
8190 cx.spawn(async move |lsp_store, cx| {
8191 zlog::trace!(logger => "Sending remote format request");
8192 let request_timer = zlog::time!(logger => "remote format request");
8193 let result = client
8194 .request(proto::FormatBuffers {
8195 project_id,
8196 trigger: trigger as i32,
8197 buffer_ids: buffers
8198 .iter()
8199 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
8200 .collect::<Result<_>>()?,
8201 })
8202 .await
8203 .and_then(|result| result.transaction.context("missing transaction"));
8204 request_timer.end();
8205
8206 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
8207
8208 lsp_store.update(cx, |lsp_store, _| {
8209 lsp_store.update_last_formatting_failure(&result);
8210 })?;
8211
8212 let transaction_response = result?;
8213 let _timer = zlog::time!(logger => "deserializing project transaction");
8214 buffer_store
8215 .update(cx, |buffer_store, cx| {
8216 buffer_store.deserialize_project_transaction(
8217 transaction_response,
8218 push_to_history,
8219 cx,
8220 )
8221 })?
8222 .await
8223 })
8224 } else {
8225 zlog::trace!(logger => "Not formatting");
8226 Task::ready(Ok(ProjectTransaction::default()))
8227 }
8228 }
8229
8230 async fn handle_format_buffers(
8231 this: Entity<Self>,
8232 envelope: TypedEnvelope<proto::FormatBuffers>,
8233 mut cx: AsyncApp,
8234 ) -> Result<proto::FormatBuffersResponse> {
8235 let sender_id = envelope.original_sender_id().unwrap_or_default();
8236 let format = this.update(&mut cx, |this, cx| {
8237 let mut buffers = HashSet::default();
8238 for buffer_id in &envelope.payload.buffer_ids {
8239 let buffer_id = BufferId::new(*buffer_id)?;
8240 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8241 }
8242 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8243 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
8244 })??;
8245
8246 let project_transaction = format.await?;
8247 let project_transaction = this.update(&mut cx, |this, cx| {
8248 this.buffer_store.update(cx, |buffer_store, cx| {
8249 buffer_store.serialize_project_transaction_for_peer(
8250 project_transaction,
8251 sender_id,
8252 cx,
8253 )
8254 })
8255 })?;
8256 Ok(proto::FormatBuffersResponse {
8257 transaction: Some(project_transaction),
8258 })
8259 }
8260
8261 async fn handle_apply_code_action_kind(
8262 this: Entity<Self>,
8263 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
8264 mut cx: AsyncApp,
8265 ) -> Result<proto::ApplyCodeActionKindResponse> {
8266 let sender_id = envelope.original_sender_id().unwrap_or_default();
8267 let format = this.update(&mut cx, |this, cx| {
8268 let mut buffers = HashSet::default();
8269 for buffer_id in &envelope.payload.buffer_ids {
8270 let buffer_id = BufferId::new(*buffer_id)?;
8271 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8272 }
8273 let kind = match envelope.payload.kind.as_str() {
8274 "" => Ok(CodeActionKind::EMPTY),
8275 "quickfix" => Ok(CodeActionKind::QUICKFIX),
8276 "refactor" => Ok(CodeActionKind::REFACTOR),
8277 "refactor.extract" => Ok(CodeActionKind::REFACTOR_EXTRACT),
8278 "refactor.inline" => Ok(CodeActionKind::REFACTOR_INLINE),
8279 "refactor.rewrite" => Ok(CodeActionKind::REFACTOR_REWRITE),
8280 "source" => Ok(CodeActionKind::SOURCE),
8281 "source.organizeImports" => Ok(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
8282 "source.fixAll" => Ok(CodeActionKind::SOURCE_FIX_ALL),
8283 _ => Err(anyhow!("Invalid code action kind")),
8284 }?;
8285 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
8286 })??;
8287
8288 let project_transaction = format.await?;
8289 let project_transaction = this.update(&mut cx, |this, cx| {
8290 this.buffer_store.update(cx, |buffer_store, cx| {
8291 buffer_store.serialize_project_transaction_for_peer(
8292 project_transaction,
8293 sender_id,
8294 cx,
8295 )
8296 })
8297 })?;
8298 Ok(proto::ApplyCodeActionKindResponse {
8299 transaction: Some(project_transaction),
8300 })
8301 }
8302
8303 async fn shutdown_language_server(
8304 server_state: Option<LanguageServerState>,
8305 name: LanguageServerName,
8306 cx: &mut AsyncApp,
8307 ) {
8308 let server = match server_state {
8309 Some(LanguageServerState::Starting { startup, .. }) => {
8310 let mut timer = cx
8311 .background_executor()
8312 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
8313 .fuse();
8314
8315 select! {
8316 server = startup.fuse() => server,
8317 _ = timer => {
8318 log::info!(
8319 "timeout waiting for language server {} to finish launching before stopping",
8320 name
8321 );
8322 None
8323 },
8324 }
8325 }
8326
8327 Some(LanguageServerState::Running { server, .. }) => Some(server),
8328
8329 None => None,
8330 };
8331
8332 if let Some(server) = server {
8333 if let Some(shutdown) = server.shutdown() {
8334 shutdown.await;
8335 }
8336 }
8337 }
8338
8339 // Returns a list of all of the worktrees which no longer have a language server and the root path
8340 // for the stopped server
8341 fn stop_local_language_server(
8342 &mut self,
8343 server_id: LanguageServerId,
8344 name: LanguageServerName,
8345 cx: &mut Context<Self>,
8346 ) -> Task<Vec<WorktreeId>> {
8347 let local = match &mut self.mode {
8348 LspStoreMode::Local(local) => local,
8349 _ => {
8350 return Task::ready(Vec::new());
8351 }
8352 };
8353
8354 let mut orphaned_worktrees = vec![];
8355 // Remove this server ID from all entries in the given worktree.
8356 local.language_server_ids.retain(|(worktree, _), ids| {
8357 if !ids.remove(&server_id) {
8358 return true;
8359 }
8360
8361 if ids.is_empty() {
8362 orphaned_worktrees.push(*worktree);
8363 false
8364 } else {
8365 true
8366 }
8367 });
8368 let _ = self.language_server_statuses.remove(&server_id);
8369 log::info!("stopping language server {name}");
8370 self.buffer_store.update(cx, |buffer_store, cx| {
8371 for buffer in buffer_store.buffers() {
8372 buffer.update(cx, |buffer, cx| {
8373 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
8374 buffer.set_completion_triggers(server_id, Default::default(), cx);
8375 });
8376 }
8377 });
8378
8379 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
8380 summaries.retain(|path, summaries_by_server_id| {
8381 if summaries_by_server_id.remove(&server_id).is_some() {
8382 if let Some((client, project_id)) = self.downstream_client.clone() {
8383 client
8384 .send(proto::UpdateDiagnosticSummary {
8385 project_id,
8386 worktree_id: worktree_id.to_proto(),
8387 summary: Some(proto::DiagnosticSummary {
8388 path: path.as_ref().to_proto(),
8389 language_server_id: server_id.0 as u64,
8390 error_count: 0,
8391 warning_count: 0,
8392 }),
8393 })
8394 .log_err();
8395 }
8396 !summaries_by_server_id.is_empty()
8397 } else {
8398 true
8399 }
8400 });
8401 }
8402
8403 let local = self.as_local_mut().unwrap();
8404 for diagnostics in local.diagnostics.values_mut() {
8405 diagnostics.retain(|_, diagnostics_by_server_id| {
8406 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
8407 diagnostics_by_server_id.remove(ix);
8408 !diagnostics_by_server_id.is_empty()
8409 } else {
8410 true
8411 }
8412 });
8413 }
8414 local.language_server_watched_paths.remove(&server_id);
8415 let server_state = local.language_servers.remove(&server_id);
8416 cx.notify();
8417 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
8418 cx.spawn(async move |_, cx| {
8419 Self::shutdown_language_server(server_state, name, cx).await;
8420 orphaned_worktrees
8421 })
8422 }
8423
8424 pub fn restart_language_servers_for_buffers(
8425 &mut self,
8426 buffers: Vec<Entity<Buffer>>,
8427 cx: &mut Context<Self>,
8428 ) {
8429 if let Some((client, project_id)) = self.upstream_client() {
8430 let request = client.request(proto::RestartLanguageServers {
8431 project_id,
8432 buffer_ids: buffers
8433 .into_iter()
8434 .map(|b| b.read(cx).remote_id().to_proto())
8435 .collect(),
8436 });
8437 cx.background_spawn(request).detach_and_log_err(cx);
8438 } else {
8439 let stop_task = self.stop_local_language_servers_for_buffers(&buffers, cx);
8440 cx.spawn(async move |this, cx| {
8441 stop_task.await;
8442 this.update(cx, |this, cx| {
8443 for buffer in buffers {
8444 this.register_buffer_with_language_servers(&buffer, true, cx);
8445 }
8446 })
8447 .ok()
8448 })
8449 .detach();
8450 }
8451 }
8452
8453 pub fn stop_language_servers_for_buffers(
8454 &mut self,
8455 buffers: Vec<Entity<Buffer>>,
8456 cx: &mut Context<Self>,
8457 ) {
8458 if let Some((client, project_id)) = self.upstream_client() {
8459 let request = client.request(proto::StopLanguageServers {
8460 project_id,
8461 buffer_ids: buffers
8462 .into_iter()
8463 .map(|b| b.read(cx).remote_id().to_proto())
8464 .collect(),
8465 });
8466 cx.background_spawn(request).detach_and_log_err(cx);
8467 } else {
8468 self.stop_local_language_servers_for_buffers(&buffers, cx)
8469 .detach();
8470 }
8471 }
8472
8473 fn stop_local_language_servers_for_buffers(
8474 &mut self,
8475 buffers: &[Entity<Buffer>],
8476 cx: &mut Context<Self>,
8477 ) -> Task<()> {
8478 let Some(local) = self.as_local_mut() else {
8479 return Task::ready(());
8480 };
8481 let language_servers_to_stop = buffers
8482 .iter()
8483 .flat_map(|buffer| {
8484 buffer.update(cx, |buffer, cx| {
8485 local.language_server_ids_for_buffer(buffer, cx)
8486 })
8487 })
8488 .collect::<BTreeSet<_>>();
8489 local.lsp_tree.update(cx, |this, _| {
8490 this.remove_nodes(&language_servers_to_stop);
8491 });
8492 let tasks = language_servers_to_stop
8493 .into_iter()
8494 .map(|server| {
8495 let name = self
8496 .language_server_statuses
8497 .get(&server)
8498 .map(|state| state.name.as_str().into())
8499 .unwrap_or_else(|| LanguageServerName::from("Unknown"));
8500 self.stop_local_language_server(server, name, cx)
8501 })
8502 .collect::<Vec<_>>();
8503
8504 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
8505 }
8506
8507 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
8508 let (worktree, relative_path) =
8509 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
8510
8511 let project_path = ProjectPath {
8512 worktree_id: worktree.read(cx).id(),
8513 path: relative_path.into(),
8514 };
8515
8516 Some(
8517 self.buffer_store()
8518 .read(cx)
8519 .get_by_path(&project_path, cx)?
8520 .read(cx),
8521 )
8522 }
8523
8524 pub fn update_diagnostics(
8525 &mut self,
8526 language_server_id: LanguageServerId,
8527 params: lsp::PublishDiagnosticsParams,
8528 disk_based_sources: &[String],
8529 cx: &mut Context<Self>,
8530 ) -> Result<()> {
8531 self.merge_diagnostics(
8532 language_server_id,
8533 params,
8534 disk_based_sources,
8535 |_| false,
8536 cx,
8537 )
8538 }
8539
8540 pub fn merge_diagnostics<F: Fn(&Diagnostic) -> bool + Clone>(
8541 &mut self,
8542 language_server_id: LanguageServerId,
8543 mut params: lsp::PublishDiagnosticsParams,
8544 disk_based_sources: &[String],
8545 filter: F,
8546 cx: &mut Context<Self>,
8547 ) -> Result<()> {
8548 if !self.mode.is_local() {
8549 anyhow::bail!("called update_diagnostics on remote");
8550 }
8551 let abs_path = params
8552 .uri
8553 .to_file_path()
8554 .map_err(|_| anyhow!("URI is not a file"))?;
8555 let mut diagnostics = Vec::default();
8556 let mut primary_diagnostic_group_ids = HashMap::default();
8557 let mut sources_by_group_id = HashMap::default();
8558 let mut supporting_diagnostics = HashMap::default();
8559
8560 // Ensure that primary diagnostics are always the most severe
8561 params.diagnostics.sort_by_key(|item| item.severity);
8562
8563 for diagnostic in ¶ms.diagnostics {
8564 let source = diagnostic.source.as_ref();
8565 let range = range_from_lsp(diagnostic.range);
8566 let is_supporting = diagnostic
8567 .related_information
8568 .as_ref()
8569 .map_or(false, |infos| {
8570 infos.iter().any(|info| {
8571 primary_diagnostic_group_ids.contains_key(&(
8572 source,
8573 diagnostic.code.clone(),
8574 range_from_lsp(info.location.range),
8575 ))
8576 })
8577 });
8578
8579 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
8580 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
8581 });
8582
8583 if is_supporting {
8584 supporting_diagnostics.insert(
8585 (source, diagnostic.code.clone(), range),
8586 (diagnostic.severity, is_unnecessary),
8587 );
8588 } else {
8589 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
8590 let is_disk_based =
8591 source.map_or(false, |source| disk_based_sources.contains(source));
8592
8593 sources_by_group_id.insert(group_id, source);
8594 primary_diagnostic_group_ids
8595 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
8596
8597 diagnostics.push(DiagnosticEntry {
8598 range,
8599 diagnostic: Diagnostic {
8600 source: diagnostic.source.clone(),
8601 code: diagnostic.code.clone(),
8602 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
8603 message: diagnostic.message.trim().to_string(),
8604 group_id,
8605 is_primary: true,
8606 is_disk_based,
8607 is_unnecessary,
8608 data: diagnostic.data.clone(),
8609 },
8610 });
8611 if let Some(infos) = &diagnostic.related_information {
8612 for info in infos {
8613 if info.location.uri == params.uri && !info.message.is_empty() {
8614 let range = range_from_lsp(info.location.range);
8615 diagnostics.push(DiagnosticEntry {
8616 range,
8617 diagnostic: Diagnostic {
8618 source: diagnostic.source.clone(),
8619 code: diagnostic.code.clone(),
8620 severity: DiagnosticSeverity::INFORMATION,
8621 message: info.message.trim().to_string(),
8622 group_id,
8623 is_primary: false,
8624 is_disk_based,
8625 is_unnecessary: false,
8626 data: diagnostic.data.clone(),
8627 },
8628 });
8629 }
8630 }
8631 }
8632 }
8633 }
8634
8635 for entry in &mut diagnostics {
8636 let diagnostic = &mut entry.diagnostic;
8637 if !diagnostic.is_primary {
8638 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
8639 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
8640 source,
8641 diagnostic.code.clone(),
8642 entry.range.clone(),
8643 )) {
8644 if let Some(severity) = severity {
8645 diagnostic.severity = severity;
8646 }
8647 diagnostic.is_unnecessary = is_unnecessary;
8648 }
8649 }
8650 }
8651
8652 self.merge_diagnostic_entries(
8653 language_server_id,
8654 abs_path,
8655 params.version,
8656 diagnostics,
8657 filter,
8658 cx,
8659 )?;
8660 Ok(())
8661 }
8662
8663 fn insert_newly_running_language_server(
8664 &mut self,
8665 adapter: Arc<CachedLspAdapter>,
8666 language_server: Arc<LanguageServer>,
8667 server_id: LanguageServerId,
8668 key: (WorktreeId, LanguageServerName),
8669 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
8670 cx: &mut Context<Self>,
8671 ) {
8672 let Some(local) = self.as_local_mut() else {
8673 return;
8674 };
8675 // If the language server for this key doesn't match the server id, don't store the
8676 // server. Which will cause it to be dropped, killing the process
8677 if local
8678 .language_server_ids
8679 .get(&key)
8680 .map(|ids| !ids.contains(&server_id))
8681 .unwrap_or(false)
8682 {
8683 return;
8684 }
8685
8686 // Update language_servers collection with Running variant of LanguageServerState
8687 // indicating that the server is up and running and ready
8688 let workspace_folders = workspace_folders.lock().clone();
8689 local.language_servers.insert(
8690 server_id,
8691 LanguageServerState::running(
8692 workspace_folders,
8693 adapter.clone(),
8694 language_server.clone(),
8695 None,
8696 ),
8697 );
8698 if let Some(file_ops_caps) = language_server
8699 .capabilities()
8700 .workspace
8701 .as_ref()
8702 .and_then(|ws| ws.file_operations.as_ref())
8703 {
8704 let did_rename_caps = file_ops_caps.did_rename.as_ref();
8705 let will_rename_caps = file_ops_caps.will_rename.as_ref();
8706 if did_rename_caps.or(will_rename_caps).is_some() {
8707 let watcher = RenamePathsWatchedForServer::default()
8708 .with_did_rename_patterns(did_rename_caps)
8709 .with_will_rename_patterns(will_rename_caps);
8710 local
8711 .language_server_paths_watched_for_rename
8712 .insert(server_id, watcher);
8713 }
8714 }
8715
8716 self.language_server_statuses.insert(
8717 server_id,
8718 LanguageServerStatus {
8719 name: language_server.name().to_string(),
8720 pending_work: Default::default(),
8721 has_pending_diagnostic_updates: false,
8722 progress_tokens: Default::default(),
8723 },
8724 );
8725
8726 cx.emit(LspStoreEvent::LanguageServerAdded(
8727 server_id,
8728 language_server.name(),
8729 Some(key.0),
8730 ));
8731 cx.emit(LspStoreEvent::RefreshInlayHints);
8732
8733 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
8734 downstream_client
8735 .send(proto::StartLanguageServer {
8736 project_id: *project_id,
8737 server: Some(proto::LanguageServer {
8738 id: server_id.0 as u64,
8739 name: language_server.name().to_string(),
8740 worktree_id: Some(key.0.to_proto()),
8741 }),
8742 })
8743 .log_err();
8744 }
8745
8746 // Tell the language server about every open buffer in the worktree that matches the language.
8747 self.buffer_store.clone().update(cx, |buffer_store, cx| {
8748 for buffer_handle in buffer_store.buffers() {
8749 let buffer = buffer_handle.read(cx);
8750 let file = match File::from_dyn(buffer.file()) {
8751 Some(file) => file,
8752 None => continue,
8753 };
8754 let language = match buffer.language() {
8755 Some(language) => language,
8756 None => continue,
8757 };
8758
8759 if file.worktree.read(cx).id() != key.0
8760 || !self
8761 .languages
8762 .lsp_adapters(&language.name())
8763 .iter()
8764 .any(|a| a.name == key.1)
8765 {
8766 continue;
8767 }
8768 // didOpen
8769 let file = match file.as_local() {
8770 Some(file) => file,
8771 None => continue,
8772 };
8773
8774 let local = self.as_local_mut().unwrap();
8775
8776 if local.registered_buffers.contains_key(&buffer.remote_id()) {
8777 let versions = local
8778 .buffer_snapshots
8779 .entry(buffer.remote_id())
8780 .or_default()
8781 .entry(server_id)
8782 .and_modify(|_| {
8783 assert!(
8784 false,
8785 "There should not be an existing snapshot for a newly inserted buffer"
8786 )
8787 })
8788 .or_insert_with(|| {
8789 vec![LspBufferSnapshot {
8790 version: 0,
8791 snapshot: buffer.text_snapshot(),
8792 }]
8793 });
8794
8795 let snapshot = versions.last().unwrap();
8796 let version = snapshot.version;
8797 let initial_snapshot = &snapshot.snapshot;
8798 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
8799 language_server.register_buffer(
8800 uri,
8801 adapter.language_id(&language.name()),
8802 version,
8803 initial_snapshot.text(),
8804 );
8805 }
8806 buffer_handle.update(cx, |buffer, cx| {
8807 buffer.set_completion_triggers(
8808 server_id,
8809 language_server
8810 .capabilities()
8811 .completion_provider
8812 .as_ref()
8813 .and_then(|provider| {
8814 provider
8815 .trigger_characters
8816 .as_ref()
8817 .map(|characters| characters.iter().cloned().collect())
8818 })
8819 .unwrap_or_default(),
8820 cx,
8821 )
8822 });
8823 }
8824 });
8825
8826 cx.notify();
8827 }
8828
8829 pub fn language_servers_running_disk_based_diagnostics(
8830 &self,
8831 ) -> impl Iterator<Item = LanguageServerId> + '_ {
8832 self.language_server_statuses
8833 .iter()
8834 .filter_map(|(id, status)| {
8835 if status.has_pending_diagnostic_updates {
8836 Some(*id)
8837 } else {
8838 None
8839 }
8840 })
8841 }
8842
8843 pub(crate) fn cancel_language_server_work_for_buffers(
8844 &mut self,
8845 buffers: impl IntoIterator<Item = Entity<Buffer>>,
8846 cx: &mut Context<Self>,
8847 ) {
8848 if let Some((client, project_id)) = self.upstream_client() {
8849 let request = client.request(proto::CancelLanguageServerWork {
8850 project_id,
8851 work: Some(proto::cancel_language_server_work::Work::Buffers(
8852 proto::cancel_language_server_work::Buffers {
8853 buffer_ids: buffers
8854 .into_iter()
8855 .map(|b| b.read(cx).remote_id().to_proto())
8856 .collect(),
8857 },
8858 )),
8859 });
8860 cx.background_spawn(request).detach_and_log_err(cx);
8861 } else if let Some(local) = self.as_local() {
8862 let servers = buffers
8863 .into_iter()
8864 .flat_map(|buffer| {
8865 buffer.update(cx, |buffer, cx| {
8866 local.language_server_ids_for_buffer(buffer, cx).into_iter()
8867 })
8868 })
8869 .collect::<HashSet<_>>();
8870 for server_id in servers {
8871 self.cancel_language_server_work(server_id, None, cx);
8872 }
8873 }
8874 }
8875
8876 pub(crate) fn cancel_language_server_work(
8877 &mut self,
8878 server_id: LanguageServerId,
8879 token_to_cancel: Option<String>,
8880 cx: &mut Context<Self>,
8881 ) {
8882 if let Some(local) = self.as_local() {
8883 let status = self.language_server_statuses.get(&server_id);
8884 let server = local.language_servers.get(&server_id);
8885 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
8886 {
8887 for (token, progress) in &status.pending_work {
8888 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
8889 if token != token_to_cancel {
8890 continue;
8891 }
8892 }
8893 if progress.is_cancellable {
8894 server
8895 .notify::<lsp::notification::WorkDoneProgressCancel>(
8896 &WorkDoneProgressCancelParams {
8897 token: lsp::NumberOrString::String(token.clone()),
8898 },
8899 )
8900 .ok();
8901 }
8902 }
8903 }
8904 } else if let Some((client, project_id)) = self.upstream_client() {
8905 let request = client.request(proto::CancelLanguageServerWork {
8906 project_id,
8907 work: Some(
8908 proto::cancel_language_server_work::Work::LanguageServerWork(
8909 proto::cancel_language_server_work::LanguageServerWork {
8910 language_server_id: server_id.to_proto(),
8911 token: token_to_cancel,
8912 },
8913 ),
8914 ),
8915 });
8916 cx.background_spawn(request).detach_and_log_err(cx);
8917 }
8918 }
8919
8920 fn register_supplementary_language_server(
8921 &mut self,
8922 id: LanguageServerId,
8923 name: LanguageServerName,
8924 server: Arc<LanguageServer>,
8925 cx: &mut Context<Self>,
8926 ) {
8927 if let Some(local) = self.as_local_mut() {
8928 local
8929 .supplementary_language_servers
8930 .insert(id, (name.clone(), server));
8931 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
8932 }
8933 }
8934
8935 fn unregister_supplementary_language_server(
8936 &mut self,
8937 id: LanguageServerId,
8938 cx: &mut Context<Self>,
8939 ) {
8940 if let Some(local) = self.as_local_mut() {
8941 local.supplementary_language_servers.remove(&id);
8942 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
8943 }
8944 }
8945
8946 pub(crate) fn supplementary_language_servers(
8947 &self,
8948 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
8949 self.as_local().into_iter().flat_map(|local| {
8950 local
8951 .supplementary_language_servers
8952 .iter()
8953 .map(|(id, (name, _))| (*id, name.clone()))
8954 })
8955 }
8956
8957 pub fn language_server_adapter_for_id(
8958 &self,
8959 id: LanguageServerId,
8960 ) -> Option<Arc<CachedLspAdapter>> {
8961 self.as_local()
8962 .and_then(|local| local.language_servers.get(&id))
8963 .and_then(|language_server_state| match language_server_state {
8964 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
8965 _ => None,
8966 })
8967 }
8968
8969 pub(super) fn update_local_worktree_language_servers(
8970 &mut self,
8971 worktree_handle: &Entity<Worktree>,
8972 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
8973 cx: &mut Context<Self>,
8974 ) {
8975 if changes.is_empty() {
8976 return;
8977 }
8978
8979 let Some(local) = self.as_local() else { return };
8980
8981 local.prettier_store.update(cx, |prettier_store, cx| {
8982 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
8983 });
8984
8985 let worktree_id = worktree_handle.read(cx).id();
8986 let mut language_server_ids = local
8987 .language_server_ids
8988 .iter()
8989 .flat_map(|((server_worktree, _), server_ids)| {
8990 server_ids
8991 .iter()
8992 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
8993 })
8994 .collect::<Vec<_>>();
8995 language_server_ids.sort();
8996 language_server_ids.dedup();
8997
8998 let abs_path = worktree_handle.read(cx).abs_path();
8999 for server_id in &language_server_ids {
9000 if let Some(LanguageServerState::Running { server, .. }) =
9001 local.language_servers.get(server_id)
9002 {
9003 if let Some(watched_paths) = local
9004 .language_server_watched_paths
9005 .get(server_id)
9006 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
9007 {
9008 let params = lsp::DidChangeWatchedFilesParams {
9009 changes: changes
9010 .iter()
9011 .filter_map(|(path, _, change)| {
9012 if !watched_paths.is_match(path) {
9013 return None;
9014 }
9015 let typ = match change {
9016 PathChange::Loaded => return None,
9017 PathChange::Added => lsp::FileChangeType::CREATED,
9018 PathChange::Removed => lsp::FileChangeType::DELETED,
9019 PathChange::Updated => lsp::FileChangeType::CHANGED,
9020 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
9021 };
9022 Some(lsp::FileEvent {
9023 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
9024 typ,
9025 })
9026 })
9027 .collect(),
9028 };
9029 if !params.changes.is_empty() {
9030 server
9031 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
9032 .log_err();
9033 }
9034 }
9035 }
9036 }
9037 }
9038
9039 pub fn wait_for_remote_buffer(
9040 &mut self,
9041 id: BufferId,
9042 cx: &mut Context<Self>,
9043 ) -> Task<Result<Entity<Buffer>>> {
9044 self.buffer_store.update(cx, |buffer_store, cx| {
9045 buffer_store.wait_for_remote_buffer(id, cx)
9046 })
9047 }
9048
9049 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9050 proto::Symbol {
9051 language_server_name: symbol.language_server_name.0.to_string(),
9052 source_worktree_id: symbol.source_worktree_id.to_proto(),
9053 language_server_id: symbol.source_language_server_id.to_proto(),
9054 worktree_id: symbol.path.worktree_id.to_proto(),
9055 path: symbol.path.path.as_ref().to_proto(),
9056 name: symbol.name.clone(),
9057 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
9058 start: Some(proto::PointUtf16 {
9059 row: symbol.range.start.0.row,
9060 column: symbol.range.start.0.column,
9061 }),
9062 end: Some(proto::PointUtf16 {
9063 row: symbol.range.end.0.row,
9064 column: symbol.range.end.0.column,
9065 }),
9066 signature: symbol.signature.to_vec(),
9067 }
9068 }
9069
9070 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
9071 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
9072 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
9073 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
9074 let path = ProjectPath {
9075 worktree_id,
9076 path: Arc::<Path>::from_proto(serialized_symbol.path),
9077 };
9078
9079 let start = serialized_symbol
9080 .start
9081 .ok_or_else(|| anyhow!("invalid start"))?;
9082 let end = serialized_symbol
9083 .end
9084 .ok_or_else(|| anyhow!("invalid end"))?;
9085 Ok(CoreSymbol {
9086 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
9087 source_worktree_id,
9088 source_language_server_id: LanguageServerId::from_proto(
9089 serialized_symbol.language_server_id,
9090 ),
9091 path,
9092 name: serialized_symbol.name,
9093 range: Unclipped(PointUtf16::new(start.row, start.column))
9094 ..Unclipped(PointUtf16::new(end.row, end.column)),
9095 kind,
9096 signature: serialized_symbol
9097 .signature
9098 .try_into()
9099 .map_err(|_| anyhow!("invalid signature"))?,
9100 })
9101 }
9102
9103 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
9104 let mut serialized_completion = proto::Completion {
9105 old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
9106 old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
9107 new_text: completion.new_text.clone(),
9108 ..proto::Completion::default()
9109 };
9110 match &completion.source {
9111 CompletionSource::Lsp {
9112 insert_range,
9113 server_id,
9114 lsp_completion,
9115 lsp_defaults,
9116 resolved,
9117 } => {
9118 let (old_insert_start, old_insert_end) = insert_range
9119 .as_ref()
9120 .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
9121 .unzip();
9122
9123 serialized_completion.old_insert_start = old_insert_start;
9124 serialized_completion.old_insert_end = old_insert_end;
9125 serialized_completion.source = proto::completion::Source::Lsp as i32;
9126 serialized_completion.server_id = server_id.0 as u64;
9127 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
9128 serialized_completion.lsp_defaults = lsp_defaults
9129 .as_deref()
9130 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
9131 serialized_completion.resolved = *resolved;
9132 }
9133 CompletionSource::BufferWord {
9134 word_range,
9135 resolved,
9136 } => {
9137 serialized_completion.source = proto::completion::Source::BufferWord as i32;
9138 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
9139 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
9140 serialized_completion.resolved = *resolved;
9141 }
9142 CompletionSource::Custom => {
9143 serialized_completion.source = proto::completion::Source::Custom as i32;
9144 serialized_completion.resolved = true;
9145 }
9146 }
9147
9148 serialized_completion
9149 }
9150
9151 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
9152 let old_replace_start = completion
9153 .old_replace_start
9154 .and_then(deserialize_anchor)
9155 .context("invalid old start")?;
9156 let old_replace_end = completion
9157 .old_replace_end
9158 .and_then(deserialize_anchor)
9159 .context("invalid old end")?;
9160 let insert_range = {
9161 match completion.old_insert_start.zip(completion.old_insert_end) {
9162 Some((start, end)) => {
9163 let start = deserialize_anchor(start).context("invalid insert old start")?;
9164 let end = deserialize_anchor(end).context("invalid insert old end")?;
9165 Some(start..end)
9166 }
9167 None => None,
9168 }
9169 };
9170 Ok(CoreCompletion {
9171 replace_range: old_replace_start..old_replace_end,
9172 new_text: completion.new_text,
9173 source: match proto::completion::Source::from_i32(completion.source) {
9174 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
9175 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
9176 insert_range,
9177 server_id: LanguageServerId::from_proto(completion.server_id),
9178 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
9179 lsp_defaults: completion
9180 .lsp_defaults
9181 .as_deref()
9182 .map(serde_json::from_slice)
9183 .transpose()?,
9184 resolved: completion.resolved,
9185 },
9186 Some(proto::completion::Source::BufferWord) => {
9187 let word_range = completion
9188 .buffer_word_start
9189 .and_then(deserialize_anchor)
9190 .context("invalid buffer word start")?
9191 ..completion
9192 .buffer_word_end
9193 .and_then(deserialize_anchor)
9194 .context("invalid buffer word end")?;
9195 CompletionSource::BufferWord {
9196 word_range,
9197 resolved: completion.resolved,
9198 }
9199 }
9200 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
9201 },
9202 })
9203 }
9204
9205 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
9206 let (kind, lsp_action) = match &action.lsp_action {
9207 LspAction::Action(code_action) => (
9208 proto::code_action::Kind::Action as i32,
9209 serde_json::to_vec(code_action).unwrap(),
9210 ),
9211 LspAction::Command(command) => (
9212 proto::code_action::Kind::Command as i32,
9213 serde_json::to_vec(command).unwrap(),
9214 ),
9215 LspAction::CodeLens(code_lens) => (
9216 proto::code_action::Kind::CodeLens as i32,
9217 serde_json::to_vec(code_lens).unwrap(),
9218 ),
9219 };
9220
9221 proto::CodeAction {
9222 server_id: action.server_id.0 as u64,
9223 start: Some(serialize_anchor(&action.range.start)),
9224 end: Some(serialize_anchor(&action.range.end)),
9225 lsp_action,
9226 kind,
9227 resolved: action.resolved,
9228 }
9229 }
9230
9231 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
9232 let start = action
9233 .start
9234 .and_then(deserialize_anchor)
9235 .context("invalid start")?;
9236 let end = action
9237 .end
9238 .and_then(deserialize_anchor)
9239 .context("invalid end")?;
9240 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
9241 Some(proto::code_action::Kind::Action) => {
9242 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
9243 }
9244 Some(proto::code_action::Kind::Command) => {
9245 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
9246 }
9247 Some(proto::code_action::Kind::CodeLens) => {
9248 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
9249 }
9250 None => anyhow::bail!("Unknown action kind {}", action.kind),
9251 };
9252 Ok(CodeAction {
9253 server_id: LanguageServerId(action.server_id as usize),
9254 range: start..end,
9255 resolved: action.resolved,
9256 lsp_action,
9257 })
9258 }
9259
9260 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
9261 match &formatting_result {
9262 Ok(_) => self.last_formatting_failure = None,
9263 Err(error) => {
9264 let error_string = format!("{error:#}");
9265 log::error!("Formatting failed: {error_string}");
9266 self.last_formatting_failure
9267 .replace(error_string.lines().join(" "));
9268 }
9269 }
9270 }
9271}
9272
9273fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
9274 let CompletionSource::BufferWord {
9275 word_range,
9276 resolved,
9277 } = &mut completion.source
9278 else {
9279 return;
9280 };
9281 if *resolved {
9282 return;
9283 }
9284
9285 if completion.new_text
9286 != snapshot
9287 .text_for_range(word_range.clone())
9288 .collect::<String>()
9289 {
9290 return;
9291 }
9292
9293 let mut offset = 0;
9294 for chunk in snapshot.chunks(word_range.clone(), true) {
9295 let end_offset = offset + chunk.text.len();
9296 if let Some(highlight_id) = chunk.syntax_highlight_id {
9297 completion
9298 .label
9299 .runs
9300 .push((offset..end_offset, highlight_id));
9301 }
9302 offset = end_offset;
9303 }
9304 *resolved = true;
9305}
9306
9307impl EventEmitter<LspStoreEvent> for LspStore {}
9308
9309fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
9310 hover
9311 .contents
9312 .retain(|hover_block| !hover_block.text.trim().is_empty());
9313 if hover.contents.is_empty() {
9314 None
9315 } else {
9316 Some(hover)
9317 }
9318}
9319
9320async fn populate_labels_for_completions(
9321 new_completions: Vec<CoreCompletion>,
9322 language: Option<Arc<Language>>,
9323 lsp_adapter: Option<Arc<CachedLspAdapter>>,
9324 completions: &mut Vec<Completion>,
9325) {
9326 let lsp_completions = new_completions
9327 .iter()
9328 .filter_map(|new_completion| {
9329 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
9330 Some(lsp_completion.into_owned())
9331 } else {
9332 None
9333 }
9334 })
9335 .collect::<Vec<_>>();
9336
9337 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
9338 lsp_adapter
9339 .labels_for_completions(&lsp_completions, language)
9340 .await
9341 .log_err()
9342 .unwrap_or_default()
9343 } else {
9344 Vec::new()
9345 }
9346 .into_iter()
9347 .fuse();
9348
9349 for completion in new_completions {
9350 match completion.source.lsp_completion(true) {
9351 Some(lsp_completion) => {
9352 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
9353 Some(docs.into())
9354 } else {
9355 None
9356 };
9357
9358 let mut label = labels.next().flatten().unwrap_or_else(|| {
9359 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
9360 });
9361 ensure_uniform_list_compatible_label(&mut label);
9362 completions.push(Completion {
9363 label,
9364 documentation,
9365 replace_range: completion.replace_range,
9366 new_text: completion.new_text,
9367 insert_text_mode: lsp_completion.insert_text_mode,
9368 source: completion.source,
9369 icon_path: None,
9370 confirm: None,
9371 });
9372 }
9373 None => {
9374 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
9375 ensure_uniform_list_compatible_label(&mut label);
9376 completions.push(Completion {
9377 label,
9378 documentation: None,
9379 replace_range: completion.replace_range,
9380 new_text: completion.new_text,
9381 source: completion.source,
9382 insert_text_mode: None,
9383 icon_path: None,
9384 confirm: None,
9385 });
9386 }
9387 }
9388 }
9389}
9390
9391#[derive(Debug)]
9392pub enum LanguageServerToQuery {
9393 /// Query language servers in order of users preference, up until one capable of handling the request is found.
9394 FirstCapable,
9395 /// Query a specific language server.
9396 Other(LanguageServerId),
9397}
9398
9399#[derive(Default)]
9400struct RenamePathsWatchedForServer {
9401 did_rename: Vec<RenameActionPredicate>,
9402 will_rename: Vec<RenameActionPredicate>,
9403}
9404
9405impl RenamePathsWatchedForServer {
9406 fn with_did_rename_patterns(
9407 mut self,
9408 did_rename: Option<&FileOperationRegistrationOptions>,
9409 ) -> Self {
9410 if let Some(did_rename) = did_rename {
9411 self.did_rename = did_rename
9412 .filters
9413 .iter()
9414 .filter_map(|filter| filter.try_into().log_err())
9415 .collect();
9416 }
9417 self
9418 }
9419 fn with_will_rename_patterns(
9420 mut self,
9421 will_rename: Option<&FileOperationRegistrationOptions>,
9422 ) -> Self {
9423 if let Some(will_rename) = will_rename {
9424 self.will_rename = will_rename
9425 .filters
9426 .iter()
9427 .filter_map(|filter| filter.try_into().log_err())
9428 .collect();
9429 }
9430 self
9431 }
9432
9433 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
9434 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
9435 }
9436 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
9437 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
9438 }
9439}
9440
9441impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
9442 type Error = globset::Error;
9443 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
9444 Ok(Self {
9445 kind: ops.pattern.matches.clone(),
9446 glob: GlobBuilder::new(&ops.pattern.glob)
9447 .case_insensitive(
9448 ops.pattern
9449 .options
9450 .as_ref()
9451 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
9452 )
9453 .build()?
9454 .compile_matcher(),
9455 })
9456 }
9457}
9458struct RenameActionPredicate {
9459 glob: GlobMatcher,
9460 kind: Option<FileOperationPatternKind>,
9461}
9462
9463impl RenameActionPredicate {
9464 // Returns true if language server should be notified
9465 fn eval(&self, path: &str, is_dir: bool) -> bool {
9466 self.kind.as_ref().map_or(true, |kind| {
9467 let expected_kind = if is_dir {
9468 FileOperationPatternKind::Folder
9469 } else {
9470 FileOperationPatternKind::File
9471 };
9472 kind == &expected_kind
9473 }) && self.glob.is_match(path)
9474 }
9475}
9476
9477#[derive(Default)]
9478struct LanguageServerWatchedPaths {
9479 worktree_paths: HashMap<WorktreeId, GlobSet>,
9480 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
9481}
9482
9483#[derive(Default)]
9484struct LanguageServerWatchedPathsBuilder {
9485 worktree_paths: HashMap<WorktreeId, GlobSet>,
9486 abs_paths: HashMap<Arc<Path>, GlobSet>,
9487}
9488
9489impl LanguageServerWatchedPathsBuilder {
9490 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
9491 self.worktree_paths.insert(worktree_id, glob_set);
9492 }
9493 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
9494 self.abs_paths.insert(path, glob_set);
9495 }
9496 fn build(
9497 self,
9498 fs: Arc<dyn Fs>,
9499 language_server_id: LanguageServerId,
9500 cx: &mut Context<LspStore>,
9501 ) -> LanguageServerWatchedPaths {
9502 let project = cx.weak_entity();
9503
9504 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
9505 let abs_paths = self
9506 .abs_paths
9507 .into_iter()
9508 .map(|(abs_path, globset)| {
9509 let task = cx.spawn({
9510 let abs_path = abs_path.clone();
9511 let fs = fs.clone();
9512
9513 let lsp_store = project.clone();
9514 async move |_, cx| {
9515 maybe!(async move {
9516 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
9517 while let Some(update) = push_updates.0.next().await {
9518 let action = lsp_store
9519 .update(cx, |this, _| {
9520 let Some(local) = this.as_local() else {
9521 return ControlFlow::Break(());
9522 };
9523 let Some(watcher) = local
9524 .language_server_watched_paths
9525 .get(&language_server_id)
9526 else {
9527 return ControlFlow::Break(());
9528 };
9529 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
9530 "Watched abs path is not registered with a watcher",
9531 );
9532 let matching_entries = update
9533 .into_iter()
9534 .filter(|event| globs.is_match(&event.path))
9535 .collect::<Vec<_>>();
9536 this.lsp_notify_abs_paths_changed(
9537 language_server_id,
9538 matching_entries,
9539 );
9540 ControlFlow::Continue(())
9541 })
9542 .ok()?;
9543
9544 if action.is_break() {
9545 break;
9546 }
9547 }
9548 Some(())
9549 })
9550 .await;
9551 }
9552 });
9553 (abs_path, (globset, task))
9554 })
9555 .collect();
9556 LanguageServerWatchedPaths {
9557 worktree_paths: self.worktree_paths,
9558 abs_paths,
9559 }
9560 }
9561}
9562
9563struct LspBufferSnapshot {
9564 version: i32,
9565 snapshot: TextBufferSnapshot,
9566}
9567
9568/// A prompt requested by LSP server.
9569#[derive(Clone, Debug)]
9570pub struct LanguageServerPromptRequest {
9571 pub level: PromptLevel,
9572 pub message: String,
9573 pub actions: Vec<MessageActionItem>,
9574 pub lsp_name: String,
9575 pub(crate) response_channel: Sender<MessageActionItem>,
9576}
9577
9578impl LanguageServerPromptRequest {
9579 pub async fn respond(self, index: usize) -> Option<()> {
9580 if let Some(response) = self.actions.into_iter().nth(index) {
9581 self.response_channel.send(response).await.ok()
9582 } else {
9583 None
9584 }
9585 }
9586}
9587impl PartialEq for LanguageServerPromptRequest {
9588 fn eq(&self, other: &Self) -> bool {
9589 self.message == other.message && self.actions == other.actions
9590 }
9591}
9592
9593#[derive(Clone, Debug, PartialEq)]
9594pub enum LanguageServerLogType {
9595 Log(MessageType),
9596 Trace(Option<String>),
9597}
9598
9599impl LanguageServerLogType {
9600 pub fn to_proto(&self) -> proto::language_server_log::LogType {
9601 match self {
9602 Self::Log(log_type) => {
9603 let message_type = match *log_type {
9604 MessageType::ERROR => 1,
9605 MessageType::WARNING => 2,
9606 MessageType::INFO => 3,
9607 MessageType::LOG => 4,
9608 other => {
9609 log::warn!("Unknown lsp log message type: {:?}", other);
9610 4
9611 }
9612 };
9613 proto::language_server_log::LogType::LogMessageType(message_type)
9614 }
9615 Self::Trace(message) => {
9616 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
9617 message: message.clone(),
9618 })
9619 }
9620 }
9621 }
9622
9623 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
9624 match log_type {
9625 proto::language_server_log::LogType::LogMessageType(message_type) => {
9626 Self::Log(match message_type {
9627 1 => MessageType::ERROR,
9628 2 => MessageType::WARNING,
9629 3 => MessageType::INFO,
9630 4 => MessageType::LOG,
9631 _ => MessageType::LOG,
9632 })
9633 }
9634 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
9635 }
9636 }
9637}
9638
9639pub enum LanguageServerState {
9640 Starting {
9641 startup: Task<Option<Arc<LanguageServer>>>,
9642 /// List of language servers that will be added to the workspace once it's initialization completes.
9643 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
9644 },
9645
9646 Running {
9647 adapter: Arc<CachedLspAdapter>,
9648 server: Arc<LanguageServer>,
9649 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
9650 },
9651}
9652
9653impl LanguageServerState {
9654 fn add_workspace_folder(&self, uri: Url) {
9655 match self {
9656 LanguageServerState::Starting {
9657 pending_workspace_folders,
9658 ..
9659 } => {
9660 pending_workspace_folders.lock().insert(uri);
9661 }
9662 LanguageServerState::Running { server, .. } => {
9663 server.add_workspace_folder(uri);
9664 }
9665 }
9666 }
9667 fn _remove_workspace_folder(&self, uri: Url) {
9668 match self {
9669 LanguageServerState::Starting {
9670 pending_workspace_folders,
9671 ..
9672 } => {
9673 pending_workspace_folders.lock().remove(&uri);
9674 }
9675 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
9676 }
9677 }
9678 fn running(
9679 workspace_folders: BTreeSet<Url>,
9680 adapter: Arc<CachedLspAdapter>,
9681 server: Arc<LanguageServer>,
9682 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
9683 ) -> Self {
9684 server.set_workspace_folders(workspace_folders);
9685 Self::Running {
9686 adapter,
9687 server,
9688 simulate_disk_based_diagnostics_completion,
9689 }
9690 }
9691}
9692
9693impl std::fmt::Debug for LanguageServerState {
9694 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9695 match self {
9696 LanguageServerState::Starting { .. } => {
9697 f.debug_struct("LanguageServerState::Starting").finish()
9698 }
9699 LanguageServerState::Running { .. } => {
9700 f.debug_struct("LanguageServerState::Running").finish()
9701 }
9702 }
9703 }
9704}
9705
9706#[derive(Clone, Debug, Serialize)]
9707pub struct LanguageServerProgress {
9708 pub is_disk_based_diagnostics_progress: bool,
9709 pub is_cancellable: bool,
9710 pub title: Option<String>,
9711 pub message: Option<String>,
9712 pub percentage: Option<usize>,
9713 #[serde(skip_serializing)]
9714 pub last_update_at: Instant,
9715}
9716
9717#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
9718pub struct DiagnosticSummary {
9719 pub error_count: usize,
9720 pub warning_count: usize,
9721}
9722
9723impl DiagnosticSummary {
9724 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
9725 let mut this = Self {
9726 error_count: 0,
9727 warning_count: 0,
9728 };
9729
9730 for entry in diagnostics {
9731 if entry.diagnostic.is_primary {
9732 match entry.diagnostic.severity {
9733 DiagnosticSeverity::ERROR => this.error_count += 1,
9734 DiagnosticSeverity::WARNING => this.warning_count += 1,
9735 _ => {}
9736 }
9737 }
9738 }
9739
9740 this
9741 }
9742
9743 pub fn is_empty(&self) -> bool {
9744 self.error_count == 0 && self.warning_count == 0
9745 }
9746
9747 pub fn to_proto(
9748 &self,
9749 language_server_id: LanguageServerId,
9750 path: &Path,
9751 ) -> proto::DiagnosticSummary {
9752 proto::DiagnosticSummary {
9753 path: path.to_proto(),
9754 language_server_id: language_server_id.0 as u64,
9755 error_count: self.error_count as u32,
9756 warning_count: self.warning_count as u32,
9757 }
9758 }
9759}
9760
9761#[derive(Clone, Debug)]
9762pub enum CompletionDocumentation {
9763 /// There is no documentation for this completion.
9764 Undocumented,
9765 /// A single line of documentation.
9766 SingleLine(SharedString),
9767 /// Multiple lines of plain text documentation.
9768 MultiLinePlainText(SharedString),
9769 /// Markdown documentation.
9770 MultiLineMarkdown(SharedString),
9771}
9772
9773impl From<lsp::Documentation> for CompletionDocumentation {
9774 fn from(docs: lsp::Documentation) -> Self {
9775 match docs {
9776 lsp::Documentation::String(text) => {
9777 if text.lines().count() <= 1 {
9778 CompletionDocumentation::SingleLine(text.into())
9779 } else {
9780 CompletionDocumentation::MultiLinePlainText(text.into())
9781 }
9782 }
9783
9784 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
9785 lsp::MarkupKind::PlainText => {
9786 if value.lines().count() <= 1 {
9787 CompletionDocumentation::SingleLine(value.into())
9788 } else {
9789 CompletionDocumentation::MultiLinePlainText(value.into())
9790 }
9791 }
9792
9793 lsp::MarkupKind::Markdown => {
9794 CompletionDocumentation::MultiLineMarkdown(value.into())
9795 }
9796 },
9797 }
9798 }
9799}
9800
9801fn glob_literal_prefix(glob: &Path) -> PathBuf {
9802 glob.components()
9803 .take_while(|component| match component {
9804 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
9805 _ => true,
9806 })
9807 .collect()
9808}
9809
9810pub struct SshLspAdapter {
9811 name: LanguageServerName,
9812 binary: LanguageServerBinary,
9813 initialization_options: Option<String>,
9814 code_action_kinds: Option<Vec<CodeActionKind>>,
9815}
9816
9817impl SshLspAdapter {
9818 pub fn new(
9819 name: LanguageServerName,
9820 binary: LanguageServerBinary,
9821 initialization_options: Option<String>,
9822 code_action_kinds: Option<String>,
9823 ) -> Self {
9824 Self {
9825 name,
9826 binary,
9827 initialization_options,
9828 code_action_kinds: code_action_kinds
9829 .as_ref()
9830 .and_then(|c| serde_json::from_str(c).ok()),
9831 }
9832 }
9833}
9834
9835#[async_trait(?Send)]
9836impl LspAdapter for SshLspAdapter {
9837 fn name(&self) -> LanguageServerName {
9838 self.name.clone()
9839 }
9840
9841 async fn initialization_options(
9842 self: Arc<Self>,
9843 _: &dyn Fs,
9844 _: &Arc<dyn LspAdapterDelegate>,
9845 ) -> Result<Option<serde_json::Value>> {
9846 let Some(options) = &self.initialization_options else {
9847 return Ok(None);
9848 };
9849 let result = serde_json::from_str(options)?;
9850 Ok(result)
9851 }
9852
9853 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
9854 self.code_action_kinds.clone()
9855 }
9856
9857 async fn check_if_user_installed(
9858 &self,
9859 _: &dyn LspAdapterDelegate,
9860 _: Arc<dyn LanguageToolchainStore>,
9861 _: &AsyncApp,
9862 ) -> Option<LanguageServerBinary> {
9863 Some(self.binary.clone())
9864 }
9865
9866 async fn cached_server_binary(
9867 &self,
9868 _: PathBuf,
9869 _: &dyn LspAdapterDelegate,
9870 ) -> Option<LanguageServerBinary> {
9871 None
9872 }
9873
9874 async fn fetch_latest_server_version(
9875 &self,
9876 _: &dyn LspAdapterDelegate,
9877 ) -> Result<Box<dyn 'static + Send + Any>> {
9878 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
9879 }
9880
9881 async fn fetch_server_binary(
9882 &self,
9883 _: Box<dyn 'static + Send + Any>,
9884 _: PathBuf,
9885 _: &dyn LspAdapterDelegate,
9886 ) -> Result<LanguageServerBinary> {
9887 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
9888 }
9889}
9890
9891pub fn language_server_settings<'a>(
9892 delegate: &'a dyn LspAdapterDelegate,
9893 language: &LanguageServerName,
9894 cx: &'a App,
9895) -> Option<&'a LspSettings> {
9896 language_server_settings_for(
9897 SettingsLocation {
9898 worktree_id: delegate.worktree_id(),
9899 path: delegate.worktree_root_path(),
9900 },
9901 language,
9902 cx,
9903 )
9904}
9905
9906pub(crate) fn language_server_settings_for<'a>(
9907 location: SettingsLocation<'a>,
9908 language: &LanguageServerName,
9909 cx: &'a App,
9910) -> Option<&'a LspSettings> {
9911 ProjectSettings::get(Some(location), cx).lsp.get(language)
9912}
9913
9914pub struct LocalLspAdapterDelegate {
9915 lsp_store: WeakEntity<LspStore>,
9916 worktree: worktree::Snapshot,
9917 fs: Arc<dyn Fs>,
9918 http_client: Arc<dyn HttpClient>,
9919 language_registry: Arc<LanguageRegistry>,
9920 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
9921}
9922
9923impl LocalLspAdapterDelegate {
9924 pub fn new(
9925 language_registry: Arc<LanguageRegistry>,
9926 environment: &Entity<ProjectEnvironment>,
9927 lsp_store: WeakEntity<LspStore>,
9928 worktree: &Entity<Worktree>,
9929 http_client: Arc<dyn HttpClient>,
9930 fs: Arc<dyn Fs>,
9931 cx: &mut App,
9932 ) -> Arc<Self> {
9933 let worktree_abs_path = worktree.read(cx).abs_path();
9934
9935 let load_shell_env_task = environment.update(cx, |env, cx| {
9936 env.get_environment(Some(worktree_abs_path), cx)
9937 });
9938
9939 Arc::new(Self {
9940 lsp_store,
9941 worktree: worktree.read(cx).snapshot(),
9942 fs,
9943 http_client,
9944 language_registry,
9945 load_shell_env_task,
9946 })
9947 }
9948
9949 fn from_local_lsp(
9950 local: &LocalLspStore,
9951 worktree: &Entity<Worktree>,
9952 cx: &mut App,
9953 ) -> Arc<Self> {
9954 Self::new(
9955 local.languages.clone(),
9956 &local.environment,
9957 local.weak.clone(),
9958 worktree,
9959 local.http_client.clone(),
9960 local.fs.clone(),
9961 cx,
9962 )
9963 }
9964}
9965
9966#[async_trait]
9967impl LspAdapterDelegate for LocalLspAdapterDelegate {
9968 fn show_notification(&self, message: &str, cx: &mut App) {
9969 self.lsp_store
9970 .update(cx, |_, cx| {
9971 cx.emit(LspStoreEvent::Notification(message.to_owned()))
9972 })
9973 .ok();
9974 }
9975
9976 fn http_client(&self) -> Arc<dyn HttpClient> {
9977 self.http_client.clone()
9978 }
9979
9980 fn worktree_id(&self) -> WorktreeId {
9981 self.worktree.id()
9982 }
9983
9984 fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool {
9985 self.worktree.entry_for_path(path).map_or(false, |entry| {
9986 is_dir.map_or(true, |is_required_to_be_dir| {
9987 is_required_to_be_dir == entry.is_dir()
9988 })
9989 })
9990 }
9991
9992 fn worktree_root_path(&self) -> &Path {
9993 self.worktree.abs_path().as_ref()
9994 }
9995
9996 async fn shell_env(&self) -> HashMap<String, String> {
9997 let task = self.load_shell_env_task.clone();
9998 task.await.unwrap_or_default()
9999 }
10000
10001 async fn npm_package_installed_version(
10002 &self,
10003 package_name: &str,
10004 ) -> Result<Option<(PathBuf, String)>> {
10005 let local_package_directory = self.worktree_root_path();
10006 let node_modules_directory = local_package_directory.join("node_modules");
10007
10008 if let Some(version) =
10009 read_package_installed_version(node_modules_directory.clone(), package_name).await?
10010 {
10011 return Ok(Some((node_modules_directory, version)));
10012 }
10013 let Some(npm) = self.which("npm".as_ref()).await else {
10014 log::warn!(
10015 "Failed to find npm executable for {:?}",
10016 local_package_directory
10017 );
10018 return Ok(None);
10019 };
10020
10021 let env = self.shell_env().await;
10022 let output = util::command::new_smol_command(&npm)
10023 .args(["root", "-g"])
10024 .envs(env)
10025 .current_dir(local_package_directory)
10026 .output()
10027 .await?;
10028 let global_node_modules =
10029 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
10030
10031 if let Some(version) =
10032 read_package_installed_version(global_node_modules.clone(), package_name).await?
10033 {
10034 return Ok(Some((global_node_modules, version)));
10035 }
10036 return Ok(None);
10037 }
10038
10039 #[cfg(not(target_os = "windows"))]
10040 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10041 let worktree_abs_path = self.worktree.abs_path();
10042 let shell_path = self.shell_env().await.get("PATH").cloned();
10043 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
10044 }
10045
10046 #[cfg(target_os = "windows")]
10047 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10048 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10049 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10050 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10051 which::which(command).ok()
10052 }
10053
10054 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
10055 let working_dir = self.worktree_root_path();
10056 let output = util::command::new_smol_command(&command.path)
10057 .args(command.arguments)
10058 .envs(command.env.clone().unwrap_or_default())
10059 .current_dir(working_dir)
10060 .output()
10061 .await?;
10062
10063 if output.status.success() {
10064 return Ok(());
10065 }
10066 Err(anyhow!(
10067 "{}, stdout: {:?}, stderr: {:?}",
10068 output.status,
10069 String::from_utf8_lossy(&output.stdout),
10070 String::from_utf8_lossy(&output.stderr)
10071 ))
10072 }
10073
10074 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
10075 self.language_registry
10076 .update_lsp_status(server_name, status);
10077 }
10078
10079 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
10080 self.language_registry
10081 .all_lsp_adapters()
10082 .into_iter()
10083 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
10084 .collect()
10085 }
10086
10087 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
10088 let dir = self.language_registry.language_server_download_dir(name)?;
10089
10090 if !dir.exists() {
10091 smol::fs::create_dir_all(&dir)
10092 .await
10093 .context("failed to create container directory")
10094 .log_err()?;
10095 }
10096
10097 Some(dir)
10098 }
10099
10100 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10101 let entry = self
10102 .worktree
10103 .entry_for_path(&path)
10104 .with_context(|| format!("no worktree entry for path {path:?}"))?;
10105 let abs_path = self
10106 .worktree
10107 .absolutize(&entry.path)
10108 .with_context(|| format!("cannot absolutize path {path:?}"))?;
10109
10110 self.fs.load(&abs_path).await
10111 }
10112}
10113
10114async fn populate_labels_for_symbols(
10115 symbols: Vec<CoreSymbol>,
10116 language_registry: &Arc<LanguageRegistry>,
10117 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10118 output: &mut Vec<Symbol>,
10119) {
10120 #[allow(clippy::mutable_key_type)]
10121 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10122
10123 let mut unknown_paths = BTreeSet::new();
10124 for symbol in symbols {
10125 let language = language_registry
10126 .language_for_file_path(&symbol.path.path)
10127 .await
10128 .ok()
10129 .or_else(|| {
10130 unknown_paths.insert(symbol.path.path.clone());
10131 None
10132 });
10133 symbols_by_language
10134 .entry(language)
10135 .or_default()
10136 .push(symbol);
10137 }
10138
10139 for unknown_path in unknown_paths {
10140 log::info!(
10141 "no language found for symbol path {}",
10142 unknown_path.display()
10143 );
10144 }
10145
10146 let mut label_params = Vec::new();
10147 for (language, mut symbols) in symbols_by_language {
10148 label_params.clear();
10149 label_params.extend(
10150 symbols
10151 .iter_mut()
10152 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10153 );
10154
10155 let mut labels = Vec::new();
10156 if let Some(language) = language {
10157 let lsp_adapter = lsp_adapter.clone().or_else(|| {
10158 language_registry
10159 .lsp_adapters(&language.name())
10160 .first()
10161 .cloned()
10162 });
10163 if let Some(lsp_adapter) = lsp_adapter {
10164 labels = lsp_adapter
10165 .labels_for_symbols(&label_params, &language)
10166 .await
10167 .log_err()
10168 .unwrap_or_default();
10169 }
10170 }
10171
10172 for ((symbol, (name, _)), label) in symbols
10173 .into_iter()
10174 .zip(label_params.drain(..))
10175 .zip(labels.into_iter().chain(iter::repeat(None)))
10176 {
10177 output.push(Symbol {
10178 language_server_name: symbol.language_server_name,
10179 source_worktree_id: symbol.source_worktree_id,
10180 source_language_server_id: symbol.source_language_server_id,
10181 path: symbol.path,
10182 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10183 name,
10184 kind: symbol.kind,
10185 range: symbol.range,
10186 signature: symbol.signature,
10187 });
10188 }
10189 }
10190}
10191
10192fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
10193 match server.capabilities().text_document_sync.as_ref()? {
10194 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
10195 lsp::TextDocumentSyncKind::NONE => None,
10196 lsp::TextDocumentSyncKind::FULL => Some(true),
10197 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
10198 _ => None,
10199 },
10200 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
10201 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
10202 if *supported {
10203 Some(true)
10204 } else {
10205 None
10206 }
10207 }
10208 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
10209 Some(save_options.include_text.unwrap_or(false))
10210 }
10211 },
10212 }
10213}
10214
10215/// Completion items are displayed in a `UniformList`.
10216/// Usually, those items are single-line strings, but in LSP responses,
10217/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
10218/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
10219/// 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,
10220/// breaking the completions menu presentation.
10221///
10222/// 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.
10223fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
10224 let mut new_text = String::with_capacity(label.text.len());
10225 let mut offset_map = vec![0; label.text.len() + 1];
10226 let mut last_char_was_space = false;
10227 let mut new_idx = 0;
10228 let mut chars = label.text.char_indices().fuse();
10229 let mut newlines_removed = false;
10230
10231 while let Some((idx, c)) = chars.next() {
10232 offset_map[idx] = new_idx;
10233
10234 match c {
10235 '\n' if last_char_was_space => {
10236 newlines_removed = true;
10237 }
10238 '\t' | ' ' if last_char_was_space => {}
10239 '\n' if !last_char_was_space => {
10240 new_text.push(' ');
10241 new_idx += 1;
10242 last_char_was_space = true;
10243 newlines_removed = true;
10244 }
10245 ' ' | '\t' => {
10246 new_text.push(' ');
10247 new_idx += 1;
10248 last_char_was_space = true;
10249 }
10250 _ => {
10251 new_text.push(c);
10252 new_idx += c.len_utf8();
10253 last_char_was_space = false;
10254 }
10255 }
10256 }
10257 offset_map[label.text.len()] = new_idx;
10258
10259 // Only modify the label if newlines were removed.
10260 if !newlines_removed {
10261 return;
10262 }
10263
10264 let last_index = new_idx;
10265 let mut run_ranges_errors = Vec::new();
10266 label.runs.retain_mut(|(range, _)| {
10267 match offset_map.get(range.start) {
10268 Some(&start) => range.start = start,
10269 None => {
10270 run_ranges_errors.push(range.clone());
10271 return false;
10272 }
10273 }
10274
10275 match offset_map.get(range.end) {
10276 Some(&end) => range.end = end,
10277 None => {
10278 run_ranges_errors.push(range.clone());
10279 range.end = last_index;
10280 }
10281 }
10282 true
10283 });
10284 if !run_ranges_errors.is_empty() {
10285 log::error!(
10286 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
10287 label.text
10288 );
10289 }
10290
10291 let mut wrong_filter_range = None;
10292 if label.filter_range == (0..label.text.len()) {
10293 label.filter_range = 0..new_text.len();
10294 } else {
10295 let mut original_filter_range = Some(label.filter_range.clone());
10296 match offset_map.get(label.filter_range.start) {
10297 Some(&start) => label.filter_range.start = start,
10298 None => {
10299 wrong_filter_range = original_filter_range.take();
10300 label.filter_range.start = last_index;
10301 }
10302 }
10303
10304 match offset_map.get(label.filter_range.end) {
10305 Some(&end) => label.filter_range.end = end,
10306 None => {
10307 wrong_filter_range = original_filter_range.take();
10308 label.filter_range.end = last_index;
10309 }
10310 }
10311 }
10312 if let Some(wrong_filter_range) = wrong_filter_range {
10313 log::error!(
10314 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
10315 label.text
10316 );
10317 }
10318
10319 label.text = new_text;
10320}
10321
10322#[cfg(test)]
10323mod tests {
10324 use language::HighlightId;
10325
10326 use super::*;
10327
10328 #[test]
10329 fn test_glob_literal_prefix() {
10330 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
10331 assert_eq!(
10332 glob_literal_prefix(Path::new("node_modules/**/*.js")),
10333 Path::new("node_modules")
10334 );
10335 assert_eq!(
10336 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10337 Path::new("foo")
10338 );
10339 assert_eq!(
10340 glob_literal_prefix(Path::new("foo/bar/baz.js")),
10341 Path::new("foo/bar/baz.js")
10342 );
10343
10344 #[cfg(target_os = "windows")]
10345 {
10346 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
10347 assert_eq!(
10348 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
10349 Path::new("node_modules")
10350 );
10351 assert_eq!(
10352 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10353 Path::new("foo")
10354 );
10355 assert_eq!(
10356 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
10357 Path::new("foo/bar/baz.js")
10358 );
10359 }
10360 }
10361
10362 #[test]
10363 fn test_multi_len_chars_normalization() {
10364 let mut label = CodeLabel {
10365 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
10366 runs: vec![(0..6, HighlightId(1))],
10367 filter_range: 0..6,
10368 };
10369 ensure_uniform_list_compatible_label(&mut label);
10370 assert_eq!(
10371 label,
10372 CodeLabel {
10373 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
10374 runs: vec![(0..6, HighlightId(1))],
10375 filter_range: 0..6,
10376 }
10377 );
10378 }
10379}