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
3418#[allow(clippy::large_enum_variant)]
3419pub(crate) enum LspStoreMode {
3420 Local(LocalLspStore), // ssh host and collab host
3421 Remote(RemoteLspStore), // collab guest
3422}
3423
3424impl LspStoreMode {
3425 fn is_local(&self) -> bool {
3426 matches!(self, LspStoreMode::Local(_))
3427 }
3428}
3429
3430pub struct LspStore {
3431 mode: LspStoreMode,
3432 last_formatting_failure: Option<String>,
3433 downstream_client: Option<(AnyProtoClient, u64)>,
3434 nonce: u128,
3435 buffer_store: Entity<BufferStore>,
3436 worktree_store: Entity<WorktreeStore>,
3437 toolchain_store: Option<Entity<ToolchainStore>>,
3438 pub languages: Arc<LanguageRegistry>,
3439 pub language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3440 active_entry: Option<ProjectEntryId>,
3441 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3442 _maintain_buffer_languages: Task<()>,
3443 diagnostic_summaries:
3444 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3445}
3446
3447pub enum LspStoreEvent {
3448 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3449 LanguageServerRemoved(LanguageServerId),
3450 LanguageServerUpdate {
3451 language_server_id: LanguageServerId,
3452 message: proto::update_language_server::Variant,
3453 },
3454 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3455 LanguageServerPrompt(LanguageServerPromptRequest),
3456 LanguageDetected {
3457 buffer: Entity<Buffer>,
3458 new_language: Option<Arc<Language>>,
3459 },
3460 Notification(String),
3461 RefreshInlayHints,
3462 RefreshCodeLens,
3463 DiagnosticsUpdated {
3464 language_server_id: LanguageServerId,
3465 path: ProjectPath,
3466 },
3467 DiskBasedDiagnosticsStarted {
3468 language_server_id: LanguageServerId,
3469 },
3470 DiskBasedDiagnosticsFinished {
3471 language_server_id: LanguageServerId,
3472 },
3473 SnippetEdit {
3474 buffer_id: BufferId,
3475 edits: Vec<(lsp::Range, Snippet)>,
3476 most_recent_edit: clock::Lamport,
3477 },
3478}
3479
3480#[derive(Clone, Debug, Serialize)]
3481pub struct LanguageServerStatus {
3482 pub name: String,
3483 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3484 pub has_pending_diagnostic_updates: bool,
3485 progress_tokens: HashSet<String>,
3486}
3487
3488#[derive(Clone, Debug)]
3489struct CoreSymbol {
3490 pub language_server_name: LanguageServerName,
3491 pub source_worktree_id: WorktreeId,
3492 pub source_language_server_id: LanguageServerId,
3493 pub path: ProjectPath,
3494 pub name: String,
3495 pub kind: lsp::SymbolKind,
3496 pub range: Range<Unclipped<PointUtf16>>,
3497 pub signature: [u8; 32],
3498}
3499
3500impl LspStore {
3501 pub fn init(client: &AnyProtoClient) {
3502 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3503 client.add_entity_request_handler(Self::handle_restart_language_servers);
3504 client.add_entity_request_handler(Self::handle_stop_language_servers);
3505 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3506 client.add_entity_message_handler(Self::handle_start_language_server);
3507 client.add_entity_message_handler(Self::handle_update_language_server);
3508 client.add_entity_message_handler(Self::handle_language_server_log);
3509 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3510 client.add_entity_request_handler(Self::handle_format_buffers);
3511 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3512 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3513 client.add_entity_request_handler(Self::handle_apply_code_action);
3514 client.add_entity_request_handler(Self::handle_inlay_hints);
3515 client.add_entity_request_handler(Self::handle_get_project_symbols);
3516 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3517 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3518 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3519 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3520 client.add_entity_request_handler(Self::handle_on_type_formatting);
3521 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3522 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3523 client.add_entity_request_handler(Self::handle_rename_project_entry);
3524 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3525 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3526 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3527 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3528 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3529 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3530 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3531 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3532 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3533 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3534 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3535 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3536 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3537
3538 client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
3539 client.add_entity_request_handler(Self::handle_lsp_ext_run_flycheck);
3540 client.add_entity_request_handler(Self::handle_lsp_ext_clear_flycheck);
3541 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3542 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3543 client.add_entity_request_handler(
3544 Self::handle_lsp_command::<lsp_ext_command::GoToParentModule>,
3545 );
3546 client.add_entity_request_handler(
3547 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3548 );
3549 client.add_entity_request_handler(
3550 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3551 );
3552 }
3553
3554 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3555 match &self.mode {
3556 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3557 _ => None,
3558 }
3559 }
3560
3561 pub fn as_local(&self) -> Option<&LocalLspStore> {
3562 match &self.mode {
3563 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3564 _ => None,
3565 }
3566 }
3567
3568 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3569 match &mut self.mode {
3570 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3571 _ => None,
3572 }
3573 }
3574
3575 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3576 match &self.mode {
3577 LspStoreMode::Remote(RemoteLspStore {
3578 upstream_client: Some(upstream_client),
3579 upstream_project_id,
3580 ..
3581 }) => Some((upstream_client.clone(), *upstream_project_id)),
3582
3583 LspStoreMode::Remote(RemoteLspStore {
3584 upstream_client: None,
3585 ..
3586 }) => None,
3587 LspStoreMode::Local(_) => None,
3588 }
3589 }
3590
3591 pub fn new_local(
3592 buffer_store: Entity<BufferStore>,
3593 worktree_store: Entity<WorktreeStore>,
3594 prettier_store: Entity<PrettierStore>,
3595 toolchain_store: Entity<ToolchainStore>,
3596 environment: Entity<ProjectEnvironment>,
3597 languages: Arc<LanguageRegistry>,
3598 http_client: Arc<dyn HttpClient>,
3599 fs: Arc<dyn Fs>,
3600 cx: &mut Context<Self>,
3601 ) -> Self {
3602 let yarn = YarnPathStore::new(fs.clone(), cx);
3603 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3604 .detach();
3605 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3606 .detach();
3607 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3608 .detach();
3609 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3610 .detach();
3611 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3612 cx.subscribe(
3613 extension_events,
3614 Self::reload_zed_json_schemas_on_extensions_changed,
3615 )
3616 .detach();
3617 } else {
3618 log::debug!("No extension events global found. Skipping JSON schema auto-reload setup");
3619 }
3620 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3621 .detach();
3622
3623 let _maintain_workspace_config = {
3624 let (sender, receiver) = watch::channel();
3625 (
3626 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3627 sender,
3628 )
3629 };
3630 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
3631 Self {
3632 mode: LspStoreMode::Local(LocalLspStore {
3633 weak: cx.weak_entity(),
3634 worktree_store: worktree_store.clone(),
3635 toolchain_store: toolchain_store.clone(),
3636 supplementary_language_servers: Default::default(),
3637 languages: languages.clone(),
3638 language_server_ids: Default::default(),
3639 language_servers: Default::default(),
3640 last_workspace_edits_by_language_server: Default::default(),
3641 language_server_watched_paths: Default::default(),
3642 language_server_paths_watched_for_rename: Default::default(),
3643 language_server_watcher_registrations: Default::default(),
3644 buffers_being_formatted: Default::default(),
3645 buffer_snapshots: Default::default(),
3646 prettier_store,
3647 environment,
3648 http_client,
3649 fs,
3650 yarn,
3651 next_diagnostic_group_id: Default::default(),
3652 diagnostics: Default::default(),
3653 _subscription: cx.on_app_quit(|this, cx| {
3654 this.as_local_mut().unwrap().shutdown_language_servers(cx)
3655 }),
3656 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3657 registered_buffers: Default::default(),
3658 }),
3659 last_formatting_failure: None,
3660 downstream_client: None,
3661 buffer_store,
3662 worktree_store,
3663 toolchain_store: Some(toolchain_store),
3664 languages: languages.clone(),
3665 language_server_statuses: Default::default(),
3666 nonce: StdRng::from_entropy().r#gen(),
3667 diagnostic_summaries: Default::default(),
3668 active_entry: None,
3669
3670 _maintain_workspace_config,
3671 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3672 }
3673 }
3674
3675 fn send_lsp_proto_request<R: LspCommand>(
3676 &self,
3677 buffer: Entity<Buffer>,
3678 client: AnyProtoClient,
3679 upstream_project_id: u64,
3680 request: R,
3681 cx: &mut Context<LspStore>,
3682 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3683 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3684 cx.spawn(async move |this, cx| {
3685 let response = client.request(message).await?;
3686 let this = this.upgrade().context("project dropped")?;
3687 request
3688 .response_from_proto(response, this, buffer, cx.clone())
3689 .await
3690 })
3691 }
3692
3693 pub(super) fn new_remote(
3694 buffer_store: Entity<BufferStore>,
3695 worktree_store: Entity<WorktreeStore>,
3696 toolchain_store: Option<Entity<ToolchainStore>>,
3697 languages: Arc<LanguageRegistry>,
3698 upstream_client: AnyProtoClient,
3699 project_id: u64,
3700 fs: Arc<dyn Fs>,
3701 cx: &mut Context<Self>,
3702 ) -> Self {
3703 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3704 .detach();
3705 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3706 .detach();
3707 let _maintain_workspace_config = {
3708 let (sender, receiver) = watch::channel();
3709 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3710 };
3711 Self {
3712 mode: LspStoreMode::Remote(RemoteLspStore {
3713 upstream_client: Some(upstream_client),
3714 upstream_project_id: project_id,
3715 }),
3716 downstream_client: None,
3717 last_formatting_failure: None,
3718 buffer_store,
3719 worktree_store,
3720 languages: languages.clone(),
3721 language_server_statuses: Default::default(),
3722 nonce: StdRng::from_entropy().r#gen(),
3723 diagnostic_summaries: Default::default(),
3724 active_entry: None,
3725 toolchain_store,
3726 _maintain_workspace_config,
3727 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3728 }
3729 }
3730
3731 fn on_buffer_store_event(
3732 &mut self,
3733 _: Entity<BufferStore>,
3734 event: &BufferStoreEvent,
3735 cx: &mut Context<Self>,
3736 ) {
3737 match event {
3738 BufferStoreEvent::BufferAdded(buffer) => {
3739 self.on_buffer_added(buffer, cx).log_err();
3740 }
3741 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3742 let buffer_id = buffer.read(cx).remote_id();
3743 if let Some(local) = self.as_local_mut() {
3744 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3745 local.reset_buffer(buffer, old_file, cx);
3746
3747 if local.registered_buffers.contains_key(&buffer_id) {
3748 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3749 }
3750 }
3751 }
3752
3753 self.detect_language_for_buffer(buffer, cx);
3754 if let Some(local) = self.as_local_mut() {
3755 local.initialize_buffer(buffer, cx);
3756 if local.registered_buffers.contains_key(&buffer_id) {
3757 local.register_buffer_with_language_servers(buffer, cx);
3758 }
3759 }
3760 }
3761 _ => {}
3762 }
3763 }
3764
3765 fn on_worktree_store_event(
3766 &mut self,
3767 _: Entity<WorktreeStore>,
3768 event: &WorktreeStoreEvent,
3769 cx: &mut Context<Self>,
3770 ) {
3771 match event {
3772 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3773 if !worktree.read(cx).is_local() {
3774 return;
3775 }
3776 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3777 worktree::Event::UpdatedEntries(changes) => {
3778 this.update_local_worktree_language_servers(&worktree, changes, cx);
3779 }
3780 worktree::Event::UpdatedGitRepositories(_)
3781 | worktree::Event::DeletedEntry(_) => {}
3782 })
3783 .detach()
3784 }
3785 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3786 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3787 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3788 }
3789 WorktreeStoreEvent::WorktreeReleased(..)
3790 | WorktreeStoreEvent::WorktreeOrderChanged
3791 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3792 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3793 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3794 }
3795 }
3796
3797 fn on_prettier_store_event(
3798 &mut self,
3799 _: Entity<PrettierStore>,
3800 event: &PrettierStoreEvent,
3801 cx: &mut Context<Self>,
3802 ) {
3803 match event {
3804 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3805 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3806 }
3807 PrettierStoreEvent::LanguageServerAdded {
3808 new_server_id,
3809 name,
3810 prettier_server,
3811 } => {
3812 self.register_supplementary_language_server(
3813 *new_server_id,
3814 name.clone(),
3815 prettier_server.clone(),
3816 cx,
3817 );
3818 }
3819 }
3820 }
3821
3822 fn on_toolchain_store_event(
3823 &mut self,
3824 _: Entity<ToolchainStore>,
3825 event: &ToolchainStoreEvent,
3826 _: &mut Context<Self>,
3827 ) {
3828 match event {
3829 ToolchainStoreEvent::ToolchainActivated { .. } => {
3830 self.request_workspace_config_refresh()
3831 }
3832 }
3833 }
3834
3835 fn request_workspace_config_refresh(&mut self) {
3836 *self._maintain_workspace_config.1.borrow_mut() = ();
3837 }
3838
3839 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3840 self.as_local().map(|local| local.prettier_store.clone())
3841 }
3842
3843 fn on_buffer_event(
3844 &mut self,
3845 buffer: Entity<Buffer>,
3846 event: &language::BufferEvent,
3847 cx: &mut Context<Self>,
3848 ) {
3849 match event {
3850 language::BufferEvent::Edited { .. } => {
3851 self.on_buffer_edited(buffer, cx);
3852 }
3853
3854 language::BufferEvent::Saved => {
3855 self.on_buffer_saved(buffer, cx);
3856 }
3857
3858 _ => {}
3859 }
3860 }
3861
3862 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3863 buffer.update(cx, |buffer, _| {
3864 buffer.set_language_registry(self.languages.clone())
3865 });
3866
3867 cx.subscribe(buffer, |this, buffer, event, cx| {
3868 this.on_buffer_event(buffer, event, cx);
3869 })
3870 .detach();
3871
3872 self.detect_language_for_buffer(buffer, cx);
3873 if let Some(local) = self.as_local_mut() {
3874 local.initialize_buffer(buffer, cx);
3875 }
3876
3877 Ok(())
3878 }
3879
3880 pub fn reload_zed_json_schemas_on_extensions_changed(
3881 &mut self,
3882 _: Entity<extension::ExtensionEvents>,
3883 evt: &extension::Event,
3884 cx: &mut Context<Self>,
3885 ) {
3886 match evt {
3887 extension::Event::ExtensionInstalled(_)
3888 | extension::Event::ConfigureExtensionRequested(_) => return,
3889 extension::Event::ExtensionsInstalledChanged => {}
3890 }
3891 if self.as_local().is_none() {
3892 return;
3893 }
3894 cx.spawn(async move |this, cx| {
3895 let weak_ref = this.clone();
3896
3897 let servers = this
3898 .update(cx, |this, cx| {
3899 let local = this.as_local()?;
3900
3901 let mut servers = Vec::new();
3902 for ((worktree_id, _), server_ids) in &local.language_server_ids {
3903 for server_id in server_ids {
3904 let Some(states) = local.language_servers.get(server_id) else {
3905 continue;
3906 };
3907 let (json_adapter, json_server) = match states {
3908 LanguageServerState::Running {
3909 adapter, server, ..
3910 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
3911 (adapter.adapter.clone(), server.clone())
3912 }
3913 _ => continue,
3914 };
3915
3916 let Some(worktree) = this
3917 .worktree_store
3918 .read(cx)
3919 .worktree_for_id(*worktree_id, cx)
3920 else {
3921 continue;
3922 };
3923 let json_delegate: Arc<dyn LspAdapterDelegate> =
3924 LocalLspAdapterDelegate::new(
3925 local.languages.clone(),
3926 &local.environment,
3927 weak_ref.clone(),
3928 &worktree,
3929 local.http_client.clone(),
3930 local.fs.clone(),
3931 cx,
3932 );
3933
3934 servers.push((json_adapter, json_server, json_delegate));
3935 }
3936 }
3937 return Some(servers);
3938 })
3939 .ok()
3940 .flatten();
3941
3942 let Some(servers) = servers else {
3943 return;
3944 };
3945
3946 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
3947 let local = this.as_local()?;
3948 let toolchain_store = this.toolchain_store(cx);
3949 return Some((local.fs.clone(), toolchain_store));
3950 }) else {
3951 return;
3952 };
3953 for (adapter, server, delegate) in servers {
3954 adapter.clear_zed_json_schema_cache().await;
3955
3956 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
3957 adapter,
3958 fs.as_ref(),
3959 &delegate,
3960 toolchain_store.clone(),
3961 cx,
3962 )
3963 .await
3964 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
3965 .ok()
3966 else {
3967 continue;
3968 };
3969 server
3970 .notify::<lsp::notification::DidChangeConfiguration>(
3971 &lsp::DidChangeConfigurationParams {
3972 settings: json_workspace_config,
3973 },
3974 )
3975 .ok();
3976 }
3977 })
3978 .detach();
3979 }
3980
3981 pub(crate) fn register_buffer_with_language_servers(
3982 &mut self,
3983 buffer: &Entity<Buffer>,
3984 ignore_refcounts: bool,
3985 cx: &mut Context<Self>,
3986 ) -> OpenLspBufferHandle {
3987 let buffer_id = buffer.read(cx).remote_id();
3988 let handle = cx.new(|_| buffer.clone());
3989 if let Some(local) = self.as_local_mut() {
3990 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
3991 return handle;
3992 };
3993 if !file.is_local() {
3994 return handle;
3995 }
3996
3997 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
3998 if !ignore_refcounts {
3999 *refcount += 1;
4000 }
4001
4002 if ignore_refcounts || *refcount == 1 {
4003 local.register_buffer_with_language_servers(buffer, cx);
4004 }
4005 if !ignore_refcounts {
4006 cx.observe_release(&handle, move |this, buffer, cx| {
4007 let local = this.as_local_mut().unwrap();
4008 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
4009 debug_panic!("bad refcounting");
4010 return;
4011 };
4012
4013 *refcount -= 1;
4014 if *refcount == 0 {
4015 local.registered_buffers.remove(&buffer_id);
4016 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
4017 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
4018 }
4019 }
4020 })
4021 .detach();
4022 }
4023 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4024 let buffer_id = buffer.read(cx).remote_id().to_proto();
4025 cx.background_spawn(async move {
4026 upstream_client
4027 .request(proto::RegisterBufferWithLanguageServers {
4028 project_id: upstream_project_id,
4029 buffer_id,
4030 })
4031 .await
4032 })
4033 .detach();
4034 } else {
4035 panic!("oops!");
4036 }
4037 handle
4038 }
4039
4040 fn maintain_buffer_languages(
4041 languages: Arc<LanguageRegistry>,
4042 cx: &mut Context<Self>,
4043 ) -> Task<()> {
4044 let mut subscription = languages.subscribe();
4045 let mut prev_reload_count = languages.reload_count();
4046 cx.spawn(async move |this, cx| {
4047 while let Some(()) = subscription.next().await {
4048 if let Some(this) = this.upgrade() {
4049 // If the language registry has been reloaded, then remove and
4050 // re-assign the languages on all open buffers.
4051 let reload_count = languages.reload_count();
4052 if reload_count > prev_reload_count {
4053 prev_reload_count = reload_count;
4054 this.update(cx, |this, cx| {
4055 this.buffer_store.clone().update(cx, |buffer_store, cx| {
4056 for buffer in buffer_store.buffers() {
4057 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
4058 {
4059 buffer
4060 .update(cx, |buffer, cx| buffer.set_language(None, cx));
4061 if let Some(local) = this.as_local_mut() {
4062 local.reset_buffer(&buffer, &f, cx);
4063
4064 if local
4065 .registered_buffers
4066 .contains_key(&buffer.read(cx).remote_id())
4067 {
4068 if let Some(file_url) =
4069 lsp::Url::from_file_path(&f.abs_path(cx))
4070 .log_err()
4071 {
4072 local.unregister_buffer_from_language_servers(
4073 &buffer, &file_url, cx,
4074 );
4075 }
4076 }
4077 }
4078 }
4079 }
4080 });
4081 })
4082 .ok();
4083 }
4084
4085 this.update(cx, |this, cx| {
4086 let mut plain_text_buffers = Vec::new();
4087 let mut buffers_with_unknown_injections = Vec::new();
4088 for handle in this.buffer_store.read(cx).buffers() {
4089 let buffer = handle.read(cx);
4090 if buffer.language().is_none()
4091 || buffer.language() == Some(&*language::PLAIN_TEXT)
4092 {
4093 plain_text_buffers.push(handle);
4094 } else if buffer.contains_unknown_injections() {
4095 buffers_with_unknown_injections.push(handle);
4096 }
4097 }
4098
4099 // Deprioritize the invisible worktrees so main worktrees' language servers can be started first,
4100 // and reused later in the invisible worktrees.
4101 plain_text_buffers.sort_by_key(|buffer| {
4102 Reverse(
4103 crate::File::from_dyn(buffer.read(cx).file())
4104 .map(|file| file.worktree.read(cx).is_visible()),
4105 )
4106 });
4107
4108 for buffer in plain_text_buffers {
4109 this.detect_language_for_buffer(&buffer, cx);
4110 if let Some(local) = this.as_local_mut() {
4111 local.initialize_buffer(&buffer, cx);
4112 if local
4113 .registered_buffers
4114 .contains_key(&buffer.read(cx).remote_id())
4115 {
4116 local.register_buffer_with_language_servers(&buffer, cx);
4117 }
4118 }
4119 }
4120
4121 for buffer in buffers_with_unknown_injections {
4122 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4123 }
4124 })
4125 .ok();
4126 }
4127 }
4128 })
4129 }
4130
4131 fn detect_language_for_buffer(
4132 &mut self,
4133 buffer_handle: &Entity<Buffer>,
4134 cx: &mut Context<Self>,
4135 ) -> Option<language::AvailableLanguage> {
4136 // If the buffer has a language, set it and start the language server if we haven't already.
4137 let buffer = buffer_handle.read(cx);
4138 let file = buffer.file()?;
4139
4140 let content = buffer.as_rope();
4141 let available_language = self.languages.language_for_file(file, Some(content), cx);
4142 if let Some(available_language) = &available_language {
4143 if let Some(Ok(Ok(new_language))) = self
4144 .languages
4145 .load_language(available_language)
4146 .now_or_never()
4147 {
4148 self.set_language_for_buffer(buffer_handle, new_language, cx);
4149 }
4150 } else {
4151 cx.emit(LspStoreEvent::LanguageDetected {
4152 buffer: buffer_handle.clone(),
4153 new_language: None,
4154 });
4155 }
4156
4157 available_language
4158 }
4159
4160 pub(crate) fn set_language_for_buffer(
4161 &mut self,
4162 buffer_entity: &Entity<Buffer>,
4163 new_language: Arc<Language>,
4164 cx: &mut Context<Self>,
4165 ) {
4166 let buffer = buffer_entity.read(cx);
4167 let buffer_file = buffer.file().cloned();
4168 let buffer_id = buffer.remote_id();
4169 if let Some(local_store) = self.as_local_mut() {
4170 if local_store.registered_buffers.contains_key(&buffer_id) {
4171 if let Some(abs_path) =
4172 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4173 {
4174 if let Some(file_url) = lsp::Url::from_file_path(&abs_path).log_err() {
4175 local_store.unregister_buffer_from_language_servers(
4176 buffer_entity,
4177 &file_url,
4178 cx,
4179 );
4180 }
4181 }
4182 }
4183 }
4184 buffer_entity.update(cx, |buffer, cx| {
4185 if buffer.language().map_or(true, |old_language| {
4186 !Arc::ptr_eq(old_language, &new_language)
4187 }) {
4188 buffer.set_language(Some(new_language.clone()), cx);
4189 }
4190 });
4191
4192 let settings =
4193 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4194 let buffer_file = File::from_dyn(buffer_file.as_ref());
4195
4196 let worktree_id = if let Some(file) = buffer_file {
4197 let worktree = file.worktree.clone();
4198
4199 if let Some(local) = self.as_local_mut() {
4200 if local.registered_buffers.contains_key(&buffer_id) {
4201 local.register_buffer_with_language_servers(buffer_entity, cx);
4202 }
4203 }
4204 Some(worktree.read(cx).id())
4205 } else {
4206 None
4207 };
4208
4209 if settings.prettier.allowed {
4210 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4211 {
4212 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4213 if let Some(prettier_store) = prettier_store {
4214 prettier_store.update(cx, |prettier_store, cx| {
4215 prettier_store.install_default_prettier(
4216 worktree_id,
4217 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4218 cx,
4219 )
4220 })
4221 }
4222 }
4223 }
4224
4225 cx.emit(LspStoreEvent::LanguageDetected {
4226 buffer: buffer_entity.clone(),
4227 new_language: Some(new_language),
4228 })
4229 }
4230
4231 pub fn buffer_store(&self) -> Entity<BufferStore> {
4232 self.buffer_store.clone()
4233 }
4234
4235 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4236 self.active_entry = active_entry;
4237 }
4238
4239 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4240 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4241 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4242 for (path, summaries) in summaries {
4243 for (&server_id, summary) in summaries {
4244 client
4245 .send(proto::UpdateDiagnosticSummary {
4246 project_id: downstream_project_id,
4247 worktree_id: worktree.id().to_proto(),
4248 summary: Some(summary.to_proto(server_id, path)),
4249 })
4250 .log_err();
4251 }
4252 }
4253 }
4254 }
4255 }
4256
4257 pub fn request_lsp<R: LspCommand>(
4258 &mut self,
4259 buffer_handle: Entity<Buffer>,
4260 server: LanguageServerToQuery,
4261 request: R,
4262 cx: &mut Context<Self>,
4263 ) -> Task<Result<R::Response>>
4264 where
4265 <R::LspRequest as lsp::request::Request>::Result: Send,
4266 <R::LspRequest as lsp::request::Request>::Params: Send,
4267 {
4268 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4269 return self.send_lsp_proto_request(
4270 buffer_handle,
4271 upstream_client,
4272 upstream_project_id,
4273 request,
4274 cx,
4275 );
4276 }
4277
4278 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4279 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4280 local
4281 .language_servers_for_buffer(buffer, cx)
4282 .find(|(_, server)| {
4283 request.check_capabilities(server.adapter_server_capabilities())
4284 })
4285 .map(|(_, server)| server.clone())
4286 }),
4287 LanguageServerToQuery::Other(id) => self
4288 .language_server_for_local_buffer(buffer, id, cx)
4289 .and_then(|(_, server)| {
4290 request
4291 .check_capabilities(server.adapter_server_capabilities())
4292 .then(|| Arc::clone(server))
4293 }),
4294 }) else {
4295 return Task::ready(Ok(Default::default()));
4296 };
4297
4298 let buffer = buffer_handle.read(cx);
4299 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4300
4301 let Some(file) = file else {
4302 return Task::ready(Ok(Default::default()));
4303 };
4304
4305 let lsp_params = match request.to_lsp_params_or_response(
4306 &file.abs_path(cx),
4307 buffer,
4308 &language_server,
4309 cx,
4310 ) {
4311 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4312 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4313
4314 Err(err) => {
4315 let message = format!(
4316 "{} via {} failed: {}",
4317 request.display_name(),
4318 language_server.name(),
4319 err
4320 );
4321 log::warn!("{message}");
4322 return Task::ready(Err(anyhow!(message)));
4323 }
4324 };
4325
4326 let status = request.status();
4327 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4328 return Task::ready(Ok(Default::default()));
4329 }
4330 return cx.spawn(async move |this, cx| {
4331 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4332
4333 let id = lsp_request.id();
4334 let _cleanup = if status.is_some() {
4335 cx.update(|cx| {
4336 this.update(cx, |this, cx| {
4337 this.on_lsp_work_start(
4338 language_server.server_id(),
4339 id.to_string(),
4340 LanguageServerProgress {
4341 is_disk_based_diagnostics_progress: false,
4342 is_cancellable: false,
4343 title: None,
4344 message: status.clone(),
4345 percentage: None,
4346 last_update_at: cx.background_executor().now(),
4347 },
4348 cx,
4349 );
4350 })
4351 })
4352 .log_err();
4353
4354 Some(defer(|| {
4355 cx.update(|cx| {
4356 this.update(cx, |this, cx| {
4357 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4358 })
4359 })
4360 .log_err();
4361 }))
4362 } else {
4363 None
4364 };
4365
4366 let result = lsp_request.await.into_response();
4367
4368 let response = result.map_err(|err| {
4369 let message = format!(
4370 "{} via {} failed: {}",
4371 request.display_name(),
4372 language_server.name(),
4373 err
4374 );
4375 log::warn!("{message}");
4376 anyhow!(message)
4377 })?;
4378
4379 let response = request
4380 .response_from_lsp(
4381 response,
4382 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
4383 buffer_handle,
4384 language_server.server_id(),
4385 cx.clone(),
4386 )
4387 .await;
4388 response
4389 });
4390 }
4391
4392 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4393 let mut language_formatters_to_check = Vec::new();
4394 for buffer in self.buffer_store.read(cx).buffers() {
4395 let buffer = buffer.read(cx);
4396 let buffer_file = File::from_dyn(buffer.file());
4397 let buffer_language = buffer.language();
4398 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4399 if buffer_language.is_some() {
4400 language_formatters_to_check.push((
4401 buffer_file.map(|f| f.worktree_id(cx)),
4402 settings.into_owned(),
4403 ));
4404 }
4405 }
4406
4407 self.refresh_server_tree(cx);
4408
4409 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4410 prettier_store.update(cx, |prettier_store, cx| {
4411 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4412 })
4413 }
4414
4415 cx.notify();
4416 }
4417
4418 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4419 let buffer_store = self.buffer_store.clone();
4420 if let Some(local) = self.as_local_mut() {
4421 let mut adapters = BTreeMap::default();
4422 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4423 let get_adapter = {
4424 let languages = local.languages.clone();
4425 let environment = local.environment.clone();
4426 let weak = local.weak.clone();
4427 let worktree_store = local.worktree_store.clone();
4428 let http_client = local.http_client.clone();
4429 let fs = local.fs.clone();
4430 move |worktree_id, cx: &mut App| {
4431 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4432 Some(LocalLspAdapterDelegate::new(
4433 languages.clone(),
4434 &environment,
4435 weak.clone(),
4436 &worktree,
4437 http_client.clone(),
4438 fs.clone(),
4439 cx,
4440 ))
4441 }
4442 };
4443
4444 let mut rebase = lsp_tree.rebase();
4445 for buffer_handle in buffer_store.read(cx).buffers().sorted_by_key(|buffer| {
4446 Reverse(
4447 crate::File::from_dyn(buffer.read(cx).file())
4448 .map(|file| file.worktree.read(cx).is_visible()),
4449 )
4450 }) {
4451 let buffer = buffer_handle.read(cx);
4452 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4453 continue;
4454 }
4455 if let Some((file, language)) = File::from_dyn(buffer.file())
4456 .cloned()
4457 .zip(buffer.language().map(|l| l.name()))
4458 {
4459 let worktree_id = file.worktree_id(cx);
4460 let Some(worktree) = local
4461 .worktree_store
4462 .read(cx)
4463 .worktree_for_id(worktree_id, cx)
4464 else {
4465 continue;
4466 };
4467
4468 let Some((reused, delegate, nodes)) = local
4469 .reuse_existing_language_server(
4470 rebase.server_tree(),
4471 &worktree,
4472 &language,
4473 cx,
4474 )
4475 .map(|(delegate, servers)| (true, delegate, servers))
4476 .or_else(|| {
4477 let delegate = adapters
4478 .entry(worktree_id)
4479 .or_insert_with(|| get_adapter(worktree_id, cx))
4480 .clone()?;
4481 let path = file
4482 .path()
4483 .parent()
4484 .map(Arc::from)
4485 .unwrap_or_else(|| file.path().clone());
4486 let worktree_path = ProjectPath { worktree_id, path };
4487
4488 let nodes = rebase.get(
4489 worktree_path,
4490 AdapterQuery::Language(&language),
4491 delegate.clone(),
4492 cx,
4493 );
4494
4495 Some((false, delegate, nodes.collect()))
4496 })
4497 else {
4498 continue;
4499 };
4500
4501 for node in nodes {
4502 if !reused {
4503 node.server_id_or_init(
4504 |LaunchDisposition {
4505 server_name,
4506 attach,
4507 path,
4508 settings,
4509 }| match attach {
4510 language::Attach::InstancePerRoot => {
4511 // todo: handle instance per root proper.
4512 if let Some(server_ids) = local
4513 .language_server_ids
4514 .get(&(worktree_id, server_name.clone()))
4515 {
4516 server_ids.iter().cloned().next().unwrap()
4517 } else {
4518 local.start_language_server(
4519 &worktree,
4520 delegate.clone(),
4521 local
4522 .languages
4523 .lsp_adapters(&language)
4524 .into_iter()
4525 .find(|adapter| {
4526 &adapter.name() == server_name
4527 })
4528 .expect("To find LSP adapter"),
4529 settings,
4530 cx,
4531 )
4532 }
4533 }
4534 language::Attach::Shared => {
4535 let uri = Url::from_file_path(
4536 worktree.read(cx).abs_path().join(&path.path),
4537 );
4538 let key = (worktree_id, server_name.clone());
4539 local.language_server_ids.remove(&key);
4540
4541 let server_id = local.start_language_server(
4542 &worktree,
4543 delegate.clone(),
4544 local
4545 .languages
4546 .lsp_adapters(&language)
4547 .into_iter()
4548 .find(|adapter| &adapter.name() == server_name)
4549 .expect("To find LSP adapter"),
4550 settings,
4551 cx,
4552 );
4553 if let Some(state) =
4554 local.language_servers.get(&server_id)
4555 {
4556 if let Ok(uri) = uri {
4557 state.add_workspace_folder(uri);
4558 };
4559 }
4560 server_id
4561 }
4562 },
4563 );
4564 }
4565 }
4566 }
4567 }
4568 rebase.finish()
4569 });
4570 for (id, name) in to_stop {
4571 self.stop_local_language_server(id, name, cx).detach();
4572 }
4573 }
4574 }
4575
4576 pub fn apply_code_action(
4577 &self,
4578 buffer_handle: Entity<Buffer>,
4579 mut action: CodeAction,
4580 push_to_history: bool,
4581 cx: &mut Context<Self>,
4582 ) -> Task<Result<ProjectTransaction>> {
4583 if let Some((upstream_client, project_id)) = self.upstream_client() {
4584 let request = proto::ApplyCodeAction {
4585 project_id,
4586 buffer_id: buffer_handle.read(cx).remote_id().into(),
4587 action: Some(Self::serialize_code_action(&action)),
4588 };
4589 let buffer_store = self.buffer_store();
4590 cx.spawn(async move |_, cx| {
4591 let response = upstream_client
4592 .request(request)
4593 .await?
4594 .transaction
4595 .ok_or_else(|| anyhow!("missing transaction"))?;
4596
4597 buffer_store
4598 .update(cx, |buffer_store, cx| {
4599 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4600 })?
4601 .await
4602 })
4603 } else if self.mode.is_local() {
4604 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4605 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4606 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4607 }) else {
4608 return Task::ready(Ok(ProjectTransaction::default()));
4609 };
4610 cx.spawn(async move |this, cx| {
4611 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4612 .await
4613 .context("resolving a code action")?;
4614 if let Some(edit) = action.lsp_action.edit() {
4615 if edit.changes.is_some() || edit.document_changes.is_some() {
4616 return LocalLspStore::deserialize_workspace_edit(
4617 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
4618 edit.clone(),
4619 push_to_history,
4620 lsp_adapter.clone(),
4621 lang_server.clone(),
4622 cx,
4623 )
4624 .await;
4625 }
4626 }
4627
4628 if let Some(command) = action.lsp_action.command() {
4629 let server_capabilities = lang_server.capabilities();
4630 let available_commands = server_capabilities
4631 .execute_command_provider
4632 .as_ref()
4633 .map(|options| options.commands.as_slice())
4634 .unwrap_or_default();
4635 if available_commands.contains(&command.command) {
4636 this.update(cx, |this, _| {
4637 this.as_local_mut()
4638 .unwrap()
4639 .last_workspace_edits_by_language_server
4640 .remove(&lang_server.server_id());
4641 })?;
4642
4643 let _result = lang_server
4644 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4645 command: command.command.clone(),
4646 arguments: command.arguments.clone().unwrap_or_default(),
4647 ..lsp::ExecuteCommandParams::default()
4648 })
4649 .await.into_response()
4650 .context("execute command")?;
4651
4652 return this.update(cx, |this, _| {
4653 this.as_local_mut()
4654 .unwrap()
4655 .last_workspace_edits_by_language_server
4656 .remove(&lang_server.server_id())
4657 .unwrap_or_default()
4658 });
4659 } else {
4660 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4661 }
4662 }
4663
4664 Ok(ProjectTransaction::default())
4665 })
4666 } else {
4667 Task::ready(Err(anyhow!("no upstream client and not local")))
4668 }
4669 }
4670
4671 pub fn apply_code_action_kind(
4672 &mut self,
4673 buffers: HashSet<Entity<Buffer>>,
4674 kind: CodeActionKind,
4675 push_to_history: bool,
4676 cx: &mut Context<Self>,
4677 ) -> Task<anyhow::Result<ProjectTransaction>> {
4678 if let Some(_) = self.as_local() {
4679 cx.spawn(async move |lsp_store, cx| {
4680 let buffers = buffers.into_iter().collect::<Vec<_>>();
4681 let result = LocalLspStore::execute_code_action_kind_locally(
4682 lsp_store.clone(),
4683 buffers,
4684 kind,
4685 push_to_history,
4686 cx,
4687 )
4688 .await;
4689 lsp_store.update(cx, |lsp_store, _| {
4690 lsp_store.update_last_formatting_failure(&result);
4691 })?;
4692 result
4693 })
4694 } else if let Some((client, project_id)) = self.upstream_client() {
4695 let buffer_store = self.buffer_store();
4696 cx.spawn(async move |lsp_store, cx| {
4697 let result = client
4698 .request(proto::ApplyCodeActionKind {
4699 project_id,
4700 kind: kind.as_str().to_owned(),
4701 buffer_ids: buffers
4702 .iter()
4703 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
4704 .collect::<Result<_>>()?,
4705 })
4706 .await
4707 .and_then(|result| result.transaction.context("missing transaction"));
4708 lsp_store.update(cx, |lsp_store, _| {
4709 lsp_store.update_last_formatting_failure(&result);
4710 })?;
4711
4712 let transaction_response = result?;
4713 buffer_store
4714 .update(cx, |buffer_store, cx| {
4715 buffer_store.deserialize_project_transaction(
4716 transaction_response,
4717 push_to_history,
4718 cx,
4719 )
4720 })?
4721 .await
4722 })
4723 } else {
4724 Task::ready(Ok(ProjectTransaction::default()))
4725 }
4726 }
4727
4728 pub fn resolve_inlay_hint(
4729 &self,
4730 hint: InlayHint,
4731 buffer_handle: Entity<Buffer>,
4732 server_id: LanguageServerId,
4733 cx: &mut Context<Self>,
4734 ) -> Task<anyhow::Result<InlayHint>> {
4735 if let Some((upstream_client, project_id)) = self.upstream_client() {
4736 let request = proto::ResolveInlayHint {
4737 project_id,
4738 buffer_id: buffer_handle.read(cx).remote_id().into(),
4739 language_server_id: server_id.0 as u64,
4740 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4741 };
4742 cx.spawn(async move |_, _| {
4743 let response = upstream_client
4744 .request(request)
4745 .await
4746 .context("inlay hints proto request")?;
4747 match response.hint {
4748 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4749 .context("inlay hints proto resolve response conversion"),
4750 None => Ok(hint),
4751 }
4752 })
4753 } else {
4754 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4755 self.language_server_for_local_buffer(buffer, server_id, cx)
4756 .map(|(_, server)| server.clone())
4757 }) else {
4758 return Task::ready(Ok(hint));
4759 };
4760 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4761 return Task::ready(Ok(hint));
4762 }
4763 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4764 cx.spawn(async move |_, cx| {
4765 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4766 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4767 );
4768 let resolved_hint = resolve_task
4769 .await
4770 .into_response()
4771 .context("inlay hint resolve LSP request")?;
4772 let resolved_hint = InlayHints::lsp_to_project_hint(
4773 resolved_hint,
4774 &buffer_handle,
4775 server_id,
4776 ResolveState::Resolved,
4777 false,
4778 cx,
4779 )
4780 .await?;
4781 Ok(resolved_hint)
4782 })
4783 }
4784 }
4785
4786 pub(crate) fn linked_edit(
4787 &mut self,
4788 buffer: &Entity<Buffer>,
4789 position: Anchor,
4790 cx: &mut Context<Self>,
4791 ) -> Task<Result<Vec<Range<Anchor>>>> {
4792 let snapshot = buffer.read(cx).snapshot();
4793 let scope = snapshot.language_scope_at(position);
4794 let Some(server_id) = self
4795 .as_local()
4796 .and_then(|local| {
4797 buffer.update(cx, |buffer, cx| {
4798 local
4799 .language_servers_for_buffer(buffer, cx)
4800 .filter(|(_, server)| {
4801 server
4802 .capabilities()
4803 .linked_editing_range_provider
4804 .is_some()
4805 })
4806 .filter(|(adapter, _)| {
4807 scope
4808 .as_ref()
4809 .map(|scope| scope.language_allowed(&adapter.name))
4810 .unwrap_or(true)
4811 })
4812 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
4813 .next()
4814 })
4815 })
4816 .or_else(|| {
4817 self.upstream_client()
4818 .is_some()
4819 .then_some(LanguageServerToQuery::FirstCapable)
4820 })
4821 .filter(|_| {
4822 maybe!({
4823 let language = buffer.read(cx).language_at(position)?;
4824 Some(
4825 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
4826 .linked_edits,
4827 )
4828 }) == Some(true)
4829 })
4830 else {
4831 return Task::ready(Ok(vec![]));
4832 };
4833
4834 self.request_lsp(
4835 buffer.clone(),
4836 server_id,
4837 LinkedEditingRange { position },
4838 cx,
4839 )
4840 }
4841
4842 fn apply_on_type_formatting(
4843 &mut self,
4844 buffer: Entity<Buffer>,
4845 position: Anchor,
4846 trigger: String,
4847 cx: &mut Context<Self>,
4848 ) -> Task<Result<Option<Transaction>>> {
4849 if let Some((client, project_id)) = self.upstream_client() {
4850 let request = proto::OnTypeFormatting {
4851 project_id,
4852 buffer_id: buffer.read(cx).remote_id().into(),
4853 position: Some(serialize_anchor(&position)),
4854 trigger,
4855 version: serialize_version(&buffer.read(cx).version()),
4856 };
4857 cx.spawn(async move |_, _| {
4858 client
4859 .request(request)
4860 .await?
4861 .transaction
4862 .map(language::proto::deserialize_transaction)
4863 .transpose()
4864 })
4865 } else if let Some(local) = self.as_local_mut() {
4866 let buffer_id = buffer.read(cx).remote_id();
4867 local.buffers_being_formatted.insert(buffer_id);
4868 cx.spawn(async move |this, cx| {
4869 let _cleanup = defer({
4870 let this = this.clone();
4871 let mut cx = cx.clone();
4872 move || {
4873 this.update(&mut cx, |this, _| {
4874 if let Some(local) = this.as_local_mut() {
4875 local.buffers_being_formatted.remove(&buffer_id);
4876 }
4877 })
4878 .ok();
4879 }
4880 });
4881
4882 buffer
4883 .update(cx, |buffer, _| {
4884 buffer.wait_for_edits(Some(position.timestamp))
4885 })?
4886 .await?;
4887 this.update(cx, |this, cx| {
4888 let position = position.to_point_utf16(buffer.read(cx));
4889 this.on_type_format(buffer, position, trigger, false, cx)
4890 })?
4891 .await
4892 })
4893 } else {
4894 Task::ready(Err(anyhow!("No upstream client or local language server")))
4895 }
4896 }
4897
4898 pub fn on_type_format<T: ToPointUtf16>(
4899 &mut self,
4900 buffer: Entity<Buffer>,
4901 position: T,
4902 trigger: String,
4903 push_to_history: bool,
4904 cx: &mut Context<Self>,
4905 ) -> Task<Result<Option<Transaction>>> {
4906 let position = position.to_point_utf16(buffer.read(cx));
4907 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
4908 }
4909
4910 fn on_type_format_impl(
4911 &mut self,
4912 buffer: Entity<Buffer>,
4913 position: PointUtf16,
4914 trigger: String,
4915 push_to_history: bool,
4916 cx: &mut Context<Self>,
4917 ) -> Task<Result<Option<Transaction>>> {
4918 let options = buffer.update(cx, |buffer, cx| {
4919 lsp_command::lsp_formatting_options(
4920 language_settings(
4921 buffer.language_at(position).map(|l| l.name()),
4922 buffer.file(),
4923 cx,
4924 )
4925 .as_ref(),
4926 )
4927 });
4928 self.request_lsp(
4929 buffer.clone(),
4930 LanguageServerToQuery::FirstCapable,
4931 OnTypeFormatting {
4932 position,
4933 trigger,
4934 options,
4935 push_to_history,
4936 },
4937 cx,
4938 )
4939 }
4940
4941 pub fn code_actions(
4942 &mut self,
4943 buffer_handle: &Entity<Buffer>,
4944 range: Range<Anchor>,
4945 kinds: Option<Vec<CodeActionKind>>,
4946 cx: &mut Context<Self>,
4947 ) -> Task<Result<Vec<CodeAction>>> {
4948 if let Some((upstream_client, project_id)) = self.upstream_client() {
4949 let request_task = upstream_client.request(proto::MultiLspQuery {
4950 buffer_id: buffer_handle.read(cx).remote_id().into(),
4951 version: serialize_version(&buffer_handle.read(cx).version()),
4952 project_id,
4953 strategy: Some(proto::multi_lsp_query::Strategy::All(
4954 proto::AllLanguageServers {},
4955 )),
4956 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
4957 GetCodeActions {
4958 range: range.clone(),
4959 kinds: kinds.clone(),
4960 }
4961 .to_proto(project_id, buffer_handle.read(cx)),
4962 )),
4963 });
4964 let buffer = buffer_handle.clone();
4965 cx.spawn(async move |weak_project, cx| {
4966 let Some(project) = weak_project.upgrade() else {
4967 return Ok(Vec::new());
4968 };
4969 let responses = request_task.await?.responses;
4970 let actions = join_all(
4971 responses
4972 .into_iter()
4973 .filter_map(|lsp_response| match lsp_response.response? {
4974 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
4975 Some(response)
4976 }
4977 unexpected => {
4978 debug_panic!("Unexpected response: {unexpected:?}");
4979 None
4980 }
4981 })
4982 .map(|code_actions_response| {
4983 GetCodeActions {
4984 range: range.clone(),
4985 kinds: kinds.clone(),
4986 }
4987 .response_from_proto(
4988 code_actions_response,
4989 project.clone(),
4990 buffer.clone(),
4991 cx.clone(),
4992 )
4993 }),
4994 )
4995 .await;
4996
4997 Ok(actions
4998 .into_iter()
4999 .collect::<Result<Vec<Vec<_>>>>()?
5000 .into_iter()
5001 .flatten()
5002 .collect())
5003 })
5004 } else {
5005 let all_actions_task = self.request_multiple_lsp_locally(
5006 buffer_handle,
5007 Some(range.start),
5008 GetCodeActions {
5009 range: range.clone(),
5010 kinds: kinds.clone(),
5011 },
5012 cx,
5013 );
5014 cx.spawn(async move |_, _| Ok(all_actions_task.await.into_iter().flatten().collect()))
5015 }
5016 }
5017
5018 pub fn code_lens(
5019 &mut self,
5020 buffer_handle: &Entity<Buffer>,
5021 cx: &mut Context<Self>,
5022 ) -> Task<Result<Vec<CodeAction>>> {
5023 if let Some((upstream_client, project_id)) = self.upstream_client() {
5024 let request_task = upstream_client.request(proto::MultiLspQuery {
5025 buffer_id: buffer_handle.read(cx).remote_id().into(),
5026 version: serialize_version(&buffer_handle.read(cx).version()),
5027 project_id,
5028 strategy: Some(proto::multi_lsp_query::Strategy::All(
5029 proto::AllLanguageServers {},
5030 )),
5031 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
5032 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
5033 )),
5034 });
5035 let buffer = buffer_handle.clone();
5036 cx.spawn(async move |weak_project, cx| {
5037 let Some(project) = weak_project.upgrade() else {
5038 return Ok(Vec::new());
5039 };
5040 let responses = request_task.await?.responses;
5041 let code_lens = join_all(
5042 responses
5043 .into_iter()
5044 .filter_map(|lsp_response| match lsp_response.response? {
5045 proto::lsp_response::Response::GetCodeLensResponse(response) => {
5046 Some(response)
5047 }
5048 unexpected => {
5049 debug_panic!("Unexpected response: {unexpected:?}");
5050 None
5051 }
5052 })
5053 .map(|code_lens_response| {
5054 GetCodeLens.response_from_proto(
5055 code_lens_response,
5056 project.clone(),
5057 buffer.clone(),
5058 cx.clone(),
5059 )
5060 }),
5061 )
5062 .await;
5063
5064 Ok(code_lens
5065 .into_iter()
5066 .collect::<Result<Vec<Vec<_>>>>()?
5067 .into_iter()
5068 .flatten()
5069 .collect())
5070 })
5071 } else {
5072 let code_lens_task =
5073 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
5074 cx.spawn(async move |_, _| Ok(code_lens_task.await.into_iter().flatten().collect()))
5075 }
5076 }
5077
5078 #[inline(never)]
5079 pub fn completions(
5080 &self,
5081 buffer: &Entity<Buffer>,
5082 position: PointUtf16,
5083 context: CompletionContext,
5084 cx: &mut Context<Self>,
5085 ) -> Task<Result<Option<Vec<Completion>>>> {
5086 let language_registry = self.languages.clone();
5087
5088 if let Some((upstream_client, project_id)) = self.upstream_client() {
5089 let task = self.send_lsp_proto_request(
5090 buffer.clone(),
5091 upstream_client,
5092 project_id,
5093 GetCompletions { position, context },
5094 cx,
5095 );
5096 let language = buffer.read(cx).language().cloned();
5097
5098 // In the future, we should provide project guests with the names of LSP adapters,
5099 // so that they can use the correct LSP adapter when computing labels. For now,
5100 // guests just use the first LSP adapter associated with the buffer's language.
5101 let lsp_adapter = language.as_ref().and_then(|language| {
5102 language_registry
5103 .lsp_adapters(&language.name())
5104 .first()
5105 .cloned()
5106 });
5107
5108 cx.foreground_executor().spawn(async move {
5109 let completions = task.await?;
5110 let mut result = Vec::new();
5111 populate_labels_for_completions(completions, language, lsp_adapter, &mut result)
5112 .await;
5113 Ok(Some(result))
5114 })
5115 } else if let Some(local) = self.as_local() {
5116 let snapshot = buffer.read(cx).snapshot();
5117 let offset = position.to_offset(&snapshot);
5118 let scope = snapshot.language_scope_at(offset);
5119 let language = snapshot.language().cloned();
5120 let completion_settings = language_settings(
5121 language.as_ref().map(|language| language.name()),
5122 buffer.read(cx).file(),
5123 cx,
5124 )
5125 .completions;
5126 if !completion_settings.lsp {
5127 return Task::ready(Ok(None));
5128 }
5129
5130 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5131 local
5132 .language_servers_for_buffer(buffer, cx)
5133 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5134 .filter(|(adapter, _)| {
5135 scope
5136 .as_ref()
5137 .map(|scope| scope.language_allowed(&adapter.name))
5138 .unwrap_or(true)
5139 })
5140 .map(|(_, server)| server.server_id())
5141 .collect()
5142 });
5143
5144 let buffer = buffer.clone();
5145 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5146 let lsp_timeout = if lsp_timeout > 0 {
5147 Some(Duration::from_millis(lsp_timeout))
5148 } else {
5149 None
5150 };
5151 cx.spawn(async move |this, cx| {
5152 let mut tasks = Vec::with_capacity(server_ids.len());
5153 this.update(cx, |lsp_store, cx| {
5154 for server_id in server_ids {
5155 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5156 let lsp_timeout = lsp_timeout
5157 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5158 let mut timeout = cx.background_spawn(async move {
5159 match lsp_timeout {
5160 Some(lsp_timeout) => {
5161 lsp_timeout.await;
5162 true
5163 },
5164 None => false,
5165 }
5166 }).fuse();
5167 let mut lsp_request = lsp_store.request_lsp(
5168 buffer.clone(),
5169 LanguageServerToQuery::Other(server_id),
5170 GetCompletions {
5171 position,
5172 context: context.clone(),
5173 },
5174 cx,
5175 ).fuse();
5176 let new_task = cx.background_spawn(async move {
5177 select_biased! {
5178 response = lsp_request => anyhow::Ok(Some(response?)),
5179 timeout_happened = timeout => {
5180 if timeout_happened {
5181 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5182 Ok(None)
5183 } else {
5184 let completions = lsp_request.await?;
5185 Ok(Some(completions))
5186 }
5187 },
5188 }
5189 });
5190 tasks.push((lsp_adapter, new_task));
5191 }
5192 })?;
5193
5194 let mut has_completions_returned = false;
5195 let mut completions = Vec::new();
5196 for (lsp_adapter, task) in tasks {
5197 if let Ok(Some(new_completions)) = task.await {
5198 has_completions_returned = true;
5199 populate_labels_for_completions(
5200 new_completions,
5201 language.clone(),
5202 lsp_adapter,
5203 &mut completions,
5204 )
5205 .await;
5206 }
5207 }
5208 if has_completions_returned {
5209 Ok(Some(completions))
5210 } else {
5211 Ok(None)
5212 }
5213 })
5214 } else {
5215 Task::ready(Err(anyhow!("No upstream client or local language server")))
5216 }
5217 }
5218
5219 pub fn resolve_completions(
5220 &self,
5221 buffer: Entity<Buffer>,
5222 completion_indices: Vec<usize>,
5223 completions: Rc<RefCell<Box<[Completion]>>>,
5224 cx: &mut Context<Self>,
5225 ) -> Task<Result<bool>> {
5226 let client = self.upstream_client();
5227
5228 let buffer_id = buffer.read(cx).remote_id();
5229 let buffer_snapshot = buffer.read(cx).snapshot();
5230
5231 cx.spawn(async move |this, cx| {
5232 let mut did_resolve = false;
5233 if let Some((client, project_id)) = client {
5234 for completion_index in completion_indices {
5235 let server_id = {
5236 let completion = &completions.borrow()[completion_index];
5237 completion.source.server_id()
5238 };
5239 if let Some(server_id) = server_id {
5240 if Self::resolve_completion_remote(
5241 project_id,
5242 server_id,
5243 buffer_id,
5244 completions.clone(),
5245 completion_index,
5246 client.clone(),
5247 )
5248 .await
5249 .log_err()
5250 .is_some()
5251 {
5252 did_resolve = true;
5253 }
5254 } else {
5255 resolve_word_completion(
5256 &buffer_snapshot,
5257 &mut completions.borrow_mut()[completion_index],
5258 );
5259 }
5260 }
5261 } else {
5262 for completion_index in completion_indices {
5263 let server_id = {
5264 let completion = &completions.borrow()[completion_index];
5265 completion.source.server_id()
5266 };
5267 if let Some(server_id) = server_id {
5268 let server_and_adapter = this
5269 .read_with(cx, |lsp_store, _| {
5270 let server = lsp_store.language_server_for_id(server_id)?;
5271 let adapter =
5272 lsp_store.language_server_adapter_for_id(server.server_id())?;
5273 Some((server, adapter))
5274 })
5275 .ok()
5276 .flatten();
5277 let Some((server, adapter)) = server_and_adapter else {
5278 continue;
5279 };
5280
5281 let resolved = Self::resolve_completion_local(
5282 server,
5283 &buffer_snapshot,
5284 completions.clone(),
5285 completion_index,
5286 )
5287 .await
5288 .log_err()
5289 .is_some();
5290 if resolved {
5291 Self::regenerate_completion_labels(
5292 adapter,
5293 &buffer_snapshot,
5294 completions.clone(),
5295 completion_index,
5296 )
5297 .await
5298 .log_err();
5299 did_resolve = true;
5300 }
5301 } else {
5302 resolve_word_completion(
5303 &buffer_snapshot,
5304 &mut completions.borrow_mut()[completion_index],
5305 );
5306 }
5307 }
5308 }
5309
5310 Ok(did_resolve)
5311 })
5312 }
5313
5314 async fn resolve_completion_local(
5315 server: Arc<lsp::LanguageServer>,
5316 snapshot: &BufferSnapshot,
5317 completions: Rc<RefCell<Box<[Completion]>>>,
5318 completion_index: usize,
5319 ) -> Result<()> {
5320 let server_id = server.server_id();
5321 let can_resolve = server
5322 .capabilities()
5323 .completion_provider
5324 .as_ref()
5325 .and_then(|options| options.resolve_provider)
5326 .unwrap_or(false);
5327 if !can_resolve {
5328 return Ok(());
5329 }
5330
5331 let request = {
5332 let completion = &completions.borrow()[completion_index];
5333 match &completion.source {
5334 CompletionSource::Lsp {
5335 lsp_completion,
5336 resolved,
5337 server_id: completion_server_id,
5338 ..
5339 } => {
5340 if *resolved {
5341 return Ok(());
5342 }
5343 anyhow::ensure!(
5344 server_id == *completion_server_id,
5345 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5346 );
5347 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5348 }
5349 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5350 return Ok(());
5351 }
5352 }
5353 };
5354 let resolved_completion = request
5355 .await
5356 .into_response()
5357 .context("resolve completion")?;
5358
5359 let mut updated_insert_range = None;
5360 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5361 // Technically we don't have to parse the whole `text_edit`, since the only
5362 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5363 // is `typescript-language-server` and they only update `text_edit.new_text`.
5364 // But we should not rely on that.
5365 let edit = parse_completion_text_edit(text_edit, snapshot);
5366
5367 if let Some(mut parsed_edit) = edit {
5368 LineEnding::normalize(&mut parsed_edit.new_text);
5369
5370 let mut completions = completions.borrow_mut();
5371 let completion = &mut completions[completion_index];
5372
5373 completion.new_text = parsed_edit.new_text;
5374 completion.replace_range = parsed_edit.replace_range;
5375
5376 updated_insert_range = parsed_edit.insert_range;
5377 }
5378 }
5379
5380 let mut completions = completions.borrow_mut();
5381 let completion = &mut completions[completion_index];
5382 if let CompletionSource::Lsp {
5383 insert_range,
5384 lsp_completion,
5385 resolved,
5386 server_id: completion_server_id,
5387 ..
5388 } = &mut completion.source
5389 {
5390 *insert_range = updated_insert_range;
5391 if *resolved {
5392 return Ok(());
5393 }
5394 anyhow::ensure!(
5395 server_id == *completion_server_id,
5396 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5397 );
5398 *lsp_completion = Box::new(resolved_completion);
5399 *resolved = true;
5400 }
5401 Ok(())
5402 }
5403
5404 async fn regenerate_completion_labels(
5405 adapter: Arc<CachedLspAdapter>,
5406 snapshot: &BufferSnapshot,
5407 completions: Rc<RefCell<Box<[Completion]>>>,
5408 completion_index: usize,
5409 ) -> Result<()> {
5410 let completion_item = completions.borrow()[completion_index]
5411 .source
5412 .lsp_completion(true)
5413 .map(Cow::into_owned);
5414 if let Some(lsp_documentation) = completion_item
5415 .as_ref()
5416 .and_then(|completion_item| completion_item.documentation.clone())
5417 {
5418 let mut completions = completions.borrow_mut();
5419 let completion = &mut completions[completion_index];
5420 completion.documentation = Some(lsp_documentation.into());
5421 } else {
5422 let mut completions = completions.borrow_mut();
5423 let completion = &mut completions[completion_index];
5424 completion.documentation = Some(CompletionDocumentation::Undocumented);
5425 }
5426
5427 let mut new_label = match completion_item {
5428 Some(completion_item) => {
5429 // 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
5430 // So we have to update the label here anyway...
5431 let language = snapshot.language();
5432 match language {
5433 Some(language) => {
5434 adapter
5435 .labels_for_completions(&[completion_item.clone()], language)
5436 .await?
5437 }
5438 None => Vec::new(),
5439 }
5440 .pop()
5441 .flatten()
5442 .unwrap_or_else(|| {
5443 CodeLabel::fallback_for_completion(
5444 &completion_item,
5445 language.map(|language| language.as_ref()),
5446 )
5447 })
5448 }
5449 None => CodeLabel::plain(
5450 completions.borrow()[completion_index].new_text.clone(),
5451 None,
5452 ),
5453 };
5454 ensure_uniform_list_compatible_label(&mut new_label);
5455
5456 let mut completions = completions.borrow_mut();
5457 let completion = &mut completions[completion_index];
5458 if completion.label.filter_text() == new_label.filter_text() {
5459 completion.label = new_label;
5460 } else {
5461 log::error!(
5462 "Resolved completion changed display label from {} to {}. \
5463 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5464 completion.label.text(),
5465 new_label.text(),
5466 completion.label.filter_text(),
5467 new_label.filter_text()
5468 );
5469 }
5470
5471 Ok(())
5472 }
5473
5474 async fn resolve_completion_remote(
5475 project_id: u64,
5476 server_id: LanguageServerId,
5477 buffer_id: BufferId,
5478 completions: Rc<RefCell<Box<[Completion]>>>,
5479 completion_index: usize,
5480 client: AnyProtoClient,
5481 ) -> Result<()> {
5482 let lsp_completion = {
5483 let completion = &completions.borrow()[completion_index];
5484 match &completion.source {
5485 CompletionSource::Lsp {
5486 lsp_completion,
5487 resolved,
5488 server_id: completion_server_id,
5489 ..
5490 } => {
5491 anyhow::ensure!(
5492 server_id == *completion_server_id,
5493 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5494 );
5495 if *resolved {
5496 return Ok(());
5497 }
5498 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5499 }
5500 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5501 return Ok(());
5502 }
5503 }
5504 };
5505 let request = proto::ResolveCompletionDocumentation {
5506 project_id,
5507 language_server_id: server_id.0 as u64,
5508 lsp_completion,
5509 buffer_id: buffer_id.into(),
5510 };
5511
5512 let response = client
5513 .request(request)
5514 .await
5515 .context("completion documentation resolve proto request")?;
5516 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5517
5518 let documentation = if response.documentation.is_empty() {
5519 CompletionDocumentation::Undocumented
5520 } else if response.documentation_is_markdown {
5521 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5522 } else if response.documentation.lines().count() <= 1 {
5523 CompletionDocumentation::SingleLine(response.documentation.into())
5524 } else {
5525 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5526 };
5527
5528 let mut completions = completions.borrow_mut();
5529 let completion = &mut completions[completion_index];
5530 completion.documentation = Some(documentation);
5531 if let CompletionSource::Lsp {
5532 insert_range,
5533 lsp_completion,
5534 resolved,
5535 server_id: completion_server_id,
5536 lsp_defaults: _,
5537 } = &mut completion.source
5538 {
5539 let completion_insert_range = response
5540 .old_insert_start
5541 .and_then(deserialize_anchor)
5542 .zip(response.old_insert_end.and_then(deserialize_anchor));
5543 *insert_range = completion_insert_range.map(|(start, end)| start..end);
5544
5545 if *resolved {
5546 return Ok(());
5547 }
5548 anyhow::ensure!(
5549 server_id == *completion_server_id,
5550 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5551 );
5552 *lsp_completion = Box::new(resolved_lsp_completion);
5553 *resolved = true;
5554 }
5555
5556 let replace_range = response
5557 .old_replace_start
5558 .and_then(deserialize_anchor)
5559 .zip(response.old_replace_end.and_then(deserialize_anchor));
5560 if let Some((old_replace_start, old_replace_end)) = replace_range {
5561 if !response.new_text.is_empty() {
5562 completion.new_text = response.new_text;
5563 completion.replace_range = old_replace_start..old_replace_end;
5564 }
5565 }
5566
5567 Ok(())
5568 }
5569
5570 pub fn apply_additional_edits_for_completion(
5571 &self,
5572 buffer_handle: Entity<Buffer>,
5573 completions: Rc<RefCell<Box<[Completion]>>>,
5574 completion_index: usize,
5575 push_to_history: bool,
5576 cx: &mut Context<Self>,
5577 ) -> Task<Result<Option<Transaction>>> {
5578 if let Some((client, project_id)) = self.upstream_client() {
5579 let buffer = buffer_handle.read(cx);
5580 let buffer_id = buffer.remote_id();
5581 cx.spawn(async move |_, cx| {
5582 let request = {
5583 let completion = completions.borrow()[completion_index].clone();
5584 proto::ApplyCompletionAdditionalEdits {
5585 project_id,
5586 buffer_id: buffer_id.into(),
5587 completion: Some(Self::serialize_completion(&CoreCompletion {
5588 replace_range: completion.replace_range,
5589 new_text: completion.new_text,
5590 source: completion.source,
5591 })),
5592 }
5593 };
5594
5595 if let Some(transaction) = client.request(request).await?.transaction {
5596 let transaction = language::proto::deserialize_transaction(transaction)?;
5597 buffer_handle
5598 .update(cx, |buffer, _| {
5599 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5600 })?
5601 .await?;
5602 if push_to_history {
5603 buffer_handle.update(cx, |buffer, _| {
5604 buffer.push_transaction(transaction.clone(), Instant::now());
5605 buffer.finalize_last_transaction();
5606 })?;
5607 }
5608 Ok(Some(transaction))
5609 } else {
5610 Ok(None)
5611 }
5612 })
5613 } else {
5614 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5615 let completion = &completions.borrow()[completion_index];
5616 let server_id = completion.source.server_id()?;
5617 Some(
5618 self.language_server_for_local_buffer(buffer, server_id, cx)?
5619 .1
5620 .clone(),
5621 )
5622 }) else {
5623 return Task::ready(Ok(None));
5624 };
5625 let snapshot = buffer_handle.read(&cx).snapshot();
5626
5627 cx.spawn(async move |this, cx| {
5628 Self::resolve_completion_local(
5629 server.clone(),
5630 &snapshot,
5631 completions.clone(),
5632 completion_index,
5633 )
5634 .await
5635 .context("resolving completion")?;
5636 let completion = completions.borrow()[completion_index].clone();
5637 let additional_text_edits = completion
5638 .source
5639 .lsp_completion(true)
5640 .as_ref()
5641 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5642 if let Some(edits) = additional_text_edits {
5643 let edits = this
5644 .update(cx, |this, cx| {
5645 this.as_local_mut().unwrap().edits_from_lsp(
5646 &buffer_handle,
5647 edits,
5648 server.server_id(),
5649 None,
5650 cx,
5651 )
5652 })?
5653 .await?;
5654
5655 buffer_handle.update(cx, |buffer, cx| {
5656 buffer.finalize_last_transaction();
5657 buffer.start_transaction();
5658
5659 for (range, text) in edits {
5660 let primary = &completion.replace_range;
5661 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5662 && primary.end.cmp(&range.start, buffer).is_ge();
5663 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5664 && range.end.cmp(&primary.end, buffer).is_ge();
5665
5666 //Skip additional edits which overlap with the primary completion edit
5667 //https://github.com/zed-industries/zed/pull/1871
5668 if !start_within && !end_within {
5669 buffer.edit([(range, text)], None, cx);
5670 }
5671 }
5672
5673 let transaction = if buffer.end_transaction(cx).is_some() {
5674 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5675 if !push_to_history {
5676 buffer.forget_transaction(transaction.id);
5677 }
5678 Some(transaction)
5679 } else {
5680 None
5681 };
5682 Ok(transaction)
5683 })?
5684 } else {
5685 Ok(None)
5686 }
5687 })
5688 }
5689 }
5690
5691 pub fn inlay_hints(
5692 &mut self,
5693 buffer_handle: Entity<Buffer>,
5694 range: Range<Anchor>,
5695 cx: &mut Context<Self>,
5696 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5697 let buffer = buffer_handle.read(cx);
5698 let range_start = range.start;
5699 let range_end = range.end;
5700 let buffer_id = buffer.remote_id().into();
5701 let lsp_request = InlayHints { range };
5702
5703 if let Some((client, project_id)) = self.upstream_client() {
5704 let request = proto::InlayHints {
5705 project_id,
5706 buffer_id,
5707 start: Some(serialize_anchor(&range_start)),
5708 end: Some(serialize_anchor(&range_end)),
5709 version: serialize_version(&buffer_handle.read(cx).version()),
5710 };
5711 cx.spawn(async move |project, cx| {
5712 let response = client
5713 .request(request)
5714 .await
5715 .context("inlay hints proto request")?;
5716 LspCommand::response_from_proto(
5717 lsp_request,
5718 response,
5719 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5720 buffer_handle.clone(),
5721 cx.clone(),
5722 )
5723 .await
5724 .context("inlay hints proto response conversion")
5725 })
5726 } else {
5727 let lsp_request_task = self.request_lsp(
5728 buffer_handle.clone(),
5729 LanguageServerToQuery::FirstCapable,
5730 lsp_request,
5731 cx,
5732 );
5733 cx.spawn(async move |_, cx| {
5734 buffer_handle
5735 .update(cx, |buffer, _| {
5736 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5737 })?
5738 .await
5739 .context("waiting for inlay hint request range edits")?;
5740 lsp_request_task.await.context("inlay hints LSP request")
5741 })
5742 }
5743 }
5744
5745 pub fn signature_help<T: ToPointUtf16>(
5746 &mut self,
5747 buffer: &Entity<Buffer>,
5748 position: T,
5749 cx: &mut Context<Self>,
5750 ) -> Task<Vec<SignatureHelp>> {
5751 let position = position.to_point_utf16(buffer.read(cx));
5752
5753 if let Some((client, upstream_project_id)) = self.upstream_client() {
5754 let request_task = client.request(proto::MultiLspQuery {
5755 buffer_id: buffer.read(cx).remote_id().into(),
5756 version: serialize_version(&buffer.read(cx).version()),
5757 project_id: upstream_project_id,
5758 strategy: Some(proto::multi_lsp_query::Strategy::All(
5759 proto::AllLanguageServers {},
5760 )),
5761 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
5762 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
5763 )),
5764 });
5765 let buffer = buffer.clone();
5766 cx.spawn(async move |weak_project, cx| {
5767 let Some(project) = weak_project.upgrade() else {
5768 return Vec::new();
5769 };
5770 join_all(
5771 request_task
5772 .await
5773 .log_err()
5774 .map(|response| response.responses)
5775 .unwrap_or_default()
5776 .into_iter()
5777 .filter_map(|lsp_response| match lsp_response.response? {
5778 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
5779 Some(response)
5780 }
5781 unexpected => {
5782 debug_panic!("Unexpected response: {unexpected:?}");
5783 None
5784 }
5785 })
5786 .map(|signature_response| {
5787 let response = GetSignatureHelp { position }.response_from_proto(
5788 signature_response,
5789 project.clone(),
5790 buffer.clone(),
5791 cx.clone(),
5792 );
5793 async move { response.await.log_err().flatten() }
5794 }),
5795 )
5796 .await
5797 .into_iter()
5798 .flatten()
5799 .collect()
5800 })
5801 } else {
5802 let all_actions_task = self.request_multiple_lsp_locally(
5803 buffer,
5804 Some(position),
5805 GetSignatureHelp { position },
5806 cx,
5807 );
5808 cx.spawn(async move |_, _| {
5809 all_actions_task
5810 .await
5811 .into_iter()
5812 .flatten()
5813 .filter(|help| !help.label.is_empty())
5814 .collect::<Vec<_>>()
5815 })
5816 }
5817 }
5818
5819 pub fn hover(
5820 &mut self,
5821 buffer: &Entity<Buffer>,
5822 position: PointUtf16,
5823 cx: &mut Context<Self>,
5824 ) -> Task<Vec<Hover>> {
5825 if let Some((client, upstream_project_id)) = self.upstream_client() {
5826 let request_task = client.request(proto::MultiLspQuery {
5827 buffer_id: buffer.read(cx).remote_id().into(),
5828 version: serialize_version(&buffer.read(cx).version()),
5829 project_id: upstream_project_id,
5830 strategy: Some(proto::multi_lsp_query::Strategy::All(
5831 proto::AllLanguageServers {},
5832 )),
5833 request: Some(proto::multi_lsp_query::Request::GetHover(
5834 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
5835 )),
5836 });
5837 let buffer = buffer.clone();
5838 cx.spawn(async move |weak_project, cx| {
5839 let Some(project) = weak_project.upgrade() else {
5840 return Vec::new();
5841 };
5842 join_all(
5843 request_task
5844 .await
5845 .log_err()
5846 .map(|response| response.responses)
5847 .unwrap_or_default()
5848 .into_iter()
5849 .filter_map(|lsp_response| match lsp_response.response? {
5850 proto::lsp_response::Response::GetHoverResponse(response) => {
5851 Some(response)
5852 }
5853 unexpected => {
5854 debug_panic!("Unexpected response: {unexpected:?}");
5855 None
5856 }
5857 })
5858 .map(|hover_response| {
5859 let response = GetHover { position }.response_from_proto(
5860 hover_response,
5861 project.clone(),
5862 buffer.clone(),
5863 cx.clone(),
5864 );
5865 async move {
5866 response
5867 .await
5868 .log_err()
5869 .flatten()
5870 .and_then(remove_empty_hover_blocks)
5871 }
5872 }),
5873 )
5874 .await
5875 .into_iter()
5876 .flatten()
5877 .collect()
5878 })
5879 } else {
5880 let all_actions_task = self.request_multiple_lsp_locally(
5881 buffer,
5882 Some(position),
5883 GetHover { position },
5884 cx,
5885 );
5886 cx.spawn(async move |_, _| {
5887 all_actions_task
5888 .await
5889 .into_iter()
5890 .filter_map(|hover| remove_empty_hover_blocks(hover?))
5891 .collect::<Vec<Hover>>()
5892 })
5893 }
5894 }
5895
5896 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
5897 let language_registry = self.languages.clone();
5898
5899 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
5900 let request = upstream_client.request(proto::GetProjectSymbols {
5901 project_id: *project_id,
5902 query: query.to_string(),
5903 });
5904 cx.foreground_executor().spawn(async move {
5905 let response = request.await?;
5906 let mut symbols = Vec::new();
5907 let core_symbols = response
5908 .symbols
5909 .into_iter()
5910 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
5911 .collect::<Vec<_>>();
5912 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
5913 .await;
5914 Ok(symbols)
5915 })
5916 } else if let Some(local) = self.as_local() {
5917 struct WorkspaceSymbolsResult {
5918 server_id: LanguageServerId,
5919 lsp_adapter: Arc<CachedLspAdapter>,
5920 worktree: WeakEntity<Worktree>,
5921 worktree_abs_path: Arc<Path>,
5922 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
5923 }
5924
5925 let mut requests = Vec::new();
5926 let mut requested_servers = BTreeSet::new();
5927 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
5928 let Some(worktree_handle) = self
5929 .worktree_store
5930 .read(cx)
5931 .worktree_for_id(*worktree_id, cx)
5932 else {
5933 continue;
5934 };
5935 let worktree = worktree_handle.read(cx);
5936 if !worktree.is_visible() {
5937 continue;
5938 }
5939
5940 let mut servers_to_query = server_ids
5941 .difference(&requested_servers)
5942 .cloned()
5943 .collect::<BTreeSet<_>>();
5944 for server_id in &servers_to_query {
5945 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
5946 Some(LanguageServerState::Running {
5947 adapter, server, ..
5948 }) => (adapter.clone(), server),
5949
5950 _ => continue 'next_server,
5951 };
5952 let supports_workspace_symbol_request =
5953 match server.capabilities().workspace_symbol_provider {
5954 Some(OneOf::Left(supported)) => supported,
5955 Some(OneOf::Right(_)) => true,
5956 None => false,
5957 };
5958 if !supports_workspace_symbol_request {
5959 continue 'next_server;
5960 }
5961 let worktree_abs_path = worktree.abs_path().clone();
5962 let worktree_handle = worktree_handle.clone();
5963 let server_id = server.server_id();
5964 requests.push(
5965 server
5966 .request::<lsp::request::WorkspaceSymbolRequest>(
5967 lsp::WorkspaceSymbolParams {
5968 query: query.to_string(),
5969 ..Default::default()
5970 },
5971 )
5972 .map(move |response| {
5973 let lsp_symbols = response.into_response()
5974 .context("workspace symbols request")
5975 .log_err()
5976 .flatten()
5977 .map(|symbol_response| match symbol_response {
5978 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
5979 flat_responses.into_iter().map(|lsp_symbol| {
5980 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
5981 }).collect::<Vec<_>>()
5982 }
5983 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
5984 nested_responses.into_iter().filter_map(|lsp_symbol| {
5985 let location = match lsp_symbol.location {
5986 OneOf::Left(location) => location,
5987 OneOf::Right(_) => {
5988 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
5989 return None
5990 }
5991 };
5992 Some((lsp_symbol.name, lsp_symbol.kind, location))
5993 }).collect::<Vec<_>>()
5994 }
5995 }).unwrap_or_default();
5996
5997 WorkspaceSymbolsResult {
5998 server_id,
5999 lsp_adapter,
6000 worktree: worktree_handle.downgrade(),
6001 worktree_abs_path,
6002 lsp_symbols,
6003 }
6004 }),
6005 );
6006 }
6007 requested_servers.append(&mut servers_to_query);
6008 }
6009
6010 cx.spawn(async move |this, cx| {
6011 let responses = futures::future::join_all(requests).await;
6012 let this = match this.upgrade() {
6013 Some(this) => this,
6014 None => return Ok(Vec::new()),
6015 };
6016
6017 let mut symbols = Vec::new();
6018 for result in responses {
6019 let core_symbols = this.update(cx, |this, cx| {
6020 result
6021 .lsp_symbols
6022 .into_iter()
6023 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
6024 let abs_path = symbol_location.uri.to_file_path().ok()?;
6025 let source_worktree = result.worktree.upgrade()?;
6026 let source_worktree_id = source_worktree.read(cx).id();
6027
6028 let path;
6029 let worktree;
6030 if let Some((tree, rel_path)) =
6031 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
6032 {
6033 worktree = tree;
6034 path = rel_path;
6035 } else {
6036 worktree = source_worktree.clone();
6037 path = relativize_path(&result.worktree_abs_path, &abs_path);
6038 }
6039
6040 let worktree_id = worktree.read(cx).id();
6041 let project_path = ProjectPath {
6042 worktree_id,
6043 path: path.into(),
6044 };
6045 let signature = this.symbol_signature(&project_path);
6046 Some(CoreSymbol {
6047 source_language_server_id: result.server_id,
6048 language_server_name: result.lsp_adapter.name.clone(),
6049 source_worktree_id,
6050 path: project_path,
6051 kind: symbol_kind,
6052 name: symbol_name,
6053 range: range_from_lsp(symbol_location.range),
6054 signature,
6055 })
6056 })
6057 .collect()
6058 })?;
6059
6060 populate_labels_for_symbols(
6061 core_symbols,
6062 &language_registry,
6063 Some(result.lsp_adapter),
6064 &mut symbols,
6065 )
6066 .await;
6067 }
6068
6069 Ok(symbols)
6070 })
6071 } else {
6072 Task::ready(Err(anyhow!("No upstream client or local language server")))
6073 }
6074 }
6075
6076 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
6077 let mut summary = DiagnosticSummary::default();
6078 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
6079 summary.error_count += path_summary.error_count;
6080 summary.warning_count += path_summary.warning_count;
6081 }
6082 summary
6083 }
6084
6085 pub fn diagnostic_summaries<'a>(
6086 &'a self,
6087 include_ignored: bool,
6088 cx: &'a App,
6089 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6090 self.worktree_store
6091 .read(cx)
6092 .visible_worktrees(cx)
6093 .filter_map(|worktree| {
6094 let worktree = worktree.read(cx);
6095 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
6096 })
6097 .flat_map(move |(worktree, summaries)| {
6098 let worktree_id = worktree.id();
6099 summaries
6100 .iter()
6101 .filter(move |(path, _)| {
6102 include_ignored
6103 || worktree
6104 .entry_for_path(path.as_ref())
6105 .map_or(false, |entry| !entry.is_ignored)
6106 })
6107 .flat_map(move |(path, summaries)| {
6108 summaries.iter().map(move |(server_id, summary)| {
6109 (
6110 ProjectPath {
6111 worktree_id,
6112 path: path.clone(),
6113 },
6114 *server_id,
6115 *summary,
6116 )
6117 })
6118 })
6119 })
6120 }
6121
6122 pub fn on_buffer_edited(
6123 &mut self,
6124 buffer: Entity<Buffer>,
6125 cx: &mut Context<Self>,
6126 ) -> Option<()> {
6127 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
6128 Some(
6129 self.as_local()?
6130 .language_servers_for_buffer(buffer, cx)
6131 .map(|i| i.1.clone())
6132 .collect(),
6133 )
6134 })?;
6135
6136 let buffer = buffer.read(cx);
6137 let file = File::from_dyn(buffer.file())?;
6138 let abs_path = file.as_local()?.abs_path(cx);
6139 let uri = lsp::Url::from_file_path(abs_path).unwrap();
6140 let next_snapshot = buffer.text_snapshot();
6141 for language_server in language_servers {
6142 let language_server = language_server.clone();
6143
6144 let buffer_snapshots = self
6145 .as_local_mut()
6146 .unwrap()
6147 .buffer_snapshots
6148 .get_mut(&buffer.remote_id())
6149 .and_then(|m| m.get_mut(&language_server.server_id()))?;
6150 let previous_snapshot = buffer_snapshots.last()?;
6151
6152 let build_incremental_change = || {
6153 buffer
6154 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6155 .map(|edit| {
6156 let edit_start = edit.new.start.0;
6157 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6158 let new_text = next_snapshot
6159 .text_for_range(edit.new.start.1..edit.new.end.1)
6160 .collect();
6161 lsp::TextDocumentContentChangeEvent {
6162 range: Some(lsp::Range::new(
6163 point_to_lsp(edit_start),
6164 point_to_lsp(edit_end),
6165 )),
6166 range_length: None,
6167 text: new_text,
6168 }
6169 })
6170 .collect()
6171 };
6172
6173 let document_sync_kind = language_server
6174 .capabilities()
6175 .text_document_sync
6176 .as_ref()
6177 .and_then(|sync| match sync {
6178 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6179 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6180 });
6181
6182 let content_changes: Vec<_> = match document_sync_kind {
6183 Some(lsp::TextDocumentSyncKind::FULL) => {
6184 vec![lsp::TextDocumentContentChangeEvent {
6185 range: None,
6186 range_length: None,
6187 text: next_snapshot.text(),
6188 }]
6189 }
6190 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6191 _ => {
6192 #[cfg(any(test, feature = "test-support"))]
6193 {
6194 build_incremental_change()
6195 }
6196
6197 #[cfg(not(any(test, feature = "test-support")))]
6198 {
6199 continue;
6200 }
6201 }
6202 };
6203
6204 let next_version = previous_snapshot.version + 1;
6205 buffer_snapshots.push(LspBufferSnapshot {
6206 version: next_version,
6207 snapshot: next_snapshot.clone(),
6208 });
6209
6210 language_server
6211 .notify::<lsp::notification::DidChangeTextDocument>(
6212 &lsp::DidChangeTextDocumentParams {
6213 text_document: lsp::VersionedTextDocumentIdentifier::new(
6214 uri.clone(),
6215 next_version,
6216 ),
6217 content_changes,
6218 },
6219 )
6220 .ok();
6221 }
6222
6223 None
6224 }
6225
6226 pub fn on_buffer_saved(
6227 &mut self,
6228 buffer: Entity<Buffer>,
6229 cx: &mut Context<Self>,
6230 ) -> Option<()> {
6231 let file = File::from_dyn(buffer.read(cx).file())?;
6232 let worktree_id = file.worktree_id(cx);
6233 let abs_path = file.as_local()?.abs_path(cx);
6234 let text_document = lsp::TextDocumentIdentifier {
6235 uri: lsp::Url::from_file_path(abs_path).log_err()?,
6236 };
6237 let local = self.as_local()?;
6238
6239 for server in local.language_servers_for_worktree(worktree_id) {
6240 if let Some(include_text) = include_text(server.as_ref()) {
6241 let text = if include_text {
6242 Some(buffer.read(cx).text())
6243 } else {
6244 None
6245 };
6246 server
6247 .notify::<lsp::notification::DidSaveTextDocument>(
6248 &lsp::DidSaveTextDocumentParams {
6249 text_document: text_document.clone(),
6250 text,
6251 },
6252 )
6253 .ok();
6254 }
6255 }
6256
6257 let language_servers = buffer.update(cx, |buffer, cx| {
6258 local.language_server_ids_for_buffer(buffer, cx)
6259 });
6260 for language_server_id in language_servers {
6261 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6262 }
6263
6264 None
6265 }
6266
6267 pub(crate) async fn refresh_workspace_configurations(
6268 this: &WeakEntity<Self>,
6269 fs: Arc<dyn Fs>,
6270 cx: &mut AsyncApp,
6271 ) {
6272 maybe!(async move {
6273 let servers = this
6274 .update(cx, |this, cx| {
6275 let Some(local) = this.as_local() else {
6276 return Vec::default();
6277 };
6278 local
6279 .language_server_ids
6280 .iter()
6281 .flat_map(|((worktree_id, _), server_ids)| {
6282 let worktree = this
6283 .worktree_store
6284 .read(cx)
6285 .worktree_for_id(*worktree_id, cx);
6286 let delegate = worktree.map(|worktree| {
6287 LocalLspAdapterDelegate::new(
6288 local.languages.clone(),
6289 &local.environment,
6290 cx.weak_entity(),
6291 &worktree,
6292 local.http_client.clone(),
6293 local.fs.clone(),
6294 cx,
6295 )
6296 });
6297
6298 server_ids.iter().filter_map(move |server_id| {
6299 let states = local.language_servers.get(server_id)?;
6300
6301 match states {
6302 LanguageServerState::Starting { .. } => None,
6303 LanguageServerState::Running {
6304 adapter, server, ..
6305 } => Some((
6306 adapter.adapter.clone(),
6307 server.clone(),
6308 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
6309 )),
6310 }
6311 })
6312 })
6313 .collect::<Vec<_>>()
6314 })
6315 .ok()?;
6316
6317 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
6318 for (adapter, server, delegate) in servers {
6319 let settings = LocalLspStore::workspace_configuration_for_adapter(
6320 adapter,
6321 fs.as_ref(),
6322 &delegate,
6323 toolchain_store.clone(),
6324 cx,
6325 )
6326 .await
6327 .ok()?;
6328
6329 server
6330 .notify::<lsp::notification::DidChangeConfiguration>(
6331 &lsp::DidChangeConfigurationParams { settings },
6332 )
6333 .ok();
6334 }
6335 Some(())
6336 })
6337 .await;
6338 }
6339
6340 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
6341 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
6342 toolchain_store.read(cx).as_language_toolchain_store()
6343 } else {
6344 Arc::new(EmptyToolchainStore)
6345 }
6346 }
6347 fn maintain_workspace_config(
6348 fs: Arc<dyn Fs>,
6349 external_refresh_requests: watch::Receiver<()>,
6350 cx: &mut Context<Self>,
6351 ) -> Task<Result<()>> {
6352 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
6353 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
6354
6355 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
6356 *settings_changed_tx.borrow_mut() = ();
6357 });
6358
6359 let mut joint_future =
6360 futures::stream::select(settings_changed_rx, external_refresh_requests);
6361 cx.spawn(async move |this, cx| {
6362 while let Some(()) = joint_future.next().await {
6363 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
6364 }
6365
6366 drop(settings_observation);
6367 anyhow::Ok(())
6368 })
6369 }
6370
6371 pub fn language_servers_for_local_buffer<'a>(
6372 &'a self,
6373 buffer: &Buffer,
6374 cx: &mut App,
6375 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6376 let local = self.as_local();
6377 let language_server_ids = local
6378 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
6379 .unwrap_or_default();
6380
6381 language_server_ids
6382 .into_iter()
6383 .filter_map(
6384 move |server_id| match local?.language_servers.get(&server_id)? {
6385 LanguageServerState::Running {
6386 adapter, server, ..
6387 } => Some((adapter, server)),
6388 _ => None,
6389 },
6390 )
6391 }
6392
6393 pub fn language_server_for_local_buffer<'a>(
6394 &'a self,
6395 buffer: &'a Buffer,
6396 server_id: LanguageServerId,
6397 cx: &'a mut App,
6398 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6399 self.as_local()?
6400 .language_servers_for_buffer(buffer, cx)
6401 .find(|(_, s)| s.server_id() == server_id)
6402 }
6403
6404 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
6405 self.diagnostic_summaries.remove(&id_to_remove);
6406 if let Some(local) = self.as_local_mut() {
6407 let to_remove = local.remove_worktree(id_to_remove, cx);
6408 for server in to_remove {
6409 self.language_server_statuses.remove(&server);
6410 }
6411 }
6412 }
6413
6414 pub fn shared(
6415 &mut self,
6416 project_id: u64,
6417 downstream_client: AnyProtoClient,
6418 _: &mut Context<Self>,
6419 ) {
6420 self.downstream_client = Some((downstream_client.clone(), project_id));
6421
6422 for (server_id, status) in &self.language_server_statuses {
6423 downstream_client
6424 .send(proto::StartLanguageServer {
6425 project_id,
6426 server: Some(proto::LanguageServer {
6427 id: server_id.0 as u64,
6428 name: status.name.clone(),
6429 worktree_id: None,
6430 }),
6431 })
6432 .log_err();
6433 }
6434 }
6435
6436 pub fn disconnected_from_host(&mut self) {
6437 self.downstream_client.take();
6438 }
6439
6440 pub fn disconnected_from_ssh_remote(&mut self) {
6441 if let LspStoreMode::Remote(RemoteLspStore {
6442 upstream_client, ..
6443 }) = &mut self.mode
6444 {
6445 upstream_client.take();
6446 }
6447 }
6448
6449 pub(crate) fn set_language_server_statuses_from_proto(
6450 &mut self,
6451 language_servers: Vec<proto::LanguageServer>,
6452 ) {
6453 self.language_server_statuses = language_servers
6454 .into_iter()
6455 .map(|server| {
6456 (
6457 LanguageServerId(server.id as usize),
6458 LanguageServerStatus {
6459 name: server.name,
6460 pending_work: Default::default(),
6461 has_pending_diagnostic_updates: false,
6462 progress_tokens: Default::default(),
6463 },
6464 )
6465 })
6466 .collect();
6467 }
6468
6469 fn register_local_language_server(
6470 &mut self,
6471 worktree: Entity<Worktree>,
6472 language_server_name: LanguageServerName,
6473 language_server_id: LanguageServerId,
6474 cx: &mut App,
6475 ) {
6476 let Some(local) = self.as_local_mut() else {
6477 return;
6478 };
6479
6480 let worktree_id = worktree.read(cx).id();
6481 if worktree.read(cx).is_visible() {
6482 let path = ProjectPath {
6483 worktree_id,
6484 path: Arc::from("".as_ref()),
6485 };
6486 let delegate = LocalLspAdapterDelegate::from_local_lsp(local, &worktree, cx);
6487 local.lsp_tree.update(cx, |language_server_tree, cx| {
6488 for node in language_server_tree.get(
6489 path,
6490 AdapterQuery::Adapter(&language_server_name),
6491 delegate,
6492 cx,
6493 ) {
6494 node.server_id_or_init(|disposition| {
6495 assert_eq!(disposition.server_name, &language_server_name);
6496
6497 language_server_id
6498 });
6499 }
6500 });
6501 }
6502
6503 local
6504 .language_server_ids
6505 .entry((worktree_id, language_server_name))
6506 .or_default()
6507 .insert(language_server_id);
6508 }
6509
6510 pub fn update_diagnostic_entries(
6511 &mut self,
6512 server_id: LanguageServerId,
6513 abs_path: PathBuf,
6514 version: Option<i32>,
6515 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6516 cx: &mut Context<Self>,
6517 ) -> anyhow::Result<()> {
6518 self.merge_diagnostic_entries(server_id, abs_path, version, diagnostics, |_, _| false, cx)
6519 }
6520
6521 pub fn merge_diagnostic_entries<F: Fn(&Diagnostic, &App) -> bool + Clone>(
6522 &mut self,
6523 server_id: LanguageServerId,
6524 abs_path: PathBuf,
6525 version: Option<i32>,
6526 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6527 filter: F,
6528 cx: &mut Context<Self>,
6529 ) -> Result<(), anyhow::Error> {
6530 let Some((worktree, relative_path)) =
6531 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
6532 else {
6533 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
6534 return Ok(());
6535 };
6536
6537 let project_path = ProjectPath {
6538 worktree_id: worktree.read(cx).id(),
6539 path: relative_path.into(),
6540 };
6541
6542 if let Some(buffer) = self.buffer_store.read(cx).get_by_path(&project_path, cx) {
6543 let snapshot = self
6544 .as_local_mut()
6545 .unwrap()
6546 .buffer_snapshot_for_lsp_version(&buffer, server_id, version, cx)?;
6547
6548 diagnostics.extend(
6549 buffer
6550 .read(cx)
6551 .get_diagnostics(server_id)
6552 .into_iter()
6553 .flat_map(|diag| {
6554 diag.iter().filter(|v| filter(&v.diagnostic, cx)).map(|v| {
6555 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
6556 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
6557 DiagnosticEntry {
6558 range: start..end,
6559 diagnostic: v.diagnostic.clone(),
6560 }
6561 })
6562 }),
6563 );
6564
6565 self.as_local_mut().unwrap().update_buffer_diagnostics(
6566 &buffer,
6567 server_id,
6568 version,
6569 diagnostics.clone(),
6570 cx,
6571 )?;
6572 }
6573
6574 let updated = worktree.update(cx, |worktree, cx| {
6575 self.update_worktree_diagnostics(
6576 worktree.id(),
6577 server_id,
6578 project_path.path.clone(),
6579 diagnostics,
6580 cx,
6581 )
6582 })?;
6583 if updated {
6584 cx.emit(LspStoreEvent::DiagnosticsUpdated {
6585 language_server_id: server_id,
6586 path: project_path,
6587 })
6588 }
6589 Ok(())
6590 }
6591
6592 fn update_worktree_diagnostics(
6593 &mut self,
6594 worktree_id: WorktreeId,
6595 server_id: LanguageServerId,
6596 worktree_path: Arc<Path>,
6597 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6598 _: &mut Context<Worktree>,
6599 ) -> Result<bool> {
6600 let local = match &mut self.mode {
6601 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
6602 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
6603 };
6604
6605 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
6606 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
6607 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
6608
6609 let old_summary = summaries_by_server_id
6610 .remove(&server_id)
6611 .unwrap_or_default();
6612
6613 let new_summary = DiagnosticSummary::new(&diagnostics);
6614 if new_summary.is_empty() {
6615 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
6616 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6617 diagnostics_by_server_id.remove(ix);
6618 }
6619 if diagnostics_by_server_id.is_empty() {
6620 diagnostics_for_tree.remove(&worktree_path);
6621 }
6622 }
6623 } else {
6624 summaries_by_server_id.insert(server_id, new_summary);
6625 let diagnostics_by_server_id = diagnostics_for_tree
6626 .entry(worktree_path.clone())
6627 .or_default();
6628 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6629 Ok(ix) => {
6630 diagnostics_by_server_id[ix] = (server_id, diagnostics);
6631 }
6632 Err(ix) => {
6633 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
6634 }
6635 }
6636 }
6637
6638 if !old_summary.is_empty() || !new_summary.is_empty() {
6639 if let Some((downstream_client, project_id)) = &self.downstream_client {
6640 downstream_client
6641 .send(proto::UpdateDiagnosticSummary {
6642 project_id: *project_id,
6643 worktree_id: worktree_id.to_proto(),
6644 summary: Some(proto::DiagnosticSummary {
6645 path: worktree_path.to_proto(),
6646 language_server_id: server_id.0 as u64,
6647 error_count: new_summary.error_count as u32,
6648 warning_count: new_summary.warning_count as u32,
6649 }),
6650 })
6651 .log_err();
6652 }
6653 }
6654
6655 Ok(!old_summary.is_empty() || !new_summary.is_empty())
6656 }
6657
6658 pub fn open_buffer_for_symbol(
6659 &mut self,
6660 symbol: &Symbol,
6661 cx: &mut Context<Self>,
6662 ) -> Task<Result<Entity<Buffer>>> {
6663 if let Some((client, project_id)) = self.upstream_client() {
6664 let request = client.request(proto::OpenBufferForSymbol {
6665 project_id,
6666 symbol: Some(Self::serialize_symbol(symbol)),
6667 });
6668 cx.spawn(async move |this, cx| {
6669 let response = request.await?;
6670 let buffer_id = BufferId::new(response.buffer_id)?;
6671 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
6672 .await
6673 })
6674 } else if let Some(local) = self.as_local() {
6675 let Some(language_server_id) = local
6676 .language_server_ids
6677 .get(&(
6678 symbol.source_worktree_id,
6679 symbol.language_server_name.clone(),
6680 ))
6681 .and_then(|ids| {
6682 ids.contains(&symbol.source_language_server_id)
6683 .then_some(symbol.source_language_server_id)
6684 })
6685 else {
6686 return Task::ready(Err(anyhow!(
6687 "language server for worktree and language not found"
6688 )));
6689 };
6690
6691 let worktree_abs_path = if let Some(worktree_abs_path) = self
6692 .worktree_store
6693 .read(cx)
6694 .worktree_for_id(symbol.path.worktree_id, cx)
6695 .map(|worktree| worktree.read(cx).abs_path())
6696 {
6697 worktree_abs_path
6698 } else {
6699 return Task::ready(Err(anyhow!("worktree not found for symbol")));
6700 };
6701
6702 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
6703 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
6704 uri
6705 } else {
6706 return Task::ready(Err(anyhow!("invalid symbol path")));
6707 };
6708
6709 self.open_local_buffer_via_lsp(
6710 symbol_uri,
6711 language_server_id,
6712 symbol.language_server_name.clone(),
6713 cx,
6714 )
6715 } else {
6716 Task::ready(Err(anyhow!("no upstream client or local store")))
6717 }
6718 }
6719
6720 pub fn open_local_buffer_via_lsp(
6721 &mut self,
6722 mut abs_path: lsp::Url,
6723 language_server_id: LanguageServerId,
6724 language_server_name: LanguageServerName,
6725 cx: &mut Context<Self>,
6726 ) -> Task<Result<Entity<Buffer>>> {
6727 cx.spawn(async move |lsp_store, cx| {
6728 // Escape percent-encoded string.
6729 let current_scheme = abs_path.scheme().to_owned();
6730 let _ = abs_path.set_scheme("file");
6731
6732 let abs_path = abs_path
6733 .to_file_path()
6734 .map_err(|_| anyhow!("can't convert URI to path"))?;
6735 let p = abs_path.clone();
6736 let yarn_worktree = lsp_store
6737 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
6738 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
6739 cx.spawn(async move |this, cx| {
6740 let t = this
6741 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
6742 .ok()?;
6743 t.await
6744 })
6745 }),
6746 None => Task::ready(None),
6747 })?
6748 .await;
6749 let (worktree_root_target, known_relative_path) =
6750 if let Some((zip_root, relative_path)) = yarn_worktree {
6751 (zip_root, Some(relative_path))
6752 } else {
6753 (Arc::<Path>::from(abs_path.as_path()), None)
6754 };
6755 let (worktree, relative_path) = if let Some(result) =
6756 lsp_store.update(cx, |lsp_store, cx| {
6757 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6758 worktree_store.find_worktree(&worktree_root_target, cx)
6759 })
6760 })? {
6761 let relative_path =
6762 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
6763 (result.0, relative_path)
6764 } else {
6765 let worktree = lsp_store
6766 .update(cx, |lsp_store, cx| {
6767 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6768 worktree_store.create_worktree(&worktree_root_target, false, cx)
6769 })
6770 })?
6771 .await?;
6772 if worktree.update(cx, |worktree, _| worktree.is_local())? {
6773 lsp_store
6774 .update(cx, |lsp_store, cx| {
6775 lsp_store.register_local_language_server(
6776 worktree.clone(),
6777 language_server_name,
6778 language_server_id,
6779 cx,
6780 )
6781 })
6782 .ok();
6783 }
6784 let worktree_root = worktree.update(cx, |worktree, _| worktree.abs_path())?;
6785 let relative_path = if let Some(known_path) = known_relative_path {
6786 known_path
6787 } else {
6788 abs_path.strip_prefix(worktree_root)?.into()
6789 };
6790 (worktree, relative_path)
6791 };
6792 let project_path = ProjectPath {
6793 worktree_id: worktree.update(cx, |worktree, _| worktree.id())?,
6794 path: relative_path,
6795 };
6796 lsp_store
6797 .update(cx, |lsp_store, cx| {
6798 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
6799 buffer_store.open_buffer(project_path, cx)
6800 })
6801 })?
6802 .await
6803 })
6804 }
6805
6806 fn request_multiple_lsp_locally<P, R>(
6807 &mut self,
6808 buffer: &Entity<Buffer>,
6809 position: Option<P>,
6810 request: R,
6811 cx: &mut Context<Self>,
6812 ) -> Task<Vec<R::Response>>
6813 where
6814 P: ToOffset,
6815 R: LspCommand + Clone,
6816 <R::LspRequest as lsp::request::Request>::Result: Send,
6817 <R::LspRequest as lsp::request::Request>::Params: Send,
6818 {
6819 let Some(local) = self.as_local() else {
6820 return Task::ready(Vec::new());
6821 };
6822
6823 let snapshot = buffer.read(cx).snapshot();
6824 let scope = position.and_then(|position| snapshot.language_scope_at(position));
6825
6826 let server_ids = buffer.update(cx, |buffer, cx| {
6827 local
6828 .language_servers_for_buffer(buffer, cx)
6829 .filter(|(adapter, _)| {
6830 scope
6831 .as_ref()
6832 .map(|scope| scope.language_allowed(&adapter.name))
6833 .unwrap_or(true)
6834 })
6835 .map(|(_, server)| server.server_id())
6836 .collect::<Vec<_>>()
6837 });
6838
6839 let mut response_results = server_ids
6840 .into_iter()
6841 .map(|server_id| {
6842 self.request_lsp(
6843 buffer.clone(),
6844 LanguageServerToQuery::Other(server_id),
6845 request.clone(),
6846 cx,
6847 )
6848 })
6849 .collect::<FuturesUnordered<_>>();
6850
6851 cx.spawn(async move |_, _| {
6852 let mut responses = Vec::with_capacity(response_results.len());
6853 while let Some(response_result) = response_results.next().await {
6854 if let Some(response) = response_result.log_err() {
6855 responses.push(response);
6856 }
6857 }
6858 responses
6859 })
6860 }
6861
6862 async fn handle_lsp_command<T: LspCommand>(
6863 this: Entity<Self>,
6864 envelope: TypedEnvelope<T::ProtoRequest>,
6865 mut cx: AsyncApp,
6866 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6867 where
6868 <T::LspRequest as lsp::request::Request>::Params: Send,
6869 <T::LspRequest as lsp::request::Request>::Result: Send,
6870 {
6871 let sender_id = envelope.original_sender_id().unwrap_or_default();
6872 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
6873 let buffer_handle = this.update(&mut cx, |this, cx| {
6874 this.buffer_store.read(cx).get_existing(buffer_id)
6875 })??;
6876 let request = T::from_proto(
6877 envelope.payload,
6878 this.clone(),
6879 buffer_handle.clone(),
6880 cx.clone(),
6881 )
6882 .await?;
6883 let response = this
6884 .update(&mut cx, |this, cx| {
6885 this.request_lsp(
6886 buffer_handle.clone(),
6887 LanguageServerToQuery::FirstCapable,
6888 request,
6889 cx,
6890 )
6891 })?
6892 .await?;
6893 this.update(&mut cx, |this, cx| {
6894 Ok(T::response_to_proto(
6895 response,
6896 this,
6897 sender_id,
6898 &buffer_handle.read(cx).version(),
6899 cx,
6900 ))
6901 })?
6902 }
6903
6904 async fn handle_multi_lsp_query(
6905 this: Entity<Self>,
6906 envelope: TypedEnvelope<proto::MultiLspQuery>,
6907 mut cx: AsyncApp,
6908 ) -> Result<proto::MultiLspQueryResponse> {
6909 let response_from_ssh = this.update(&mut cx, |this, _| {
6910 let (upstream_client, project_id) = this.upstream_client()?;
6911 let mut payload = envelope.payload.clone();
6912 payload.project_id = project_id;
6913
6914 Some(upstream_client.request(payload))
6915 })?;
6916 if let Some(response_from_ssh) = response_from_ssh {
6917 return response_from_ssh.await;
6918 }
6919
6920 let sender_id = envelope.original_sender_id().unwrap_or_default();
6921 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6922 let version = deserialize_version(&envelope.payload.version);
6923 let buffer = this.update(&mut cx, |this, cx| {
6924 this.buffer_store.read(cx).get_existing(buffer_id)
6925 })??;
6926 buffer
6927 .update(&mut cx, |buffer, _| {
6928 buffer.wait_for_version(version.clone())
6929 })?
6930 .await?;
6931 let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
6932 match envelope
6933 .payload
6934 .strategy
6935 .context("invalid request without the strategy")?
6936 {
6937 proto::multi_lsp_query::Strategy::All(_) => {
6938 // currently, there's only one multiple language servers query strategy,
6939 // so just ensure it's specified correctly
6940 }
6941 }
6942 match envelope.payload.request {
6943 Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
6944 let get_hover =
6945 GetHover::from_proto(get_hover, this.clone(), buffer.clone(), cx.clone())
6946 .await?;
6947 let all_hovers = this
6948 .update(&mut cx, |this, cx| {
6949 this.request_multiple_lsp_locally(
6950 &buffer,
6951 Some(get_hover.position),
6952 get_hover,
6953 cx,
6954 )
6955 })?
6956 .await
6957 .into_iter()
6958 .filter_map(|hover| remove_empty_hover_blocks(hover?));
6959 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6960 responses: all_hovers
6961 .map(|hover| proto::LspResponse {
6962 response: Some(proto::lsp_response::Response::GetHoverResponse(
6963 GetHover::response_to_proto(
6964 Some(hover),
6965 project,
6966 sender_id,
6967 &buffer_version,
6968 cx,
6969 ),
6970 )),
6971 })
6972 .collect(),
6973 })
6974 }
6975 Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
6976 let get_code_actions = GetCodeActions::from_proto(
6977 get_code_actions,
6978 this.clone(),
6979 buffer.clone(),
6980 cx.clone(),
6981 )
6982 .await?;
6983
6984 let all_actions = this
6985 .update(&mut cx, |project, cx| {
6986 project.request_multiple_lsp_locally(
6987 &buffer,
6988 Some(get_code_actions.range.start),
6989 get_code_actions,
6990 cx,
6991 )
6992 })?
6993 .await
6994 .into_iter();
6995
6996 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6997 responses: all_actions
6998 .map(|code_actions| proto::LspResponse {
6999 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
7000 GetCodeActions::response_to_proto(
7001 code_actions,
7002 project,
7003 sender_id,
7004 &buffer_version,
7005 cx,
7006 ),
7007 )),
7008 })
7009 .collect(),
7010 })
7011 }
7012 Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
7013 let get_signature_help = GetSignatureHelp::from_proto(
7014 get_signature_help,
7015 this.clone(),
7016 buffer.clone(),
7017 cx.clone(),
7018 )
7019 .await?;
7020
7021 let all_signatures = this
7022 .update(&mut cx, |project, cx| {
7023 project.request_multiple_lsp_locally(
7024 &buffer,
7025 Some(get_signature_help.position),
7026 get_signature_help,
7027 cx,
7028 )
7029 })?
7030 .await
7031 .into_iter();
7032
7033 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7034 responses: all_signatures
7035 .map(|signature_help| proto::LspResponse {
7036 response: Some(
7037 proto::lsp_response::Response::GetSignatureHelpResponse(
7038 GetSignatureHelp::response_to_proto(
7039 signature_help,
7040 project,
7041 sender_id,
7042 &buffer_version,
7043 cx,
7044 ),
7045 ),
7046 ),
7047 })
7048 .collect(),
7049 })
7050 }
7051 Some(proto::multi_lsp_query::Request::GetCodeLens(get_code_lens)) => {
7052 let get_code_lens = GetCodeLens::from_proto(
7053 get_code_lens,
7054 this.clone(),
7055 buffer.clone(),
7056 cx.clone(),
7057 )
7058 .await?;
7059
7060 let code_lens_actions = this
7061 .update(&mut cx, |project, cx| {
7062 project.request_multiple_lsp_locally(
7063 &buffer,
7064 None::<usize>,
7065 get_code_lens,
7066 cx,
7067 )
7068 })?
7069 .await
7070 .into_iter();
7071
7072 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7073 responses: code_lens_actions
7074 .map(|actions| proto::LspResponse {
7075 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
7076 GetCodeLens::response_to_proto(
7077 actions,
7078 project,
7079 sender_id,
7080 &buffer_version,
7081 cx,
7082 ),
7083 )),
7084 })
7085 .collect(),
7086 })
7087 }
7088 None => anyhow::bail!("empty multi lsp query request"),
7089 }
7090 }
7091
7092 async fn handle_apply_code_action(
7093 this: Entity<Self>,
7094 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7095 mut cx: AsyncApp,
7096 ) -> Result<proto::ApplyCodeActionResponse> {
7097 let sender_id = envelope.original_sender_id().unwrap_or_default();
7098 let action = Self::deserialize_code_action(
7099 envelope
7100 .payload
7101 .action
7102 .ok_or_else(|| anyhow!("invalid action"))?,
7103 )?;
7104 let apply_code_action = this.update(&mut cx, |this, cx| {
7105 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7106 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7107 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
7108 })??;
7109
7110 let project_transaction = apply_code_action.await?;
7111 let project_transaction = this.update(&mut cx, |this, cx| {
7112 this.buffer_store.update(cx, |buffer_store, cx| {
7113 buffer_store.serialize_project_transaction_for_peer(
7114 project_transaction,
7115 sender_id,
7116 cx,
7117 )
7118 })
7119 })?;
7120 Ok(proto::ApplyCodeActionResponse {
7121 transaction: Some(project_transaction),
7122 })
7123 }
7124
7125 async fn handle_register_buffer_with_language_servers(
7126 this: Entity<Self>,
7127 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
7128 mut cx: AsyncApp,
7129 ) -> Result<proto::Ack> {
7130 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7131 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
7132 this.update(&mut cx, |this, cx| {
7133 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
7134 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
7135 project_id: upstream_project_id,
7136 buffer_id: buffer_id.to_proto(),
7137 });
7138 }
7139
7140 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
7141 anyhow::bail!("buffer is not open");
7142 };
7143
7144 let handle = this.register_buffer_with_language_servers(&buffer, false, cx);
7145 this.buffer_store().update(cx, |buffer_store, _| {
7146 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
7147 });
7148
7149 Ok(())
7150 })??;
7151 Ok(proto::Ack {})
7152 }
7153
7154 async fn handle_language_server_id_for_name(
7155 lsp_store: Entity<Self>,
7156 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7157 mut cx: AsyncApp,
7158 ) -> Result<proto::LanguageServerIdForNameResponse> {
7159 let name = &envelope.payload.name;
7160 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7161 lsp_store
7162 .update(&mut cx, |lsp_store, cx| {
7163 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7164 let server_id = buffer.update(cx, |buffer, cx| {
7165 lsp_store
7166 .language_servers_for_local_buffer(buffer, cx)
7167 .find_map(|(adapter, server)| {
7168 if adapter.name.0.as_ref() == name {
7169 Some(server.server_id())
7170 } else {
7171 None
7172 }
7173 })
7174 });
7175 Ok(server_id)
7176 })?
7177 .map(|server_id| proto::LanguageServerIdForNameResponse {
7178 server_id: server_id.map(|id| id.to_proto()),
7179 })
7180 }
7181
7182 async fn handle_rename_project_entry(
7183 this: Entity<Self>,
7184 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7185 mut cx: AsyncApp,
7186 ) -> Result<proto::ProjectEntryResponse> {
7187 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7188 let (worktree_id, worktree, old_path, is_dir) = this
7189 .update(&mut cx, |this, cx| {
7190 this.worktree_store
7191 .read(cx)
7192 .worktree_and_entry_for_id(entry_id, cx)
7193 .map(|(worktree, entry)| {
7194 (
7195 worktree.read(cx).id(),
7196 worktree,
7197 entry.path.clone(),
7198 entry.is_dir(),
7199 )
7200 })
7201 })?
7202 .ok_or_else(|| anyhow!("worktree not found"))?;
7203 let (old_abs_path, new_abs_path) = {
7204 let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
7205 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
7206 (root_path.join(&old_path), root_path.join(&new_path))
7207 };
7208
7209 Self::will_rename_entry(
7210 this.downgrade(),
7211 worktree_id,
7212 &old_abs_path,
7213 &new_abs_path,
7214 is_dir,
7215 cx.clone(),
7216 )
7217 .await;
7218 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
7219 this.update(&mut cx, |this, _| {
7220 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
7221 })
7222 .ok();
7223 response
7224 }
7225
7226 async fn handle_update_diagnostic_summary(
7227 this: Entity<Self>,
7228 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7229 mut cx: AsyncApp,
7230 ) -> Result<()> {
7231 this.update(&mut cx, |this, cx| {
7232 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7233 if let Some(message) = envelope.payload.summary {
7234 let project_path = ProjectPath {
7235 worktree_id,
7236 path: Arc::<Path>::from_proto(message.path),
7237 };
7238 let path = project_path.path.clone();
7239 let server_id = LanguageServerId(message.language_server_id as usize);
7240 let summary = DiagnosticSummary {
7241 error_count: message.error_count as usize,
7242 warning_count: message.warning_count as usize,
7243 };
7244
7245 if summary.is_empty() {
7246 if let Some(worktree_summaries) =
7247 this.diagnostic_summaries.get_mut(&worktree_id)
7248 {
7249 if let Some(summaries) = worktree_summaries.get_mut(&path) {
7250 summaries.remove(&server_id);
7251 if summaries.is_empty() {
7252 worktree_summaries.remove(&path);
7253 }
7254 }
7255 }
7256 } else {
7257 this.diagnostic_summaries
7258 .entry(worktree_id)
7259 .or_default()
7260 .entry(path)
7261 .or_default()
7262 .insert(server_id, summary);
7263 }
7264 if let Some((downstream_client, project_id)) = &this.downstream_client {
7265 downstream_client
7266 .send(proto::UpdateDiagnosticSummary {
7267 project_id: *project_id,
7268 worktree_id: worktree_id.to_proto(),
7269 summary: Some(proto::DiagnosticSummary {
7270 path: project_path.path.as_ref().to_proto(),
7271 language_server_id: server_id.0 as u64,
7272 error_count: summary.error_count as u32,
7273 warning_count: summary.warning_count as u32,
7274 }),
7275 })
7276 .log_err();
7277 }
7278 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7279 language_server_id: LanguageServerId(message.language_server_id as usize),
7280 path: project_path,
7281 });
7282 }
7283 Ok(())
7284 })?
7285 }
7286
7287 async fn handle_start_language_server(
7288 this: Entity<Self>,
7289 envelope: TypedEnvelope<proto::StartLanguageServer>,
7290 mut cx: AsyncApp,
7291 ) -> Result<()> {
7292 let server = envelope
7293 .payload
7294 .server
7295 .ok_or_else(|| anyhow!("invalid server"))?;
7296
7297 this.update(&mut cx, |this, cx| {
7298 let server_id = LanguageServerId(server.id as usize);
7299 this.language_server_statuses.insert(
7300 server_id,
7301 LanguageServerStatus {
7302 name: server.name.clone(),
7303 pending_work: Default::default(),
7304 has_pending_diagnostic_updates: false,
7305 progress_tokens: Default::default(),
7306 },
7307 );
7308 cx.emit(LspStoreEvent::LanguageServerAdded(
7309 server_id,
7310 LanguageServerName(server.name.into()),
7311 server.worktree_id.map(WorktreeId::from_proto),
7312 ));
7313 cx.notify();
7314 })?;
7315 Ok(())
7316 }
7317
7318 async fn handle_update_language_server(
7319 this: Entity<Self>,
7320 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7321 mut cx: AsyncApp,
7322 ) -> Result<()> {
7323 this.update(&mut cx, |this, cx| {
7324 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7325
7326 match envelope
7327 .payload
7328 .variant
7329 .ok_or_else(|| anyhow!("invalid variant"))?
7330 {
7331 proto::update_language_server::Variant::WorkStart(payload) => {
7332 this.on_lsp_work_start(
7333 language_server_id,
7334 payload.token,
7335 LanguageServerProgress {
7336 title: payload.title,
7337 is_disk_based_diagnostics_progress: false,
7338 is_cancellable: payload.is_cancellable.unwrap_or(false),
7339 message: payload.message,
7340 percentage: payload.percentage.map(|p| p as usize),
7341 last_update_at: cx.background_executor().now(),
7342 },
7343 cx,
7344 );
7345 }
7346
7347 proto::update_language_server::Variant::WorkProgress(payload) => {
7348 this.on_lsp_work_progress(
7349 language_server_id,
7350 payload.token,
7351 LanguageServerProgress {
7352 title: None,
7353 is_disk_based_diagnostics_progress: false,
7354 is_cancellable: payload.is_cancellable.unwrap_or(false),
7355 message: payload.message,
7356 percentage: payload.percentage.map(|p| p as usize),
7357 last_update_at: cx.background_executor().now(),
7358 },
7359 cx,
7360 );
7361 }
7362
7363 proto::update_language_server::Variant::WorkEnd(payload) => {
7364 this.on_lsp_work_end(language_server_id, payload.token, cx);
7365 }
7366
7367 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7368 this.disk_based_diagnostics_started(language_server_id, cx);
7369 }
7370
7371 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7372 this.disk_based_diagnostics_finished(language_server_id, cx)
7373 }
7374 }
7375
7376 Ok(())
7377 })?
7378 }
7379
7380 async fn handle_language_server_log(
7381 this: Entity<Self>,
7382 envelope: TypedEnvelope<proto::LanguageServerLog>,
7383 mut cx: AsyncApp,
7384 ) -> Result<()> {
7385 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7386 let log_type = envelope
7387 .payload
7388 .log_type
7389 .map(LanguageServerLogType::from_proto)
7390 .context("invalid language server log type")?;
7391
7392 let message = envelope.payload.message;
7393
7394 this.update(&mut cx, |_, cx| {
7395 cx.emit(LspStoreEvent::LanguageServerLog(
7396 language_server_id,
7397 log_type,
7398 message,
7399 ));
7400 })
7401 }
7402
7403 async fn handle_lsp_ext_cancel_flycheck(
7404 lsp_store: Entity<Self>,
7405 envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
7406 mut cx: AsyncApp,
7407 ) -> Result<proto::Ack> {
7408 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7409 lsp_store.update(&mut cx, |lsp_store, _| {
7410 if let Some(server) = lsp_store.language_server_for_id(server_id) {
7411 server
7412 .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
7413 .context("handling lsp ext cancel flycheck")
7414 } else {
7415 anyhow::Ok(())
7416 }
7417 })??;
7418
7419 Ok(proto::Ack {})
7420 }
7421
7422 async fn handle_lsp_ext_run_flycheck(
7423 lsp_store: Entity<Self>,
7424 envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
7425 mut cx: AsyncApp,
7426 ) -> Result<proto::Ack> {
7427 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7428 lsp_store.update(&mut cx, |lsp_store, cx| {
7429 if let Some(server) = lsp_store.language_server_for_id(server_id) {
7430 let text_document = if envelope.payload.current_file_only {
7431 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7432 lsp_store
7433 .buffer_store()
7434 .read(cx)
7435 .get(buffer_id)
7436 .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
7437 .map(|path| make_text_document_identifier(&path))
7438 .transpose()?
7439 } else {
7440 None
7441 };
7442 server
7443 .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
7444 &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
7445 )
7446 .context("handling lsp ext run flycheck")
7447 } else {
7448 anyhow::Ok(())
7449 }
7450 })??;
7451
7452 Ok(proto::Ack {})
7453 }
7454
7455 async fn handle_lsp_ext_clear_flycheck(
7456 lsp_store: Entity<Self>,
7457 envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
7458 mut cx: AsyncApp,
7459 ) -> Result<proto::Ack> {
7460 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7461 lsp_store.update(&mut cx, |lsp_store, _| {
7462 if let Some(server) = lsp_store.language_server_for_id(server_id) {
7463 server
7464 .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
7465 .context("handling lsp ext clear flycheck")
7466 } else {
7467 anyhow::Ok(())
7468 }
7469 })??;
7470
7471 Ok(proto::Ack {})
7472 }
7473
7474 pub fn disk_based_diagnostics_started(
7475 &mut self,
7476 language_server_id: LanguageServerId,
7477 cx: &mut Context<Self>,
7478 ) {
7479 if let Some(language_server_status) =
7480 self.language_server_statuses.get_mut(&language_server_id)
7481 {
7482 language_server_status.has_pending_diagnostic_updates = true;
7483 }
7484
7485 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
7486 cx.emit(LspStoreEvent::LanguageServerUpdate {
7487 language_server_id,
7488 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
7489 Default::default(),
7490 ),
7491 })
7492 }
7493
7494 pub fn disk_based_diagnostics_finished(
7495 &mut self,
7496 language_server_id: LanguageServerId,
7497 cx: &mut Context<Self>,
7498 ) {
7499 if let Some(language_server_status) =
7500 self.language_server_statuses.get_mut(&language_server_id)
7501 {
7502 language_server_status.has_pending_diagnostic_updates = false;
7503 }
7504
7505 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
7506 cx.emit(LspStoreEvent::LanguageServerUpdate {
7507 language_server_id,
7508 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
7509 Default::default(),
7510 ),
7511 })
7512 }
7513
7514 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
7515 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
7516 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
7517 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
7518 // the language server might take some time to publish diagnostics.
7519 fn simulate_disk_based_diagnostics_events_if_needed(
7520 &mut self,
7521 language_server_id: LanguageServerId,
7522 cx: &mut Context<Self>,
7523 ) {
7524 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
7525
7526 let Some(LanguageServerState::Running {
7527 simulate_disk_based_diagnostics_completion,
7528 adapter,
7529 ..
7530 }) = self
7531 .as_local_mut()
7532 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
7533 else {
7534 return;
7535 };
7536
7537 if adapter.disk_based_diagnostics_progress_token.is_some() {
7538 return;
7539 }
7540
7541 let prev_task =
7542 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
7543 cx.background_executor()
7544 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
7545 .await;
7546
7547 this.update(cx, |this, cx| {
7548 this.disk_based_diagnostics_finished(language_server_id, cx);
7549
7550 if let Some(LanguageServerState::Running {
7551 simulate_disk_based_diagnostics_completion,
7552 ..
7553 }) = this.as_local_mut().and_then(|local_store| {
7554 local_store.language_servers.get_mut(&language_server_id)
7555 }) {
7556 *simulate_disk_based_diagnostics_completion = None;
7557 }
7558 })
7559 .ok();
7560 }));
7561
7562 if prev_task.is_none() {
7563 self.disk_based_diagnostics_started(language_server_id, cx);
7564 }
7565 }
7566
7567 pub fn language_server_statuses(
7568 &self,
7569 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
7570 self.language_server_statuses
7571 .iter()
7572 .map(|(key, value)| (*key, value))
7573 }
7574
7575 pub(super) fn did_rename_entry(
7576 &self,
7577 worktree_id: WorktreeId,
7578 old_path: &Path,
7579 new_path: &Path,
7580 is_dir: bool,
7581 ) {
7582 maybe!({
7583 let local_store = self.as_local()?;
7584
7585 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
7586 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
7587
7588 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7589 let Some(filter) = local_store
7590 .language_server_paths_watched_for_rename
7591 .get(&language_server.server_id())
7592 else {
7593 continue;
7594 };
7595
7596 if filter.should_send_did_rename(&old_uri, is_dir) {
7597 language_server
7598 .notify::<DidRenameFiles>(&RenameFilesParams {
7599 files: vec![FileRename {
7600 old_uri: old_uri.clone(),
7601 new_uri: new_uri.clone(),
7602 }],
7603 })
7604 .ok();
7605 }
7606 }
7607 Some(())
7608 });
7609 }
7610
7611 pub(super) fn will_rename_entry(
7612 this: WeakEntity<Self>,
7613 worktree_id: WorktreeId,
7614 old_path: &Path,
7615 new_path: &Path,
7616 is_dir: bool,
7617 cx: AsyncApp,
7618 ) -> Task<()> {
7619 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
7620 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
7621 cx.spawn(async move |cx| {
7622 let mut tasks = vec![];
7623 this.update(cx, |this, cx| {
7624 let local_store = this.as_local()?;
7625 let old_uri = old_uri?;
7626 let new_uri = new_uri?;
7627 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7628 let Some(filter) = local_store
7629 .language_server_paths_watched_for_rename
7630 .get(&language_server.server_id())
7631 else {
7632 continue;
7633 };
7634 let Some(adapter) =
7635 this.language_server_adapter_for_id(language_server.server_id())
7636 else {
7637 continue;
7638 };
7639 if filter.should_send_will_rename(&old_uri, is_dir) {
7640 let apply_edit = cx.spawn({
7641 let old_uri = old_uri.clone();
7642 let new_uri = new_uri.clone();
7643 let language_server = language_server.clone();
7644 async move |this, cx| {
7645 let edit = language_server
7646 .request::<WillRenameFiles>(RenameFilesParams {
7647 files: vec![FileRename { old_uri, new_uri }],
7648 })
7649 .await
7650 .into_response()
7651 .context("will rename files")
7652 .log_err()
7653 .flatten()?;
7654
7655 LocalLspStore::deserialize_workspace_edit(
7656 this.upgrade()?,
7657 edit,
7658 false,
7659 adapter.clone(),
7660 language_server.clone(),
7661 cx,
7662 )
7663 .await
7664 .ok();
7665 Some(())
7666 }
7667 });
7668 tasks.push(apply_edit);
7669 }
7670 }
7671 Some(())
7672 })
7673 .ok()
7674 .flatten();
7675 for task in tasks {
7676 // Await on tasks sequentially so that the order of application of edits is deterministic
7677 // (at least with regards to the order of registration of language servers)
7678 task.await;
7679 }
7680 })
7681 }
7682
7683 fn lsp_notify_abs_paths_changed(
7684 &mut self,
7685 server_id: LanguageServerId,
7686 changes: Vec<PathEvent>,
7687 ) {
7688 maybe!({
7689 let server = self.language_server_for_id(server_id)?;
7690 let changes = changes
7691 .into_iter()
7692 .filter_map(|event| {
7693 let typ = match event.kind? {
7694 PathEventKind::Created => lsp::FileChangeType::CREATED,
7695 PathEventKind::Removed => lsp::FileChangeType::DELETED,
7696 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
7697 };
7698 Some(lsp::FileEvent {
7699 uri: lsp::Url::from_file_path(&event.path).ok()?,
7700 typ,
7701 })
7702 })
7703 .collect::<Vec<_>>();
7704 if !changes.is_empty() {
7705 server
7706 .notify::<lsp::notification::DidChangeWatchedFiles>(
7707 &lsp::DidChangeWatchedFilesParams { changes },
7708 )
7709 .ok();
7710 }
7711 Some(())
7712 });
7713 }
7714
7715 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7716 let local_lsp_store = self.as_local()?;
7717 if let Some(LanguageServerState::Running { server, .. }) =
7718 local_lsp_store.language_servers.get(&id)
7719 {
7720 Some(server.clone())
7721 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
7722 Some(Arc::clone(server))
7723 } else {
7724 None
7725 }
7726 }
7727
7728 fn on_lsp_progress(
7729 &mut self,
7730 progress: lsp::ProgressParams,
7731 language_server_id: LanguageServerId,
7732 disk_based_diagnostics_progress_token: Option<String>,
7733 cx: &mut Context<Self>,
7734 ) {
7735 let token = match progress.token {
7736 lsp::NumberOrString::String(token) => token,
7737 lsp::NumberOrString::Number(token) => {
7738 log::info!("skipping numeric progress token {}", token);
7739 return;
7740 }
7741 };
7742
7743 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
7744 let language_server_status =
7745 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7746 status
7747 } else {
7748 return;
7749 };
7750
7751 if !language_server_status.progress_tokens.contains(&token) {
7752 return;
7753 }
7754
7755 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
7756 .as_ref()
7757 .map_or(false, |disk_based_token| {
7758 token.starts_with(disk_based_token)
7759 });
7760
7761 match progress {
7762 lsp::WorkDoneProgress::Begin(report) => {
7763 if is_disk_based_diagnostics_progress {
7764 self.disk_based_diagnostics_started(language_server_id, cx);
7765 }
7766 self.on_lsp_work_start(
7767 language_server_id,
7768 token.clone(),
7769 LanguageServerProgress {
7770 title: Some(report.title),
7771 is_disk_based_diagnostics_progress,
7772 is_cancellable: report.cancellable.unwrap_or(false),
7773 message: report.message.clone(),
7774 percentage: report.percentage.map(|p| p as usize),
7775 last_update_at: cx.background_executor().now(),
7776 },
7777 cx,
7778 );
7779 }
7780 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
7781 language_server_id,
7782 token,
7783 LanguageServerProgress {
7784 title: None,
7785 is_disk_based_diagnostics_progress,
7786 is_cancellable: report.cancellable.unwrap_or(false),
7787 message: report.message,
7788 percentage: report.percentage.map(|p| p as usize),
7789 last_update_at: cx.background_executor().now(),
7790 },
7791 cx,
7792 ),
7793 lsp::WorkDoneProgress::End(_) => {
7794 language_server_status.progress_tokens.remove(&token);
7795 self.on_lsp_work_end(language_server_id, token.clone(), cx);
7796 if is_disk_based_diagnostics_progress {
7797 self.disk_based_diagnostics_finished(language_server_id, cx);
7798 }
7799 }
7800 }
7801 }
7802
7803 fn on_lsp_work_start(
7804 &mut self,
7805 language_server_id: LanguageServerId,
7806 token: String,
7807 progress: LanguageServerProgress,
7808 cx: &mut Context<Self>,
7809 ) {
7810 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7811 status.pending_work.insert(token.clone(), progress.clone());
7812 cx.notify();
7813 }
7814 cx.emit(LspStoreEvent::LanguageServerUpdate {
7815 language_server_id,
7816 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
7817 token,
7818 title: progress.title,
7819 message: progress.message,
7820 percentage: progress.percentage.map(|p| p as u32),
7821 is_cancellable: Some(progress.is_cancellable),
7822 }),
7823 })
7824 }
7825
7826 fn on_lsp_work_progress(
7827 &mut self,
7828 language_server_id: LanguageServerId,
7829 token: String,
7830 progress: LanguageServerProgress,
7831 cx: &mut Context<Self>,
7832 ) {
7833 let mut did_update = false;
7834 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7835 match status.pending_work.entry(token.clone()) {
7836 btree_map::Entry::Vacant(entry) => {
7837 entry.insert(progress.clone());
7838 did_update = true;
7839 }
7840 btree_map::Entry::Occupied(mut entry) => {
7841 let entry = entry.get_mut();
7842 if (progress.last_update_at - entry.last_update_at)
7843 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
7844 {
7845 entry.last_update_at = progress.last_update_at;
7846 if progress.message.is_some() {
7847 entry.message = progress.message.clone();
7848 }
7849 if progress.percentage.is_some() {
7850 entry.percentage = progress.percentage;
7851 }
7852 if progress.is_cancellable != entry.is_cancellable {
7853 entry.is_cancellable = progress.is_cancellable;
7854 }
7855 did_update = true;
7856 }
7857 }
7858 }
7859 }
7860
7861 if did_update {
7862 cx.emit(LspStoreEvent::LanguageServerUpdate {
7863 language_server_id,
7864 message: proto::update_language_server::Variant::WorkProgress(
7865 proto::LspWorkProgress {
7866 token,
7867 message: progress.message,
7868 percentage: progress.percentage.map(|p| p as u32),
7869 is_cancellable: Some(progress.is_cancellable),
7870 },
7871 ),
7872 })
7873 }
7874 }
7875
7876 fn on_lsp_work_end(
7877 &mut self,
7878 language_server_id: LanguageServerId,
7879 token: String,
7880 cx: &mut Context<Self>,
7881 ) {
7882 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7883 if let Some(work) = status.pending_work.remove(&token) {
7884 if !work.is_disk_based_diagnostics_progress {
7885 cx.emit(LspStoreEvent::RefreshInlayHints);
7886 }
7887 }
7888 cx.notify();
7889 }
7890
7891 cx.emit(LspStoreEvent::LanguageServerUpdate {
7892 language_server_id,
7893 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
7894 })
7895 }
7896
7897 pub async fn handle_resolve_completion_documentation(
7898 this: Entity<Self>,
7899 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7900 mut cx: AsyncApp,
7901 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7902 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7903
7904 let completion = this
7905 .read_with(&cx, |this, cx| {
7906 let id = LanguageServerId(envelope.payload.language_server_id as usize);
7907 let Some(server) = this.language_server_for_id(id) else {
7908 return Err(anyhow!("No language server {id}"));
7909 };
7910
7911 Ok(cx.background_spawn(async move {
7912 let can_resolve = server
7913 .capabilities()
7914 .completion_provider
7915 .as_ref()
7916 .and_then(|options| options.resolve_provider)
7917 .unwrap_or(false);
7918 if can_resolve {
7919 server
7920 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
7921 .await
7922 .into_response()
7923 .context("resolve completion item")
7924 } else {
7925 anyhow::Ok(lsp_completion)
7926 }
7927 }))
7928 })??
7929 .await?;
7930
7931 let mut documentation_is_markdown = false;
7932 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
7933 let documentation = match completion.documentation {
7934 Some(lsp::Documentation::String(text)) => text,
7935
7936 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7937 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
7938 value
7939 }
7940
7941 _ => String::new(),
7942 };
7943
7944 // If we have a new buffer_id, that means we're talking to a new client
7945 // and want to check for new text_edits in the completion too.
7946 let mut old_replace_start = None;
7947 let mut old_replace_end = None;
7948 let mut old_insert_start = None;
7949 let mut old_insert_end = None;
7950 let mut new_text = String::default();
7951 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
7952 let buffer_snapshot = this.update(&mut cx, |this, cx| {
7953 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7954 anyhow::Ok(buffer.read(cx).snapshot())
7955 })??;
7956
7957 if let Some(text_edit) = completion.text_edit.as_ref() {
7958 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
7959
7960 if let Some(mut edit) = edit {
7961 LineEnding::normalize(&mut edit.new_text);
7962
7963 new_text = edit.new_text;
7964 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
7965 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
7966 if let Some(insert_range) = edit.insert_range {
7967 old_insert_start = Some(serialize_anchor(&insert_range.start));
7968 old_insert_end = Some(serialize_anchor(&insert_range.end));
7969 }
7970 }
7971 }
7972 }
7973
7974 Ok(proto::ResolveCompletionDocumentationResponse {
7975 documentation,
7976 documentation_is_markdown,
7977 old_replace_start,
7978 old_replace_end,
7979 new_text,
7980 lsp_completion,
7981 old_insert_start,
7982 old_insert_end,
7983 })
7984 }
7985
7986 async fn handle_on_type_formatting(
7987 this: Entity<Self>,
7988 envelope: TypedEnvelope<proto::OnTypeFormatting>,
7989 mut cx: AsyncApp,
7990 ) -> Result<proto::OnTypeFormattingResponse> {
7991 let on_type_formatting = this.update(&mut cx, |this, cx| {
7992 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7993 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7994 let position = envelope
7995 .payload
7996 .position
7997 .and_then(deserialize_anchor)
7998 .ok_or_else(|| anyhow!("invalid position"))?;
7999 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8000 buffer,
8001 position,
8002 envelope.payload.trigger.clone(),
8003 cx,
8004 ))
8005 })??;
8006
8007 let transaction = on_type_formatting
8008 .await?
8009 .as_ref()
8010 .map(language::proto::serialize_transaction);
8011 Ok(proto::OnTypeFormattingResponse { transaction })
8012 }
8013
8014 async fn handle_refresh_inlay_hints(
8015 this: Entity<Self>,
8016 _: TypedEnvelope<proto::RefreshInlayHints>,
8017 mut cx: AsyncApp,
8018 ) -> Result<proto::Ack> {
8019 this.update(&mut cx, |_, cx| {
8020 cx.emit(LspStoreEvent::RefreshInlayHints);
8021 })?;
8022 Ok(proto::Ack {})
8023 }
8024
8025 async fn handle_inlay_hints(
8026 this: Entity<Self>,
8027 envelope: TypedEnvelope<proto::InlayHints>,
8028 mut cx: AsyncApp,
8029 ) -> Result<proto::InlayHintsResponse> {
8030 let sender_id = envelope.original_sender_id().unwrap_or_default();
8031 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8032 let buffer = this.update(&mut cx, |this, cx| {
8033 this.buffer_store.read(cx).get_existing(buffer_id)
8034 })??;
8035 buffer
8036 .update(&mut cx, |buffer, _| {
8037 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8038 })?
8039 .await
8040 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8041
8042 let start = envelope
8043 .payload
8044 .start
8045 .and_then(deserialize_anchor)
8046 .context("missing range start")?;
8047 let end = envelope
8048 .payload
8049 .end
8050 .and_then(deserialize_anchor)
8051 .context("missing range end")?;
8052 let buffer_hints = this
8053 .update(&mut cx, |lsp_store, cx| {
8054 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
8055 })?
8056 .await
8057 .context("inlay hints fetch")?;
8058
8059 this.update(&mut cx, |project, cx| {
8060 InlayHints::response_to_proto(
8061 buffer_hints,
8062 project,
8063 sender_id,
8064 &buffer.read(cx).version(),
8065 cx,
8066 )
8067 })
8068 }
8069
8070 async fn handle_resolve_inlay_hint(
8071 this: Entity<Self>,
8072 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8073 mut cx: AsyncApp,
8074 ) -> Result<proto::ResolveInlayHintResponse> {
8075 let proto_hint = envelope
8076 .payload
8077 .hint
8078 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8079 let hint = InlayHints::proto_to_project_hint(proto_hint)
8080 .context("resolved proto inlay hint conversion")?;
8081 let buffer = this.update(&mut cx, |this, cx| {
8082 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8083 this.buffer_store.read(cx).get_existing(buffer_id)
8084 })??;
8085 let response_hint = this
8086 .update(&mut cx, |this, cx| {
8087 this.resolve_inlay_hint(
8088 hint,
8089 buffer,
8090 LanguageServerId(envelope.payload.language_server_id as usize),
8091 cx,
8092 )
8093 })?
8094 .await
8095 .context("inlay hints fetch")?;
8096 Ok(proto::ResolveInlayHintResponse {
8097 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8098 })
8099 }
8100
8101 async fn handle_refresh_code_lens(
8102 this: Entity<Self>,
8103 _: TypedEnvelope<proto::RefreshCodeLens>,
8104 mut cx: AsyncApp,
8105 ) -> Result<proto::Ack> {
8106 this.update(&mut cx, |_, cx| {
8107 cx.emit(LspStoreEvent::RefreshCodeLens);
8108 })?;
8109 Ok(proto::Ack {})
8110 }
8111
8112 async fn handle_open_buffer_for_symbol(
8113 this: Entity<Self>,
8114 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8115 mut cx: AsyncApp,
8116 ) -> Result<proto::OpenBufferForSymbolResponse> {
8117 let peer_id = envelope.original_sender_id().unwrap_or_default();
8118 let symbol = envelope
8119 .payload
8120 .symbol
8121 .ok_or_else(|| anyhow!("invalid symbol"))?;
8122 let symbol = Self::deserialize_symbol(symbol)?;
8123 let symbol = this.update(&mut cx, |this, _| {
8124 let signature = this.symbol_signature(&symbol.path);
8125 if signature == symbol.signature {
8126 Ok(symbol)
8127 } else {
8128 Err(anyhow!("invalid symbol signature"))
8129 }
8130 })??;
8131 let buffer = this
8132 .update(&mut cx, |this, cx| {
8133 this.open_buffer_for_symbol(
8134 &Symbol {
8135 language_server_name: symbol.language_server_name,
8136 source_worktree_id: symbol.source_worktree_id,
8137 source_language_server_id: symbol.source_language_server_id,
8138 path: symbol.path,
8139 name: symbol.name,
8140 kind: symbol.kind,
8141 range: symbol.range,
8142 signature: symbol.signature,
8143 label: CodeLabel {
8144 text: Default::default(),
8145 runs: Default::default(),
8146 filter_range: Default::default(),
8147 },
8148 },
8149 cx,
8150 )
8151 })?
8152 .await?;
8153
8154 this.update(&mut cx, |this, cx| {
8155 let is_private = buffer
8156 .read(cx)
8157 .file()
8158 .map(|f| f.is_private())
8159 .unwrap_or_default();
8160 if is_private {
8161 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
8162 } else {
8163 this.buffer_store
8164 .update(cx, |buffer_store, cx| {
8165 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
8166 })
8167 .detach_and_log_err(cx);
8168 let buffer_id = buffer.read(cx).remote_id().to_proto();
8169 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
8170 }
8171 })?
8172 }
8173
8174 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8175 let mut hasher = Sha256::new();
8176 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8177 hasher.update(project_path.path.to_string_lossy().as_bytes());
8178 hasher.update(self.nonce.to_be_bytes());
8179 hasher.finalize().as_slice().try_into().unwrap()
8180 }
8181
8182 pub async fn handle_get_project_symbols(
8183 this: Entity<Self>,
8184 envelope: TypedEnvelope<proto::GetProjectSymbols>,
8185 mut cx: AsyncApp,
8186 ) -> Result<proto::GetProjectSymbolsResponse> {
8187 let symbols = this
8188 .update(&mut cx, |this, cx| {
8189 this.symbols(&envelope.payload.query, cx)
8190 })?
8191 .await?;
8192
8193 Ok(proto::GetProjectSymbolsResponse {
8194 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
8195 })
8196 }
8197
8198 pub async fn handle_restart_language_servers(
8199 this: Entity<Self>,
8200 envelope: TypedEnvelope<proto::RestartLanguageServers>,
8201 mut cx: AsyncApp,
8202 ) -> Result<proto::Ack> {
8203 this.update(&mut cx, |this, cx| {
8204 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
8205 this.restart_language_servers_for_buffers(buffers, cx);
8206 })?;
8207
8208 Ok(proto::Ack {})
8209 }
8210
8211 pub async fn handle_stop_language_servers(
8212 this: Entity<Self>,
8213 envelope: TypedEnvelope<proto::StopLanguageServers>,
8214 mut cx: AsyncApp,
8215 ) -> Result<proto::Ack> {
8216 this.update(&mut cx, |this, cx| {
8217 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
8218 this.stop_language_servers_for_buffers(buffers, cx);
8219 })?;
8220
8221 Ok(proto::Ack {})
8222 }
8223
8224 pub async fn handle_cancel_language_server_work(
8225 this: Entity<Self>,
8226 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
8227 mut cx: AsyncApp,
8228 ) -> Result<proto::Ack> {
8229 this.update(&mut cx, |this, cx| {
8230 if let Some(work) = envelope.payload.work {
8231 match work {
8232 proto::cancel_language_server_work::Work::Buffers(buffers) => {
8233 let buffers =
8234 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
8235 this.cancel_language_server_work_for_buffers(buffers, cx);
8236 }
8237 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
8238 let server_id = LanguageServerId::from_proto(work.language_server_id);
8239 this.cancel_language_server_work(server_id, work.token, cx);
8240 }
8241 }
8242 }
8243 })?;
8244
8245 Ok(proto::Ack {})
8246 }
8247
8248 fn buffer_ids_to_buffers(
8249 &mut self,
8250 buffer_ids: impl Iterator<Item = u64>,
8251 cx: &mut Context<Self>,
8252 ) -> Vec<Entity<Buffer>> {
8253 buffer_ids
8254 .into_iter()
8255 .flat_map(|buffer_id| {
8256 self.buffer_store
8257 .read(cx)
8258 .get(BufferId::new(buffer_id).log_err()?)
8259 })
8260 .collect::<Vec<_>>()
8261 }
8262
8263 async fn handle_apply_additional_edits_for_completion(
8264 this: Entity<Self>,
8265 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8266 mut cx: AsyncApp,
8267 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8268 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8269 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8270 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8271 let completion = Self::deserialize_completion(
8272 envelope
8273 .payload
8274 .completion
8275 .ok_or_else(|| anyhow!("invalid completion"))?,
8276 )?;
8277 anyhow::Ok((buffer, completion))
8278 })??;
8279
8280 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8281 this.apply_additional_edits_for_completion(
8282 buffer,
8283 Rc::new(RefCell::new(Box::new([Completion {
8284 replace_range: completion.replace_range,
8285 new_text: completion.new_text,
8286 source: completion.source,
8287 documentation: None,
8288 label: CodeLabel {
8289 text: Default::default(),
8290 runs: Default::default(),
8291 filter_range: Default::default(),
8292 },
8293 insert_text_mode: None,
8294 icon_path: None,
8295 confirm: None,
8296 }]))),
8297 0,
8298 false,
8299 cx,
8300 )
8301 })?;
8302
8303 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8304 transaction: apply_additional_edits
8305 .await?
8306 .as_ref()
8307 .map(language::proto::serialize_transaction),
8308 })
8309 }
8310
8311 pub fn last_formatting_failure(&self) -> Option<&str> {
8312 self.last_formatting_failure.as_deref()
8313 }
8314
8315 pub fn reset_last_formatting_failure(&mut self) {
8316 self.last_formatting_failure = None;
8317 }
8318
8319 pub fn environment_for_buffer(
8320 &self,
8321 buffer: &Entity<Buffer>,
8322 cx: &mut Context<Self>,
8323 ) -> Shared<Task<Option<HashMap<String, String>>>> {
8324 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
8325 environment.update(cx, |env, cx| {
8326 env.get_buffer_environment(&buffer, &self.worktree_store, cx)
8327 })
8328 } else {
8329 Task::ready(None).shared()
8330 }
8331 }
8332
8333 pub fn format(
8334 &mut self,
8335 buffers: HashSet<Entity<Buffer>>,
8336 target: LspFormatTarget,
8337 push_to_history: bool,
8338 trigger: FormatTrigger,
8339 cx: &mut Context<Self>,
8340 ) -> Task<anyhow::Result<ProjectTransaction>> {
8341 let logger = zlog::scoped!("format");
8342 if let Some(_) = self.as_local() {
8343 zlog::trace!(logger => "Formatting locally");
8344 let logger = zlog::scoped!(logger => "local");
8345 let buffers = buffers
8346 .into_iter()
8347 .map(|buffer_handle| {
8348 let buffer = buffer_handle.read(cx);
8349 let buffer_abs_path = File::from_dyn(buffer.file())
8350 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
8351
8352 (buffer_handle, buffer_abs_path, buffer.remote_id())
8353 })
8354 .collect::<Vec<_>>();
8355
8356 cx.spawn(async move |lsp_store, cx| {
8357 let mut formattable_buffers = Vec::with_capacity(buffers.len());
8358
8359 for (handle, abs_path, id) in buffers {
8360 let env = lsp_store
8361 .update(cx, |lsp_store, cx| {
8362 lsp_store.environment_for_buffer(&handle, cx)
8363 })?
8364 .await;
8365
8366 let ranges = match &target {
8367 LspFormatTarget::Buffers => None,
8368 LspFormatTarget::Ranges(ranges) => {
8369 let Some(ranges) = ranges.get(&id) else {
8370 return Err(anyhow!("No format ranges provided for buffer"));
8371 };
8372 Some(ranges.clone())
8373 }
8374 };
8375
8376 formattable_buffers.push(FormattableBuffer {
8377 handle,
8378 abs_path,
8379 env,
8380 ranges,
8381 });
8382 }
8383 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
8384
8385 let format_timer = zlog::time!(logger => "Formatting buffers");
8386 let result = LocalLspStore::format_locally(
8387 lsp_store.clone(),
8388 formattable_buffers,
8389 push_to_history,
8390 trigger,
8391 logger,
8392 cx,
8393 )
8394 .await;
8395 format_timer.end();
8396
8397 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
8398
8399 lsp_store.update(cx, |lsp_store, _| {
8400 lsp_store.update_last_formatting_failure(&result);
8401 })?;
8402
8403 result
8404 })
8405 } else if let Some((client, project_id)) = self.upstream_client() {
8406 zlog::trace!(logger => "Formatting remotely");
8407 let logger = zlog::scoped!(logger => "remote");
8408 // Don't support formatting ranges via remote
8409 match target {
8410 LspFormatTarget::Buffers => {}
8411 LspFormatTarget::Ranges(_) => {
8412 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
8413 return Task::ready(Ok(ProjectTransaction::default()));
8414 }
8415 }
8416
8417 let buffer_store = self.buffer_store();
8418 cx.spawn(async move |lsp_store, cx| {
8419 zlog::trace!(logger => "Sending remote format request");
8420 let request_timer = zlog::time!(logger => "remote format request");
8421 let result = client
8422 .request(proto::FormatBuffers {
8423 project_id,
8424 trigger: trigger as i32,
8425 buffer_ids: buffers
8426 .iter()
8427 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
8428 .collect::<Result<_>>()?,
8429 })
8430 .await
8431 .and_then(|result| result.transaction.context("missing transaction"));
8432 request_timer.end();
8433
8434 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
8435
8436 lsp_store.update(cx, |lsp_store, _| {
8437 lsp_store.update_last_formatting_failure(&result);
8438 })?;
8439
8440 let transaction_response = result?;
8441 let _timer = zlog::time!(logger => "deserializing project transaction");
8442 buffer_store
8443 .update(cx, |buffer_store, cx| {
8444 buffer_store.deserialize_project_transaction(
8445 transaction_response,
8446 push_to_history,
8447 cx,
8448 )
8449 })?
8450 .await
8451 })
8452 } else {
8453 zlog::trace!(logger => "Not formatting");
8454 Task::ready(Ok(ProjectTransaction::default()))
8455 }
8456 }
8457
8458 async fn handle_format_buffers(
8459 this: Entity<Self>,
8460 envelope: TypedEnvelope<proto::FormatBuffers>,
8461 mut cx: AsyncApp,
8462 ) -> Result<proto::FormatBuffersResponse> {
8463 let sender_id = envelope.original_sender_id().unwrap_or_default();
8464 let format = this.update(&mut cx, |this, cx| {
8465 let mut buffers = HashSet::default();
8466 for buffer_id in &envelope.payload.buffer_ids {
8467 let buffer_id = BufferId::new(*buffer_id)?;
8468 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8469 }
8470 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8471 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
8472 })??;
8473
8474 let project_transaction = format.await?;
8475 let project_transaction = this.update(&mut cx, |this, cx| {
8476 this.buffer_store.update(cx, |buffer_store, cx| {
8477 buffer_store.serialize_project_transaction_for_peer(
8478 project_transaction,
8479 sender_id,
8480 cx,
8481 )
8482 })
8483 })?;
8484 Ok(proto::FormatBuffersResponse {
8485 transaction: Some(project_transaction),
8486 })
8487 }
8488
8489 async fn handle_apply_code_action_kind(
8490 this: Entity<Self>,
8491 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
8492 mut cx: AsyncApp,
8493 ) -> Result<proto::ApplyCodeActionKindResponse> {
8494 let sender_id = envelope.original_sender_id().unwrap_or_default();
8495 let format = this.update(&mut cx, |this, cx| {
8496 let mut buffers = HashSet::default();
8497 for buffer_id in &envelope.payload.buffer_ids {
8498 let buffer_id = BufferId::new(*buffer_id)?;
8499 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8500 }
8501 let kind = match envelope.payload.kind.as_str() {
8502 "" => Ok(CodeActionKind::EMPTY),
8503 "quickfix" => Ok(CodeActionKind::QUICKFIX),
8504 "refactor" => Ok(CodeActionKind::REFACTOR),
8505 "refactor.extract" => Ok(CodeActionKind::REFACTOR_EXTRACT),
8506 "refactor.inline" => Ok(CodeActionKind::REFACTOR_INLINE),
8507 "refactor.rewrite" => Ok(CodeActionKind::REFACTOR_REWRITE),
8508 "source" => Ok(CodeActionKind::SOURCE),
8509 "source.organizeImports" => Ok(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
8510 "source.fixAll" => Ok(CodeActionKind::SOURCE_FIX_ALL),
8511 _ => Err(anyhow!("Invalid code action kind")),
8512 }?;
8513 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
8514 })??;
8515
8516 let project_transaction = format.await?;
8517 let project_transaction = this.update(&mut cx, |this, cx| {
8518 this.buffer_store.update(cx, |buffer_store, cx| {
8519 buffer_store.serialize_project_transaction_for_peer(
8520 project_transaction,
8521 sender_id,
8522 cx,
8523 )
8524 })
8525 })?;
8526 Ok(proto::ApplyCodeActionKindResponse {
8527 transaction: Some(project_transaction),
8528 })
8529 }
8530
8531 async fn shutdown_language_server(
8532 server_state: Option<LanguageServerState>,
8533 name: LanguageServerName,
8534 cx: &mut AsyncApp,
8535 ) {
8536 let server = match server_state {
8537 Some(LanguageServerState::Starting { startup, .. }) => {
8538 let mut timer = cx
8539 .background_executor()
8540 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
8541 .fuse();
8542
8543 select! {
8544 server = startup.fuse() => server,
8545 _ = timer => {
8546 log::info!(
8547 "timeout waiting for language server {} to finish launching before stopping",
8548 name
8549 );
8550 None
8551 },
8552 }
8553 }
8554
8555 Some(LanguageServerState::Running { server, .. }) => Some(server),
8556
8557 None => None,
8558 };
8559
8560 if let Some(server) = server {
8561 if let Some(shutdown) = server.shutdown() {
8562 shutdown.await;
8563 }
8564 }
8565 }
8566
8567 // Returns a list of all of the worktrees which no longer have a language server and the root path
8568 // for the stopped server
8569 fn stop_local_language_server(
8570 &mut self,
8571 server_id: LanguageServerId,
8572 name: LanguageServerName,
8573 cx: &mut Context<Self>,
8574 ) -> Task<Vec<WorktreeId>> {
8575 let local = match &mut self.mode {
8576 LspStoreMode::Local(local) => local,
8577 _ => {
8578 return Task::ready(Vec::new());
8579 }
8580 };
8581
8582 let mut orphaned_worktrees = vec![];
8583 // Remove this server ID from all entries in the given worktree.
8584 local.language_server_ids.retain(|(worktree, _), ids| {
8585 if !ids.remove(&server_id) {
8586 return true;
8587 }
8588
8589 if ids.is_empty() {
8590 orphaned_worktrees.push(*worktree);
8591 false
8592 } else {
8593 true
8594 }
8595 });
8596 let _ = self.language_server_statuses.remove(&server_id);
8597 log::info!("stopping language server {name}");
8598 self.buffer_store.update(cx, |buffer_store, cx| {
8599 for buffer in buffer_store.buffers() {
8600 buffer.update(cx, |buffer, cx| {
8601 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
8602 buffer.set_completion_triggers(server_id, Default::default(), cx);
8603 });
8604 }
8605 });
8606
8607 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
8608 summaries.retain(|path, summaries_by_server_id| {
8609 if summaries_by_server_id.remove(&server_id).is_some() {
8610 if let Some((client, project_id)) = self.downstream_client.clone() {
8611 client
8612 .send(proto::UpdateDiagnosticSummary {
8613 project_id,
8614 worktree_id: worktree_id.to_proto(),
8615 summary: Some(proto::DiagnosticSummary {
8616 path: path.as_ref().to_proto(),
8617 language_server_id: server_id.0 as u64,
8618 error_count: 0,
8619 warning_count: 0,
8620 }),
8621 })
8622 .log_err();
8623 }
8624 !summaries_by_server_id.is_empty()
8625 } else {
8626 true
8627 }
8628 });
8629 }
8630
8631 let local = self.as_local_mut().unwrap();
8632 for diagnostics in local.diagnostics.values_mut() {
8633 diagnostics.retain(|_, diagnostics_by_server_id| {
8634 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
8635 diagnostics_by_server_id.remove(ix);
8636 !diagnostics_by_server_id.is_empty()
8637 } else {
8638 true
8639 }
8640 });
8641 }
8642 local.language_server_watched_paths.remove(&server_id);
8643 let server_state = local.language_servers.remove(&server_id);
8644 cx.notify();
8645 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
8646 cx.spawn(async move |_, cx| {
8647 Self::shutdown_language_server(server_state, name, cx).await;
8648 orphaned_worktrees
8649 })
8650 }
8651
8652 pub fn restart_language_servers_for_buffers(
8653 &mut self,
8654 buffers: Vec<Entity<Buffer>>,
8655 cx: &mut Context<Self>,
8656 ) {
8657 if let Some((client, project_id)) = self.upstream_client() {
8658 let request = client.request(proto::RestartLanguageServers {
8659 project_id,
8660 buffer_ids: buffers
8661 .into_iter()
8662 .map(|b| b.read(cx).remote_id().to_proto())
8663 .collect(),
8664 });
8665 cx.background_spawn(request).detach_and_log_err(cx);
8666 } else {
8667 let stop_task = self.stop_local_language_servers_for_buffers(&buffers, cx);
8668 cx.spawn(async move |this, cx| {
8669 stop_task.await;
8670 this.update(cx, |this, cx| {
8671 for buffer in buffers {
8672 this.register_buffer_with_language_servers(&buffer, true, cx);
8673 }
8674 })
8675 .ok()
8676 })
8677 .detach();
8678 }
8679 }
8680
8681 pub fn stop_language_servers_for_buffers(
8682 &mut self,
8683 buffers: Vec<Entity<Buffer>>,
8684 cx: &mut Context<Self>,
8685 ) {
8686 if let Some((client, project_id)) = self.upstream_client() {
8687 let request = client.request(proto::StopLanguageServers {
8688 project_id,
8689 buffer_ids: buffers
8690 .into_iter()
8691 .map(|b| b.read(cx).remote_id().to_proto())
8692 .collect(),
8693 });
8694 cx.background_spawn(request).detach_and_log_err(cx);
8695 } else {
8696 self.stop_local_language_servers_for_buffers(&buffers, cx)
8697 .detach();
8698 }
8699 }
8700
8701 fn stop_local_language_servers_for_buffers(
8702 &mut self,
8703 buffers: &[Entity<Buffer>],
8704 cx: &mut Context<Self>,
8705 ) -> Task<()> {
8706 let Some(local) = self.as_local_mut() else {
8707 return Task::ready(());
8708 };
8709 let language_servers_to_stop = buffers
8710 .iter()
8711 .flat_map(|buffer| {
8712 buffer.update(cx, |buffer, cx| {
8713 local.language_server_ids_for_buffer(buffer, cx)
8714 })
8715 })
8716 .collect::<BTreeSet<_>>();
8717 local.lsp_tree.update(cx, |this, _| {
8718 this.remove_nodes(&language_servers_to_stop);
8719 });
8720 let tasks = language_servers_to_stop
8721 .into_iter()
8722 .map(|server| {
8723 let name = self
8724 .language_server_statuses
8725 .get(&server)
8726 .map(|state| state.name.as_str().into())
8727 .unwrap_or_else(|| LanguageServerName::from("Unknown"));
8728 self.stop_local_language_server(server, name, cx)
8729 })
8730 .collect::<Vec<_>>();
8731
8732 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
8733 }
8734
8735 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
8736 let (worktree, relative_path) =
8737 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
8738
8739 let project_path = ProjectPath {
8740 worktree_id: worktree.read(cx).id(),
8741 path: relative_path.into(),
8742 };
8743
8744 Some(
8745 self.buffer_store()
8746 .read(cx)
8747 .get_by_path(&project_path, cx)?
8748 .read(cx),
8749 )
8750 }
8751
8752 pub fn update_diagnostics(
8753 &mut self,
8754 language_server_id: LanguageServerId,
8755 params: lsp::PublishDiagnosticsParams,
8756 disk_based_sources: &[String],
8757 cx: &mut Context<Self>,
8758 ) -> Result<()> {
8759 self.merge_diagnostics(
8760 language_server_id,
8761 params,
8762 disk_based_sources,
8763 |_, _| false,
8764 cx,
8765 )
8766 }
8767
8768 pub fn merge_diagnostics<F: Fn(&Diagnostic, &App) -> bool + Clone>(
8769 &mut self,
8770 language_server_id: LanguageServerId,
8771 mut params: lsp::PublishDiagnosticsParams,
8772 disk_based_sources: &[String],
8773 filter: F,
8774 cx: &mut Context<Self>,
8775 ) -> Result<()> {
8776 if !self.mode.is_local() {
8777 anyhow::bail!("called update_diagnostics on remote");
8778 }
8779 let abs_path = params
8780 .uri
8781 .to_file_path()
8782 .map_err(|_| anyhow!("URI is not a file"))?;
8783 let mut diagnostics = Vec::default();
8784 let mut primary_diagnostic_group_ids = HashMap::default();
8785 let mut sources_by_group_id = HashMap::default();
8786 let mut supporting_diagnostics = HashMap::default();
8787
8788 let adapter = self.language_server_adapter_for_id(language_server_id);
8789
8790 // Ensure that primary diagnostics are always the most severe
8791 params.diagnostics.sort_by_key(|item| item.severity);
8792
8793 for diagnostic in ¶ms.diagnostics {
8794 let source = diagnostic.source.as_ref();
8795 let range = range_from_lsp(diagnostic.range);
8796 let is_supporting = diagnostic
8797 .related_information
8798 .as_ref()
8799 .map_or(false, |infos| {
8800 infos.iter().any(|info| {
8801 primary_diagnostic_group_ids.contains_key(&(
8802 source,
8803 diagnostic.code.clone(),
8804 range_from_lsp(info.location.range),
8805 ))
8806 })
8807 });
8808
8809 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
8810 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
8811 });
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}