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