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