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