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: Option<LspData>,
3546}
3547
3548type DocumentColorTask =
3549 Shared<Task<std::result::Result<HashSet<DocumentColor>, Arc<anyhow::Error>>>>;
3550
3551#[derive(Debug)]
3552struct LspData {
3553 mtime: MTime,
3554 buffer_lsp_data: HashMap<LanguageServerId, HashMap<PathBuf, BufferLspData>>,
3555 colors_update: HashMap<PathBuf, DocumentColorTask>,
3556 last_version_queried: HashMap<PathBuf, Global>,
3557}
3558
3559#[derive(Debug, Default)]
3560struct BufferLspData {
3561 colors: Option<HashSet<DocumentColor>>,
3562}
3563
3564#[derive(Debug)]
3565pub enum LspStoreEvent {
3566 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3567 LanguageServerRemoved(LanguageServerId),
3568 LanguageServerUpdate {
3569 language_server_id: LanguageServerId,
3570 name: Option<LanguageServerName>,
3571 message: proto::update_language_server::Variant,
3572 },
3573 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3574 LanguageServerPrompt(LanguageServerPromptRequest),
3575 LanguageDetected {
3576 buffer: Entity<Buffer>,
3577 new_language: Option<Arc<Language>>,
3578 },
3579 Notification(String),
3580 RefreshInlayHints,
3581 RefreshCodeLens,
3582 DiagnosticsUpdated {
3583 language_server_id: LanguageServerId,
3584 path: ProjectPath,
3585 },
3586 DiskBasedDiagnosticsStarted {
3587 language_server_id: LanguageServerId,
3588 },
3589 DiskBasedDiagnosticsFinished {
3590 language_server_id: LanguageServerId,
3591 },
3592 SnippetEdit {
3593 buffer_id: BufferId,
3594 edits: Vec<(lsp::Range, Snippet)>,
3595 most_recent_edit: clock::Lamport,
3596 },
3597}
3598
3599#[derive(Clone, Debug, Serialize)]
3600pub struct LanguageServerStatus {
3601 pub name: String,
3602 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3603 pub has_pending_diagnostic_updates: bool,
3604 progress_tokens: HashSet<String>,
3605}
3606
3607#[derive(Clone, Debug)]
3608struct CoreSymbol {
3609 pub language_server_name: LanguageServerName,
3610 pub source_worktree_id: WorktreeId,
3611 pub source_language_server_id: LanguageServerId,
3612 pub path: ProjectPath,
3613 pub name: String,
3614 pub kind: lsp::SymbolKind,
3615 pub range: Range<Unclipped<PointUtf16>>,
3616 pub signature: [u8; 32],
3617}
3618
3619impl LspStore {
3620 pub fn init(client: &AnyProtoClient) {
3621 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3622 client.add_entity_request_handler(Self::handle_restart_language_servers);
3623 client.add_entity_request_handler(Self::handle_stop_language_servers);
3624 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3625 client.add_entity_message_handler(Self::handle_start_language_server);
3626 client.add_entity_message_handler(Self::handle_update_language_server);
3627 client.add_entity_message_handler(Self::handle_language_server_log);
3628 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3629 client.add_entity_request_handler(Self::handle_format_buffers);
3630 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3631 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3632 client.add_entity_request_handler(Self::handle_apply_code_action);
3633 client.add_entity_request_handler(Self::handle_inlay_hints);
3634 client.add_entity_request_handler(Self::handle_get_project_symbols);
3635 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3636 client.add_entity_request_handler(Self::handle_get_color_presentation);
3637 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3638 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3639 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3640 client.add_entity_request_handler(Self::handle_on_type_formatting);
3641 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3642 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3643 client.add_entity_request_handler(Self::handle_rename_project_entry);
3644 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3645 client.add_entity_request_handler(Self::handle_pull_workspace_diagnostics);
3646 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3647 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3648 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3649 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3650 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3651 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3652 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3653 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3654 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3655 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3656 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3657 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3658
3659 client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
3660 client.add_entity_request_handler(Self::handle_lsp_ext_run_flycheck);
3661 client.add_entity_request_handler(Self::handle_lsp_ext_clear_flycheck);
3662 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3663 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3664 client.add_entity_request_handler(
3665 Self::handle_lsp_command::<lsp_ext_command::GoToParentModule>,
3666 );
3667 client.add_entity_request_handler(
3668 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3669 );
3670 client.add_entity_request_handler(
3671 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3672 );
3673 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentDiagnostics>);
3674 }
3675
3676 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3677 match &self.mode {
3678 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3679 _ => None,
3680 }
3681 }
3682
3683 pub fn as_local(&self) -> Option<&LocalLspStore> {
3684 match &self.mode {
3685 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3686 _ => None,
3687 }
3688 }
3689
3690 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3691 match &mut self.mode {
3692 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3693 _ => None,
3694 }
3695 }
3696
3697 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3698 match &self.mode {
3699 LspStoreMode::Remote(RemoteLspStore {
3700 upstream_client: Some(upstream_client),
3701 upstream_project_id,
3702 ..
3703 }) => Some((upstream_client.clone(), *upstream_project_id)),
3704
3705 LspStoreMode::Remote(RemoteLspStore {
3706 upstream_client: None,
3707 ..
3708 }) => None,
3709 LspStoreMode::Local(_) => None,
3710 }
3711 }
3712
3713 pub fn new_local(
3714 buffer_store: Entity<BufferStore>,
3715 worktree_store: Entity<WorktreeStore>,
3716 prettier_store: Entity<PrettierStore>,
3717 toolchain_store: Entity<ToolchainStore>,
3718 environment: Entity<ProjectEnvironment>,
3719 manifest_tree: Entity<ManifestTree>,
3720 languages: Arc<LanguageRegistry>,
3721 http_client: Arc<dyn HttpClient>,
3722 fs: Arc<dyn Fs>,
3723 cx: &mut Context<Self>,
3724 ) -> Self {
3725 let yarn = YarnPathStore::new(fs.clone(), cx);
3726 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3727 .detach();
3728 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3729 .detach();
3730 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3731 .detach();
3732 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3733 .detach();
3734 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3735 cx.subscribe(
3736 extension_events,
3737 Self::reload_zed_json_schemas_on_extensions_changed,
3738 )
3739 .detach();
3740 } else {
3741 log::debug!("No extension events global found. Skipping JSON schema auto-reload setup");
3742 }
3743 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3744 .detach();
3745 subscribe_to_binary_statuses(&languages, cx).detach();
3746
3747 let _maintain_workspace_config = {
3748 let (sender, receiver) = watch::channel();
3749 (
3750 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3751 sender,
3752 )
3753 };
3754
3755 Self {
3756 mode: LspStoreMode::Local(LocalLspStore {
3757 weak: cx.weak_entity(),
3758 worktree_store: worktree_store.clone(),
3759 toolchain_store: toolchain_store.clone(),
3760 supplementary_language_servers: Default::default(),
3761 languages: languages.clone(),
3762 language_server_ids: Default::default(),
3763 language_servers: Default::default(),
3764 last_workspace_edits_by_language_server: Default::default(),
3765 language_server_watched_paths: Default::default(),
3766 language_server_paths_watched_for_rename: Default::default(),
3767 language_server_watcher_registrations: Default::default(),
3768 buffers_being_formatted: Default::default(),
3769 buffer_snapshots: Default::default(),
3770 prettier_store,
3771 environment,
3772 http_client,
3773 fs,
3774 yarn,
3775 next_diagnostic_group_id: Default::default(),
3776 diagnostics: Default::default(),
3777 _subscription: cx.on_app_quit(|this, cx| {
3778 this.as_local_mut()
3779 .unwrap()
3780 .shutdown_language_servers_on_quit(cx)
3781 }),
3782 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3783 registered_buffers: HashMap::default(),
3784 buffer_pull_diagnostics_result_ids: HashMap::default(),
3785 }),
3786 last_formatting_failure: None,
3787 downstream_client: None,
3788 buffer_store,
3789 worktree_store,
3790 toolchain_store: Some(toolchain_store),
3791 languages: languages.clone(),
3792 language_server_statuses: Default::default(),
3793 nonce: StdRng::from_entropy().r#gen(),
3794 diagnostic_summaries: HashMap::default(),
3795 lsp_data: None,
3796 active_entry: None,
3797 _maintain_workspace_config,
3798 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3799 }
3800 }
3801
3802 fn send_lsp_proto_request<R: LspCommand>(
3803 &self,
3804 buffer: Entity<Buffer>,
3805 client: AnyProtoClient,
3806 upstream_project_id: u64,
3807 request: R,
3808 cx: &mut Context<LspStore>,
3809 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3810 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3811 cx.spawn(async move |this, cx| {
3812 let response = client.request(message).await?;
3813 let this = this.upgrade().context("project dropped")?;
3814 request
3815 .response_from_proto(response, this, buffer, cx.clone())
3816 .await
3817 })
3818 }
3819
3820 pub(super) fn new_remote(
3821 buffer_store: Entity<BufferStore>,
3822 worktree_store: Entity<WorktreeStore>,
3823 toolchain_store: Option<Entity<ToolchainStore>>,
3824 languages: Arc<LanguageRegistry>,
3825 upstream_client: AnyProtoClient,
3826 project_id: u64,
3827 fs: Arc<dyn Fs>,
3828 cx: &mut Context<Self>,
3829 ) -> Self {
3830 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3831 .detach();
3832 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3833 .detach();
3834 subscribe_to_binary_statuses(&languages, cx).detach();
3835 let _maintain_workspace_config = {
3836 let (sender, receiver) = watch::channel();
3837 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3838 };
3839 Self {
3840 mode: LspStoreMode::Remote(RemoteLspStore {
3841 upstream_client: Some(upstream_client),
3842 upstream_project_id: project_id,
3843 }),
3844 downstream_client: None,
3845 last_formatting_failure: None,
3846 buffer_store,
3847 worktree_store,
3848 languages: languages.clone(),
3849 language_server_statuses: Default::default(),
3850 nonce: StdRng::from_entropy().r#gen(),
3851 diagnostic_summaries: HashMap::default(),
3852 lsp_data: None,
3853 active_entry: None,
3854 toolchain_store,
3855 _maintain_workspace_config,
3856 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3857 }
3858 }
3859
3860 fn on_buffer_store_event(
3861 &mut self,
3862 _: Entity<BufferStore>,
3863 event: &BufferStoreEvent,
3864 cx: &mut Context<Self>,
3865 ) {
3866 match event {
3867 BufferStoreEvent::BufferAdded(buffer) => {
3868 self.on_buffer_added(buffer, cx).log_err();
3869 }
3870 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3871 let buffer_id = buffer.read(cx).remote_id();
3872 if let Some(local) = self.as_local_mut() {
3873 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3874 local.reset_buffer(buffer, old_file, cx);
3875
3876 if local.registered_buffers.contains_key(&buffer_id) {
3877 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3878 }
3879 }
3880 }
3881
3882 self.detect_language_for_buffer(buffer, cx);
3883 if let Some(local) = self.as_local_mut() {
3884 local.initialize_buffer(buffer, cx);
3885 if local.registered_buffers.contains_key(&buffer_id) {
3886 local.register_buffer_with_language_servers(buffer, HashSet::default(), cx);
3887 }
3888 }
3889 }
3890 _ => {}
3891 }
3892 }
3893
3894 fn on_worktree_store_event(
3895 &mut self,
3896 _: Entity<WorktreeStore>,
3897 event: &WorktreeStoreEvent,
3898 cx: &mut Context<Self>,
3899 ) {
3900 match event {
3901 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3902 if !worktree.read(cx).is_local() {
3903 return;
3904 }
3905 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3906 worktree::Event::UpdatedEntries(changes) => {
3907 this.update_local_worktree_language_servers(&worktree, changes, cx);
3908 }
3909 worktree::Event::UpdatedGitRepositories(_)
3910 | worktree::Event::DeletedEntry(_) => {}
3911 })
3912 .detach()
3913 }
3914 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3915 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3916 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3917 }
3918 WorktreeStoreEvent::WorktreeReleased(..)
3919 | WorktreeStoreEvent::WorktreeOrderChanged
3920 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3921 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3922 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3923 }
3924 }
3925
3926 fn on_prettier_store_event(
3927 &mut self,
3928 _: Entity<PrettierStore>,
3929 event: &PrettierStoreEvent,
3930 cx: &mut Context<Self>,
3931 ) {
3932 match event {
3933 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3934 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3935 }
3936 PrettierStoreEvent::LanguageServerAdded {
3937 new_server_id,
3938 name,
3939 prettier_server,
3940 } => {
3941 self.register_supplementary_language_server(
3942 *new_server_id,
3943 name.clone(),
3944 prettier_server.clone(),
3945 cx,
3946 );
3947 }
3948 }
3949 }
3950
3951 fn on_toolchain_store_event(
3952 &mut self,
3953 _: Entity<ToolchainStore>,
3954 event: &ToolchainStoreEvent,
3955 _: &mut Context<Self>,
3956 ) {
3957 match event {
3958 ToolchainStoreEvent::ToolchainActivated { .. } => {
3959 self.request_workspace_config_refresh()
3960 }
3961 }
3962 }
3963
3964 fn request_workspace_config_refresh(&mut self) {
3965 *self._maintain_workspace_config.1.borrow_mut() = ();
3966 }
3967
3968 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3969 self.as_local().map(|local| local.prettier_store.clone())
3970 }
3971
3972 fn on_buffer_event(
3973 &mut self,
3974 buffer: Entity<Buffer>,
3975 event: &language::BufferEvent,
3976 cx: &mut Context<Self>,
3977 ) {
3978 match event {
3979 language::BufferEvent::Edited => {
3980 self.on_buffer_edited(buffer, cx);
3981 }
3982
3983 language::BufferEvent::Saved => {
3984 self.on_buffer_saved(buffer, cx);
3985 }
3986
3987 _ => {}
3988 }
3989 }
3990
3991 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3992 buffer
3993 .read(cx)
3994 .set_language_registry(self.languages.clone());
3995
3996 cx.subscribe(buffer, |this, buffer, event, cx| {
3997 this.on_buffer_event(buffer, event, cx);
3998 })
3999 .detach();
4000
4001 self.detect_language_for_buffer(buffer, cx);
4002 if let Some(local) = self.as_local_mut() {
4003 local.initialize_buffer(buffer, cx);
4004 }
4005
4006 Ok(())
4007 }
4008
4009 pub fn reload_zed_json_schemas_on_extensions_changed(
4010 &mut self,
4011 _: Entity<extension::ExtensionEvents>,
4012 evt: &extension::Event,
4013 cx: &mut Context<Self>,
4014 ) {
4015 match evt {
4016 extension::Event::ExtensionInstalled(_)
4017 | extension::Event::ExtensionUninstalled(_)
4018 | extension::Event::ConfigureExtensionRequested(_) => return,
4019 extension::Event::ExtensionsInstalledChanged => {}
4020 }
4021 if self.as_local().is_none() {
4022 return;
4023 }
4024 cx.spawn(async move |this, cx| {
4025 let weak_ref = this.clone();
4026
4027 let servers = this
4028 .update(cx, |this, cx| {
4029 let local = this.as_local()?;
4030
4031 let mut servers = Vec::new();
4032 for ((worktree_id, _), server_ids) in &local.language_server_ids {
4033 for server_id in server_ids {
4034 let Some(states) = local.language_servers.get(server_id) else {
4035 continue;
4036 };
4037 let (json_adapter, json_server) = match states {
4038 LanguageServerState::Running {
4039 adapter, server, ..
4040 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
4041 (adapter.adapter.clone(), server.clone())
4042 }
4043 _ => continue,
4044 };
4045
4046 let Some(worktree) = this
4047 .worktree_store
4048 .read(cx)
4049 .worktree_for_id(*worktree_id, cx)
4050 else {
4051 continue;
4052 };
4053 let json_delegate: Arc<dyn LspAdapterDelegate> =
4054 LocalLspAdapterDelegate::new(
4055 local.languages.clone(),
4056 &local.environment,
4057 weak_ref.clone(),
4058 &worktree,
4059 local.http_client.clone(),
4060 local.fs.clone(),
4061 cx,
4062 );
4063
4064 servers.push((json_adapter, json_server, json_delegate));
4065 }
4066 }
4067 return Some(servers);
4068 })
4069 .ok()
4070 .flatten();
4071
4072 let Some(servers) = servers else {
4073 return;
4074 };
4075
4076 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
4077 let local = this.as_local()?;
4078 let toolchain_store = this.toolchain_store(cx);
4079 return Some((local.fs.clone(), toolchain_store));
4080 }) else {
4081 return;
4082 };
4083 for (adapter, server, delegate) in servers {
4084 adapter.clear_zed_json_schema_cache().await;
4085
4086 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
4087 adapter,
4088 fs.as_ref(),
4089 &delegate,
4090 toolchain_store.clone(),
4091 cx,
4092 )
4093 .await
4094 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
4095 .ok()
4096 else {
4097 continue;
4098 };
4099 server
4100 .notify::<lsp::notification::DidChangeConfiguration>(
4101 &lsp::DidChangeConfigurationParams {
4102 settings: json_workspace_config,
4103 },
4104 )
4105 .ok();
4106 }
4107 })
4108 .detach();
4109 }
4110
4111 pub(crate) fn register_buffer_with_language_servers(
4112 &mut self,
4113 buffer: &Entity<Buffer>,
4114 only_register_servers: HashSet<LanguageServerSelector>,
4115 ignore_refcounts: bool,
4116 cx: &mut Context<Self>,
4117 ) -> OpenLspBufferHandle {
4118 let buffer_id = buffer.read(cx).remote_id();
4119 let handle = cx.new(|_| buffer.clone());
4120 if let Some(local) = self.as_local_mut() {
4121 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
4122 if !ignore_refcounts {
4123 *refcount += 1;
4124 }
4125
4126 // We run early exits on non-existing buffers AFTER we mark the buffer as registered in order to handle buffer saving.
4127 // 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
4128 // 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
4129 // servers in practice (we don't support non-file URI schemes in our LSP impl).
4130 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
4131 return handle;
4132 };
4133 if !file.is_local() {
4134 return handle;
4135 }
4136
4137 if ignore_refcounts || *refcount == 1 {
4138 local.register_buffer_with_language_servers(buffer, only_register_servers, cx);
4139 }
4140 if !ignore_refcounts {
4141 cx.observe_release(&handle, move |this, buffer, cx| {
4142 let local = this.as_local_mut().unwrap();
4143 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
4144 debug_panic!("bad refcounting");
4145 return;
4146 };
4147
4148 *refcount -= 1;
4149 if *refcount == 0 {
4150 local.registered_buffers.remove(&buffer_id);
4151 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
4152 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
4153 }
4154 }
4155 })
4156 .detach();
4157 }
4158 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4159 let buffer_id = buffer.read(cx).remote_id().to_proto();
4160 cx.background_spawn(async move {
4161 upstream_client
4162 .request(proto::RegisterBufferWithLanguageServers {
4163 project_id: upstream_project_id,
4164 buffer_id,
4165 only_servers: only_register_servers
4166 .into_iter()
4167 .map(|selector| {
4168 let selector = match selector {
4169 LanguageServerSelector::Id(language_server_id) => {
4170 proto::language_server_selector::Selector::ServerId(
4171 language_server_id.to_proto(),
4172 )
4173 }
4174 LanguageServerSelector::Name(language_server_name) => {
4175 proto::language_server_selector::Selector::Name(
4176 language_server_name.to_string(),
4177 )
4178 }
4179 };
4180 proto::LanguageServerSelector {
4181 selector: Some(selector),
4182 }
4183 })
4184 .collect(),
4185 })
4186 .await
4187 })
4188 .detach();
4189 } else {
4190 panic!("oops!");
4191 }
4192 handle
4193 }
4194
4195 fn maintain_buffer_languages(
4196 languages: Arc<LanguageRegistry>,
4197 cx: &mut Context<Self>,
4198 ) -> Task<()> {
4199 let mut subscription = languages.subscribe();
4200 let mut prev_reload_count = languages.reload_count();
4201 cx.spawn(async move |this, cx| {
4202 while let Some(()) = subscription.next().await {
4203 if let Some(this) = this.upgrade() {
4204 // If the language registry has been reloaded, then remove and
4205 // re-assign the languages on all open buffers.
4206 let reload_count = languages.reload_count();
4207 if reload_count > prev_reload_count {
4208 prev_reload_count = reload_count;
4209 this.update(cx, |this, cx| {
4210 this.buffer_store.clone().update(cx, |buffer_store, cx| {
4211 for buffer in buffer_store.buffers() {
4212 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
4213 {
4214 buffer
4215 .update(cx, |buffer, cx| buffer.set_language(None, cx));
4216 if let Some(local) = this.as_local_mut() {
4217 local.reset_buffer(&buffer, &f, cx);
4218
4219 if local
4220 .registered_buffers
4221 .contains_key(&buffer.read(cx).remote_id())
4222 {
4223 if let Some(file_url) =
4224 file_path_to_lsp_url(&f.abs_path(cx)).log_err()
4225 {
4226 local.unregister_buffer_from_language_servers(
4227 &buffer, &file_url, cx,
4228 );
4229 }
4230 }
4231 }
4232 }
4233 }
4234 });
4235 })
4236 .ok();
4237 }
4238
4239 this.update(cx, |this, cx| {
4240 let mut plain_text_buffers = Vec::new();
4241 let mut buffers_with_unknown_injections = Vec::new();
4242 for handle in this.buffer_store.read(cx).buffers() {
4243 let buffer = handle.read(cx);
4244 if buffer.language().is_none()
4245 || buffer.language() == Some(&*language::PLAIN_TEXT)
4246 {
4247 plain_text_buffers.push(handle);
4248 } else if buffer.contains_unknown_injections() {
4249 buffers_with_unknown_injections.push(handle);
4250 }
4251 }
4252
4253 // Deprioritize the invisible worktrees so main worktrees' language servers can be started first,
4254 // and reused later in the invisible worktrees.
4255 plain_text_buffers.sort_by_key(|buffer| {
4256 Reverse(
4257 File::from_dyn(buffer.read(cx).file())
4258 .map(|file| file.worktree.read(cx).is_visible()),
4259 )
4260 });
4261
4262 for buffer in plain_text_buffers {
4263 this.detect_language_for_buffer(&buffer, cx);
4264 if let Some(local) = this.as_local_mut() {
4265 local.initialize_buffer(&buffer, cx);
4266 if local
4267 .registered_buffers
4268 .contains_key(&buffer.read(cx).remote_id())
4269 {
4270 local.register_buffer_with_language_servers(
4271 &buffer,
4272 HashSet::default(),
4273 cx,
4274 );
4275 }
4276 }
4277 }
4278
4279 for buffer in buffers_with_unknown_injections {
4280 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4281 }
4282 })
4283 .ok();
4284 }
4285 }
4286 })
4287 }
4288
4289 fn detect_language_for_buffer(
4290 &mut self,
4291 buffer_handle: &Entity<Buffer>,
4292 cx: &mut Context<Self>,
4293 ) -> Option<language::AvailableLanguage> {
4294 // If the buffer has a language, set it and start the language server if we haven't already.
4295 let buffer = buffer_handle.read(cx);
4296 let file = buffer.file()?;
4297
4298 let content = buffer.as_rope();
4299 let available_language = self.languages.language_for_file(file, Some(content), cx);
4300 if let Some(available_language) = &available_language {
4301 if let Some(Ok(Ok(new_language))) = self
4302 .languages
4303 .load_language(available_language)
4304 .now_or_never()
4305 {
4306 self.set_language_for_buffer(buffer_handle, new_language, cx);
4307 }
4308 } else {
4309 cx.emit(LspStoreEvent::LanguageDetected {
4310 buffer: buffer_handle.clone(),
4311 new_language: None,
4312 });
4313 }
4314
4315 available_language
4316 }
4317
4318 pub(crate) fn set_language_for_buffer(
4319 &mut self,
4320 buffer_entity: &Entity<Buffer>,
4321 new_language: Arc<Language>,
4322 cx: &mut Context<Self>,
4323 ) {
4324 let buffer = buffer_entity.read(cx);
4325 let buffer_file = buffer.file().cloned();
4326 let buffer_id = buffer.remote_id();
4327 if let Some(local_store) = self.as_local_mut() {
4328 if local_store.registered_buffers.contains_key(&buffer_id) {
4329 if let Some(abs_path) =
4330 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4331 {
4332 if let Some(file_url) = file_path_to_lsp_url(&abs_path).log_err() {
4333 local_store.unregister_buffer_from_language_servers(
4334 buffer_entity,
4335 &file_url,
4336 cx,
4337 );
4338 }
4339 }
4340 }
4341 }
4342 buffer_entity.update(cx, |buffer, cx| {
4343 if buffer.language().map_or(true, |old_language| {
4344 !Arc::ptr_eq(old_language, &new_language)
4345 }) {
4346 buffer.set_language(Some(new_language.clone()), cx);
4347 }
4348 });
4349
4350 let settings =
4351 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4352 let buffer_file = File::from_dyn(buffer_file.as_ref());
4353
4354 let worktree_id = if let Some(file) = buffer_file {
4355 let worktree = file.worktree.clone();
4356
4357 if let Some(local) = self.as_local_mut() {
4358 if local.registered_buffers.contains_key(&buffer_id) {
4359 local.register_buffer_with_language_servers(
4360 buffer_entity,
4361 HashSet::default(),
4362 cx,
4363 );
4364 }
4365 }
4366 Some(worktree.read(cx).id())
4367 } else {
4368 None
4369 };
4370
4371 if settings.prettier.allowed {
4372 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4373 {
4374 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4375 if let Some(prettier_store) = prettier_store {
4376 prettier_store.update(cx, |prettier_store, cx| {
4377 prettier_store.install_default_prettier(
4378 worktree_id,
4379 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4380 cx,
4381 )
4382 })
4383 }
4384 }
4385 }
4386
4387 cx.emit(LspStoreEvent::LanguageDetected {
4388 buffer: buffer_entity.clone(),
4389 new_language: Some(new_language),
4390 })
4391 }
4392
4393 pub fn buffer_store(&self) -> Entity<BufferStore> {
4394 self.buffer_store.clone()
4395 }
4396
4397 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4398 self.active_entry = active_entry;
4399 }
4400
4401 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4402 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4403 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4404 for (path, summaries) in summaries {
4405 for (&server_id, summary) in summaries {
4406 client
4407 .send(proto::UpdateDiagnosticSummary {
4408 project_id: downstream_project_id,
4409 worktree_id: worktree.id().to_proto(),
4410 summary: Some(summary.to_proto(server_id, path)),
4411 })
4412 .log_err();
4413 }
4414 }
4415 }
4416 }
4417 }
4418
4419 pub fn request_lsp<R: LspCommand>(
4420 &mut self,
4421 buffer_handle: Entity<Buffer>,
4422 server: LanguageServerToQuery,
4423 request: R,
4424 cx: &mut Context<Self>,
4425 ) -> Task<Result<R::Response>>
4426 where
4427 <R::LspRequest as lsp::request::Request>::Result: Send,
4428 <R::LspRequest as lsp::request::Request>::Params: Send,
4429 {
4430 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4431 return self.send_lsp_proto_request(
4432 buffer_handle,
4433 upstream_client,
4434 upstream_project_id,
4435 request,
4436 cx,
4437 );
4438 }
4439
4440 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4441 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4442 local
4443 .language_servers_for_buffer(buffer, cx)
4444 .find(|(_, server)| {
4445 request.check_capabilities(server.adapter_server_capabilities())
4446 })
4447 .map(|(_, server)| server.clone())
4448 }),
4449 LanguageServerToQuery::Other(id) => self
4450 .language_server_for_local_buffer(buffer, id, cx)
4451 .and_then(|(_, server)| {
4452 request
4453 .check_capabilities(server.adapter_server_capabilities())
4454 .then(|| Arc::clone(server))
4455 }),
4456 }) else {
4457 return Task::ready(Ok(Default::default()));
4458 };
4459
4460 let buffer = buffer_handle.read(cx);
4461 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4462
4463 let Some(file) = file else {
4464 return Task::ready(Ok(Default::default()));
4465 };
4466
4467 let lsp_params = match request.to_lsp_params_or_response(
4468 &file.abs_path(cx),
4469 buffer,
4470 &language_server,
4471 cx,
4472 ) {
4473 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4474 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4475
4476 Err(err) => {
4477 let message = format!(
4478 "{} via {} failed: {}",
4479 request.display_name(),
4480 language_server.name(),
4481 err
4482 );
4483 log::warn!("{message}");
4484 return Task::ready(Err(anyhow!(message)));
4485 }
4486 };
4487
4488 let status = request.status();
4489 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4490 return Task::ready(Ok(Default::default()));
4491 }
4492 return cx.spawn(async move |this, cx| {
4493 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4494
4495 let id = lsp_request.id();
4496 let _cleanup = if status.is_some() {
4497 cx.update(|cx| {
4498 this.update(cx, |this, cx| {
4499 this.on_lsp_work_start(
4500 language_server.server_id(),
4501 id.to_string(),
4502 LanguageServerProgress {
4503 is_disk_based_diagnostics_progress: false,
4504 is_cancellable: false,
4505 title: None,
4506 message: status.clone(),
4507 percentage: None,
4508 last_update_at: cx.background_executor().now(),
4509 },
4510 cx,
4511 );
4512 })
4513 })
4514 .log_err();
4515
4516 Some(defer(|| {
4517 cx.update(|cx| {
4518 this.update(cx, |this, cx| {
4519 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4520 })
4521 })
4522 .log_err();
4523 }))
4524 } else {
4525 None
4526 };
4527
4528 let result = lsp_request.await.into_response();
4529
4530 let response = result.map_err(|err| {
4531 let message = format!(
4532 "{} via {} failed: {}",
4533 request.display_name(),
4534 language_server.name(),
4535 err
4536 );
4537 log::warn!("{message}");
4538 anyhow::anyhow!(message)
4539 })?;
4540
4541 let response = request
4542 .response_from_lsp(
4543 response,
4544 this.upgrade().context("no app context")?,
4545 buffer_handle,
4546 language_server.server_id(),
4547 cx.clone(),
4548 )
4549 .await;
4550 response
4551 });
4552 }
4553
4554 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4555 let mut language_formatters_to_check = Vec::new();
4556 for buffer in self.buffer_store.read(cx).buffers() {
4557 let buffer = buffer.read(cx);
4558 let buffer_file = File::from_dyn(buffer.file());
4559 let buffer_language = buffer.language();
4560 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4561 if buffer_language.is_some() {
4562 language_formatters_to_check.push((
4563 buffer_file.map(|f| f.worktree_id(cx)),
4564 settings.into_owned(),
4565 ));
4566 }
4567 }
4568
4569 self.refresh_server_tree(cx);
4570
4571 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4572 prettier_store.update(cx, |prettier_store, cx| {
4573 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4574 })
4575 }
4576
4577 cx.notify();
4578 }
4579
4580 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4581 let buffer_store = self.buffer_store.clone();
4582 if let Some(local) = self.as_local_mut() {
4583 let mut adapters = BTreeMap::default();
4584 let get_adapter = {
4585 let languages = local.languages.clone();
4586 let environment = local.environment.clone();
4587 let weak = local.weak.clone();
4588 let worktree_store = local.worktree_store.clone();
4589 let http_client = local.http_client.clone();
4590 let fs = local.fs.clone();
4591 move |worktree_id, cx: &mut App| {
4592 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4593 Some(LocalLspAdapterDelegate::new(
4594 languages.clone(),
4595 &environment,
4596 weak.clone(),
4597 &worktree,
4598 http_client.clone(),
4599 fs.clone(),
4600 cx,
4601 ))
4602 }
4603 };
4604
4605 let mut messages_to_report = Vec::new();
4606 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4607 let mut rebase = lsp_tree.rebase();
4608 for buffer_handle in buffer_store.read(cx).buffers().sorted_by_key(|buffer| {
4609 Reverse(
4610 File::from_dyn(buffer.read(cx).file())
4611 .map(|file| file.worktree.read(cx).is_visible()),
4612 )
4613 }) {
4614 let buffer = buffer_handle.read(cx);
4615 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4616 continue;
4617 }
4618 if let Some((file, language)) = File::from_dyn(buffer.file())
4619 .cloned()
4620 .zip(buffer.language().map(|l| l.name()))
4621 {
4622 let worktree_id = file.worktree_id(cx);
4623 let Some(worktree) = local
4624 .worktree_store
4625 .read(cx)
4626 .worktree_for_id(worktree_id, cx)
4627 else {
4628 continue;
4629 };
4630
4631 let Some((reused, delegate, nodes)) = local
4632 .reuse_existing_language_server(
4633 rebase.server_tree(),
4634 &worktree,
4635 &language,
4636 cx,
4637 )
4638 .map(|(delegate, servers)| (true, delegate, servers))
4639 .or_else(|| {
4640 let lsp_delegate = adapters
4641 .entry(worktree_id)
4642 .or_insert_with(|| get_adapter(worktree_id, cx))
4643 .clone()?;
4644 let delegate = Arc::new(ManifestQueryDelegate::new(
4645 worktree.read(cx).snapshot(),
4646 ));
4647 let path = file
4648 .path()
4649 .parent()
4650 .map(Arc::from)
4651 .unwrap_or_else(|| file.path().clone());
4652 let worktree_path = ProjectPath { worktree_id, path };
4653
4654 let nodes = rebase.get(
4655 worktree_path,
4656 AdapterQuery::Language(&language),
4657 delegate.clone(),
4658 cx,
4659 );
4660
4661 Some((false, lsp_delegate, nodes.collect()))
4662 })
4663 else {
4664 continue;
4665 };
4666
4667 let abs_path = file.abs_path(cx);
4668 for node in nodes {
4669 if !reused {
4670 let server_id = node.server_id_or_init(
4671 |LaunchDisposition {
4672 server_name,
4673 attach,
4674 path,
4675 settings,
4676 }| match attach {
4677 language::Attach::InstancePerRoot => {
4678 // todo: handle instance per root proper.
4679 if let Some(server_ids) = local
4680 .language_server_ids
4681 .get(&(worktree_id, server_name.clone()))
4682 {
4683 server_ids.iter().cloned().next().unwrap()
4684 } else {
4685 let adapter = local
4686 .languages
4687 .lsp_adapters(&language)
4688 .into_iter()
4689 .find(|adapter| &adapter.name() == server_name)
4690 .expect("To find LSP adapter");
4691 let server_id = local.start_language_server(
4692 &worktree,
4693 delegate.clone(),
4694 adapter,
4695 settings,
4696 cx,
4697 );
4698 server_id
4699 }
4700 }
4701 language::Attach::Shared => {
4702 let uri = Url::from_file_path(
4703 worktree.read(cx).abs_path().join(&path.path),
4704 );
4705 let key = (worktree_id, server_name.clone());
4706 local.language_server_ids.remove(&key);
4707
4708 let adapter = local
4709 .languages
4710 .lsp_adapters(&language)
4711 .into_iter()
4712 .find(|adapter| &adapter.name() == server_name)
4713 .expect("To find LSP adapter");
4714 let server_id = local.start_language_server(
4715 &worktree,
4716 delegate.clone(),
4717 adapter,
4718 settings,
4719 cx,
4720 );
4721 if let Some(state) =
4722 local.language_servers.get(&server_id)
4723 {
4724 if let Ok(uri) = uri {
4725 state.add_workspace_folder(uri);
4726 };
4727 }
4728 server_id
4729 }
4730 },
4731 );
4732
4733 if let Some(language_server_id) = server_id {
4734 messages_to_report.push(LspStoreEvent::LanguageServerUpdate {
4735 language_server_id,
4736 name: node.name(),
4737 message:
4738 proto::update_language_server::Variant::RegisteredForBuffer(
4739 proto::RegisteredForBuffer {
4740 buffer_abs_path: abs_path.to_string_lossy().to_string(),
4741 },
4742 ),
4743 });
4744 }
4745 }
4746 }
4747 }
4748 }
4749 rebase.finish()
4750 });
4751 for message in messages_to_report {
4752 cx.emit(message);
4753 }
4754 for (id, _) in to_stop {
4755 self.stop_local_language_server(id, cx).detach();
4756 }
4757 }
4758 }
4759
4760 pub fn apply_code_action(
4761 &self,
4762 buffer_handle: Entity<Buffer>,
4763 mut action: CodeAction,
4764 push_to_history: bool,
4765 cx: &mut Context<Self>,
4766 ) -> Task<Result<ProjectTransaction>> {
4767 if let Some((upstream_client, project_id)) = self.upstream_client() {
4768 let request = proto::ApplyCodeAction {
4769 project_id,
4770 buffer_id: buffer_handle.read(cx).remote_id().into(),
4771 action: Some(Self::serialize_code_action(&action)),
4772 };
4773 let buffer_store = self.buffer_store();
4774 cx.spawn(async move |_, cx| {
4775 let response = upstream_client
4776 .request(request)
4777 .await?
4778 .transaction
4779 .context("missing transaction")?;
4780
4781 buffer_store
4782 .update(cx, |buffer_store, cx| {
4783 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4784 })?
4785 .await
4786 })
4787 } else if self.mode.is_local() {
4788 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4789 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4790 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4791 }) else {
4792 return Task::ready(Ok(ProjectTransaction::default()));
4793 };
4794 cx.spawn(async move |this, cx| {
4795 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4796 .await
4797 .context("resolving a code action")?;
4798 if let Some(edit) = action.lsp_action.edit() {
4799 if edit.changes.is_some() || edit.document_changes.is_some() {
4800 return LocalLspStore::deserialize_workspace_edit(
4801 this.upgrade().context("no app present")?,
4802 edit.clone(),
4803 push_to_history,
4804 lsp_adapter.clone(),
4805 lang_server.clone(),
4806 cx,
4807 )
4808 .await;
4809 }
4810 }
4811
4812 if let Some(command) = action.lsp_action.command() {
4813 let server_capabilities = lang_server.capabilities();
4814 let available_commands = server_capabilities
4815 .execute_command_provider
4816 .as_ref()
4817 .map(|options| options.commands.as_slice())
4818 .unwrap_or_default();
4819 if available_commands.contains(&command.command) {
4820 this.update(cx, |this, _| {
4821 this.as_local_mut()
4822 .unwrap()
4823 .last_workspace_edits_by_language_server
4824 .remove(&lang_server.server_id());
4825 })?;
4826
4827 let _result = lang_server
4828 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4829 command: command.command.clone(),
4830 arguments: command.arguments.clone().unwrap_or_default(),
4831 ..lsp::ExecuteCommandParams::default()
4832 })
4833 .await.into_response()
4834 .context("execute command")?;
4835
4836 return this.update(cx, |this, _| {
4837 this.as_local_mut()
4838 .unwrap()
4839 .last_workspace_edits_by_language_server
4840 .remove(&lang_server.server_id())
4841 .unwrap_or_default()
4842 });
4843 } else {
4844 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4845 }
4846 }
4847
4848 Ok(ProjectTransaction::default())
4849 })
4850 } else {
4851 Task::ready(Err(anyhow!("no upstream client and not local")))
4852 }
4853 }
4854
4855 pub fn apply_code_action_kind(
4856 &mut self,
4857 buffers: HashSet<Entity<Buffer>>,
4858 kind: CodeActionKind,
4859 push_to_history: bool,
4860 cx: &mut Context<Self>,
4861 ) -> Task<anyhow::Result<ProjectTransaction>> {
4862 if let Some(_) = self.as_local() {
4863 cx.spawn(async move |lsp_store, cx| {
4864 let buffers = buffers.into_iter().collect::<Vec<_>>();
4865 let result = LocalLspStore::execute_code_action_kind_locally(
4866 lsp_store.clone(),
4867 buffers,
4868 kind,
4869 push_to_history,
4870 cx,
4871 )
4872 .await;
4873 lsp_store.update(cx, |lsp_store, _| {
4874 lsp_store.update_last_formatting_failure(&result);
4875 })?;
4876 result
4877 })
4878 } else if let Some((client, project_id)) = self.upstream_client() {
4879 let buffer_store = self.buffer_store();
4880 cx.spawn(async move |lsp_store, cx| {
4881 let result = client
4882 .request(proto::ApplyCodeActionKind {
4883 project_id,
4884 kind: kind.as_str().to_owned(),
4885 buffer_ids: buffers
4886 .iter()
4887 .map(|buffer| {
4888 buffer.read_with(cx, |buffer, _| buffer.remote_id().into())
4889 })
4890 .collect::<Result<_>>()?,
4891 })
4892 .await
4893 .and_then(|result| result.transaction.context("missing transaction"));
4894 lsp_store.update(cx, |lsp_store, _| {
4895 lsp_store.update_last_formatting_failure(&result);
4896 })?;
4897
4898 let transaction_response = result?;
4899 buffer_store
4900 .update(cx, |buffer_store, cx| {
4901 buffer_store.deserialize_project_transaction(
4902 transaction_response,
4903 push_to_history,
4904 cx,
4905 )
4906 })?
4907 .await
4908 })
4909 } else {
4910 Task::ready(Ok(ProjectTransaction::default()))
4911 }
4912 }
4913
4914 pub fn resolve_inlay_hint(
4915 &self,
4916 hint: InlayHint,
4917 buffer_handle: Entity<Buffer>,
4918 server_id: LanguageServerId,
4919 cx: &mut Context<Self>,
4920 ) -> Task<anyhow::Result<InlayHint>> {
4921 if let Some((upstream_client, project_id)) = self.upstream_client() {
4922 let request = proto::ResolveInlayHint {
4923 project_id,
4924 buffer_id: buffer_handle.read(cx).remote_id().into(),
4925 language_server_id: server_id.0 as u64,
4926 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4927 };
4928 cx.spawn(async move |_, _| {
4929 let response = upstream_client
4930 .request(request)
4931 .await
4932 .context("inlay hints proto request")?;
4933 match response.hint {
4934 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4935 .context("inlay hints proto resolve response conversion"),
4936 None => Ok(hint),
4937 }
4938 })
4939 } else {
4940 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4941 self.language_server_for_local_buffer(buffer, server_id, cx)
4942 .map(|(_, server)| server.clone())
4943 }) else {
4944 return Task::ready(Ok(hint));
4945 };
4946 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4947 return Task::ready(Ok(hint));
4948 }
4949 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4950 cx.spawn(async move |_, cx| {
4951 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4952 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4953 );
4954 let resolved_hint = resolve_task
4955 .await
4956 .into_response()
4957 .context("inlay hint resolve LSP request")?;
4958 let resolved_hint = InlayHints::lsp_to_project_hint(
4959 resolved_hint,
4960 &buffer_handle,
4961 server_id,
4962 ResolveState::Resolved,
4963 false,
4964 cx,
4965 )
4966 .await?;
4967 Ok(resolved_hint)
4968 })
4969 }
4970 }
4971
4972 pub fn resolve_color_presentation(
4973 &mut self,
4974 mut color: DocumentColor,
4975 buffer: Entity<Buffer>,
4976 server_id: LanguageServerId,
4977 cx: &mut Context<Self>,
4978 ) -> Task<Result<DocumentColor>> {
4979 if color.resolved {
4980 return Task::ready(Ok(color));
4981 }
4982
4983 if let Some((upstream_client, project_id)) = self.upstream_client() {
4984 let start = color.lsp_range.start;
4985 let end = color.lsp_range.end;
4986 let request = proto::GetColorPresentation {
4987 project_id,
4988 server_id: server_id.to_proto(),
4989 buffer_id: buffer.read(cx).remote_id().into(),
4990 color: Some(proto::ColorInformation {
4991 red: color.color.red,
4992 green: color.color.green,
4993 blue: color.color.blue,
4994 alpha: color.color.alpha,
4995 lsp_range_start: Some(proto::PointUtf16 {
4996 row: start.line,
4997 column: start.character,
4998 }),
4999 lsp_range_end: Some(proto::PointUtf16 {
5000 row: end.line,
5001 column: end.character,
5002 }),
5003 }),
5004 };
5005 cx.background_spawn(async move {
5006 let response = upstream_client
5007 .request(request)
5008 .await
5009 .context("color presentation proto request")?;
5010 color.resolved = true;
5011 color.color_presentations = response
5012 .presentations
5013 .into_iter()
5014 .map(|presentation| ColorPresentation {
5015 label: presentation.label,
5016 text_edit: presentation.text_edit.and_then(deserialize_lsp_edit),
5017 additional_text_edits: presentation
5018 .additional_text_edits
5019 .into_iter()
5020 .filter_map(deserialize_lsp_edit)
5021 .collect(),
5022 })
5023 .collect();
5024 Ok(color)
5025 })
5026 } else {
5027 let path = match buffer
5028 .update(cx, |buffer, cx| {
5029 Some(File::from_dyn(buffer.file())?.abs_path(cx))
5030 })
5031 .context("buffer with the missing path")
5032 {
5033 Ok(path) => path,
5034 Err(e) => return Task::ready(Err(e)),
5035 };
5036 let Some(lang_server) = buffer.update(cx, |buffer, cx| {
5037 self.language_server_for_local_buffer(buffer, server_id, cx)
5038 .map(|(_, server)| server.clone())
5039 }) else {
5040 return Task::ready(Ok(color));
5041 };
5042 cx.background_spawn(async move {
5043 let resolve_task = lang_server.request::<lsp::request::ColorPresentationRequest>(
5044 lsp::ColorPresentationParams {
5045 text_document: make_text_document_identifier(&path)?,
5046 color: color.color,
5047 range: color.lsp_range,
5048 work_done_progress_params: Default::default(),
5049 partial_result_params: Default::default(),
5050 },
5051 );
5052 color.color_presentations = resolve_task
5053 .await
5054 .into_response()
5055 .context("color presentation resolve LSP request")?
5056 .into_iter()
5057 .map(|presentation| ColorPresentation {
5058 label: presentation.label,
5059 text_edit: presentation.text_edit,
5060 additional_text_edits: presentation
5061 .additional_text_edits
5062 .unwrap_or_default(),
5063 })
5064 .collect();
5065 color.resolved = true;
5066 Ok(color)
5067 })
5068 }
5069 }
5070
5071 pub(crate) fn linked_edit(
5072 &mut self,
5073 buffer: &Entity<Buffer>,
5074 position: Anchor,
5075 cx: &mut Context<Self>,
5076 ) -> Task<Result<Vec<Range<Anchor>>>> {
5077 let snapshot = buffer.read(cx).snapshot();
5078 let scope = snapshot.language_scope_at(position);
5079 let Some(server_id) = self
5080 .as_local()
5081 .and_then(|local| {
5082 buffer.update(cx, |buffer, cx| {
5083 local
5084 .language_servers_for_buffer(buffer, cx)
5085 .filter(|(_, server)| {
5086 server
5087 .capabilities()
5088 .linked_editing_range_provider
5089 .is_some()
5090 })
5091 .filter(|(adapter, _)| {
5092 scope
5093 .as_ref()
5094 .map(|scope| scope.language_allowed(&adapter.name))
5095 .unwrap_or(true)
5096 })
5097 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
5098 .next()
5099 })
5100 })
5101 .or_else(|| {
5102 self.upstream_client()
5103 .is_some()
5104 .then_some(LanguageServerToQuery::FirstCapable)
5105 })
5106 .filter(|_| {
5107 maybe!({
5108 let language = buffer.read(cx).language_at(position)?;
5109 Some(
5110 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
5111 .linked_edits,
5112 )
5113 }) == Some(true)
5114 })
5115 else {
5116 return Task::ready(Ok(vec![]));
5117 };
5118
5119 self.request_lsp(
5120 buffer.clone(),
5121 server_id,
5122 LinkedEditingRange { position },
5123 cx,
5124 )
5125 }
5126
5127 fn apply_on_type_formatting(
5128 &mut self,
5129 buffer: Entity<Buffer>,
5130 position: Anchor,
5131 trigger: String,
5132 cx: &mut Context<Self>,
5133 ) -> Task<Result<Option<Transaction>>> {
5134 if let Some((client, project_id)) = self.upstream_client() {
5135 let request = proto::OnTypeFormatting {
5136 project_id,
5137 buffer_id: buffer.read(cx).remote_id().into(),
5138 position: Some(serialize_anchor(&position)),
5139 trigger,
5140 version: serialize_version(&buffer.read(cx).version()),
5141 };
5142 cx.spawn(async move |_, _| {
5143 client
5144 .request(request)
5145 .await?
5146 .transaction
5147 .map(language::proto::deserialize_transaction)
5148 .transpose()
5149 })
5150 } else if let Some(local) = self.as_local_mut() {
5151 let buffer_id = buffer.read(cx).remote_id();
5152 local.buffers_being_formatted.insert(buffer_id);
5153 cx.spawn(async move |this, cx| {
5154 let _cleanup = defer({
5155 let this = this.clone();
5156 let mut cx = cx.clone();
5157 move || {
5158 this.update(&mut cx, |this, _| {
5159 if let Some(local) = this.as_local_mut() {
5160 local.buffers_being_formatted.remove(&buffer_id);
5161 }
5162 })
5163 .ok();
5164 }
5165 });
5166
5167 buffer
5168 .update(cx, |buffer, _| {
5169 buffer.wait_for_edits(Some(position.timestamp))
5170 })?
5171 .await?;
5172 this.update(cx, |this, cx| {
5173 let position = position.to_point_utf16(buffer.read(cx));
5174 this.on_type_format(buffer, position, trigger, false, cx)
5175 })?
5176 .await
5177 })
5178 } else {
5179 Task::ready(Err(anyhow!("No upstream client or local language server")))
5180 }
5181 }
5182
5183 pub fn on_type_format<T: ToPointUtf16>(
5184 &mut self,
5185 buffer: Entity<Buffer>,
5186 position: T,
5187 trigger: String,
5188 push_to_history: bool,
5189 cx: &mut Context<Self>,
5190 ) -> Task<Result<Option<Transaction>>> {
5191 let position = position.to_point_utf16(buffer.read(cx));
5192 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5193 }
5194
5195 fn on_type_format_impl(
5196 &mut self,
5197 buffer: Entity<Buffer>,
5198 position: PointUtf16,
5199 trigger: String,
5200 push_to_history: bool,
5201 cx: &mut Context<Self>,
5202 ) -> Task<Result<Option<Transaction>>> {
5203 let options = buffer.update(cx, |buffer, cx| {
5204 lsp_command::lsp_formatting_options(
5205 language_settings(
5206 buffer.language_at(position).map(|l| l.name()),
5207 buffer.file(),
5208 cx,
5209 )
5210 .as_ref(),
5211 )
5212 });
5213
5214 cx.spawn(async move |this, cx| {
5215 if let Some(waiter) =
5216 buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())?
5217 {
5218 waiter.await?;
5219 }
5220 cx.update(|cx| {
5221 this.update(cx, |this, cx| {
5222 this.request_lsp(
5223 buffer.clone(),
5224 LanguageServerToQuery::FirstCapable,
5225 OnTypeFormatting {
5226 position,
5227 trigger,
5228 options,
5229 push_to_history,
5230 },
5231 cx,
5232 )
5233 })
5234 })??
5235 .await
5236 })
5237 }
5238
5239 pub fn code_actions(
5240 &mut self,
5241 buffer_handle: &Entity<Buffer>,
5242 range: Range<Anchor>,
5243 kinds: Option<Vec<CodeActionKind>>,
5244 cx: &mut Context<Self>,
5245 ) -> Task<Result<Vec<CodeAction>>> {
5246 if let Some((upstream_client, project_id)) = self.upstream_client() {
5247 let request_task = upstream_client.request(proto::MultiLspQuery {
5248 buffer_id: buffer_handle.read(cx).remote_id().into(),
5249 version: serialize_version(&buffer_handle.read(cx).version()),
5250 project_id,
5251 strategy: Some(proto::multi_lsp_query::Strategy::All(
5252 proto::AllLanguageServers {},
5253 )),
5254 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
5255 GetCodeActions {
5256 range: range.clone(),
5257 kinds: kinds.clone(),
5258 }
5259 .to_proto(project_id, buffer_handle.read(cx)),
5260 )),
5261 });
5262 let buffer = buffer_handle.clone();
5263 cx.spawn(async move |weak_project, cx| {
5264 let Some(project) = weak_project.upgrade() else {
5265 return Ok(Vec::new());
5266 };
5267 let responses = request_task.await?.responses;
5268 let actions = join_all(
5269 responses
5270 .into_iter()
5271 .filter_map(|lsp_response| match lsp_response.response? {
5272 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
5273 Some(response)
5274 }
5275 unexpected => {
5276 debug_panic!("Unexpected response: {unexpected:?}");
5277 None
5278 }
5279 })
5280 .map(|code_actions_response| {
5281 GetCodeActions {
5282 range: range.clone(),
5283 kinds: kinds.clone(),
5284 }
5285 .response_from_proto(
5286 code_actions_response,
5287 project.clone(),
5288 buffer.clone(),
5289 cx.clone(),
5290 )
5291 }),
5292 )
5293 .await;
5294
5295 Ok(actions
5296 .into_iter()
5297 .collect::<Result<Vec<Vec<_>>>>()?
5298 .into_iter()
5299 .flatten()
5300 .collect())
5301 })
5302 } else {
5303 let all_actions_task = self.request_multiple_lsp_locally(
5304 buffer_handle,
5305 Some(range.start),
5306 GetCodeActions {
5307 range: range.clone(),
5308 kinds: kinds.clone(),
5309 },
5310 cx,
5311 );
5312 cx.spawn(async move |_, _| {
5313 Ok(all_actions_task
5314 .await
5315 .into_iter()
5316 .flat_map(|(_, actions)| actions)
5317 .collect())
5318 })
5319 }
5320 }
5321
5322 pub fn code_lens(
5323 &mut self,
5324 buffer_handle: &Entity<Buffer>,
5325 cx: &mut Context<Self>,
5326 ) -> Task<Result<Vec<CodeAction>>> {
5327 if let Some((upstream_client, project_id)) = self.upstream_client() {
5328 let request_task = upstream_client.request(proto::MultiLspQuery {
5329 buffer_id: buffer_handle.read(cx).remote_id().into(),
5330 version: serialize_version(&buffer_handle.read(cx).version()),
5331 project_id,
5332 strategy: Some(proto::multi_lsp_query::Strategy::All(
5333 proto::AllLanguageServers {},
5334 )),
5335 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
5336 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
5337 )),
5338 });
5339 let buffer = buffer_handle.clone();
5340 cx.spawn(async move |weak_project, cx| {
5341 let Some(project) = weak_project.upgrade() else {
5342 return Ok(Vec::new());
5343 };
5344 let responses = request_task.await?.responses;
5345 let code_lens = join_all(
5346 responses
5347 .into_iter()
5348 .filter_map(|lsp_response| match lsp_response.response? {
5349 proto::lsp_response::Response::GetCodeLensResponse(response) => {
5350 Some(response)
5351 }
5352 unexpected => {
5353 debug_panic!("Unexpected response: {unexpected:?}");
5354 None
5355 }
5356 })
5357 .map(|code_lens_response| {
5358 GetCodeLens.response_from_proto(
5359 code_lens_response,
5360 project.clone(),
5361 buffer.clone(),
5362 cx.clone(),
5363 )
5364 }),
5365 )
5366 .await;
5367
5368 Ok(code_lens
5369 .into_iter()
5370 .collect::<Result<Vec<Vec<_>>>>()?
5371 .into_iter()
5372 .flatten()
5373 .collect())
5374 })
5375 } else {
5376 let code_lens_task =
5377 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
5378 cx.spawn(async move |_, _| {
5379 Ok(code_lens_task
5380 .await
5381 .into_iter()
5382 .flat_map(|(_, code_lens)| code_lens)
5383 .collect())
5384 })
5385 }
5386 }
5387
5388 #[inline(never)]
5389 pub fn completions(
5390 &self,
5391 buffer: &Entity<Buffer>,
5392 position: PointUtf16,
5393 context: CompletionContext,
5394 cx: &mut Context<Self>,
5395 ) -> Task<Result<Vec<CompletionResponse>>> {
5396 let language_registry = self.languages.clone();
5397
5398 if let Some((upstream_client, project_id)) = self.upstream_client() {
5399 let task = self.send_lsp_proto_request(
5400 buffer.clone(),
5401 upstream_client,
5402 project_id,
5403 GetCompletions { position, context },
5404 cx,
5405 );
5406 let language = buffer.read(cx).language().cloned();
5407
5408 // In the future, we should provide project guests with the names of LSP adapters,
5409 // so that they can use the correct LSP adapter when computing labels. For now,
5410 // guests just use the first LSP adapter associated with the buffer's language.
5411 let lsp_adapter = language.as_ref().and_then(|language| {
5412 language_registry
5413 .lsp_adapters(&language.name())
5414 .first()
5415 .cloned()
5416 });
5417
5418 cx.foreground_executor().spawn(async move {
5419 let completion_response = task.await?;
5420 let completions = populate_labels_for_completions(
5421 completion_response.completions,
5422 language,
5423 lsp_adapter,
5424 )
5425 .await;
5426 Ok(vec![CompletionResponse {
5427 completions,
5428 is_incomplete: completion_response.is_incomplete,
5429 }])
5430 })
5431 } else if let Some(local) = self.as_local() {
5432 let snapshot = buffer.read(cx).snapshot();
5433 let offset = position.to_offset(&snapshot);
5434 let scope = snapshot.language_scope_at(offset);
5435 let language = snapshot.language().cloned();
5436 let completion_settings = language_settings(
5437 language.as_ref().map(|language| language.name()),
5438 buffer.read(cx).file(),
5439 cx,
5440 )
5441 .completions;
5442 if !completion_settings.lsp {
5443 return Task::ready(Ok(Vec::new()));
5444 }
5445
5446 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5447 local
5448 .language_servers_for_buffer(buffer, cx)
5449 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5450 .filter(|(adapter, _)| {
5451 scope
5452 .as_ref()
5453 .map(|scope| scope.language_allowed(&adapter.name))
5454 .unwrap_or(true)
5455 })
5456 .map(|(_, server)| server.server_id())
5457 .collect()
5458 });
5459
5460 let buffer = buffer.clone();
5461 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5462 let lsp_timeout = if lsp_timeout > 0 {
5463 Some(Duration::from_millis(lsp_timeout))
5464 } else {
5465 None
5466 };
5467 cx.spawn(async move |this, cx| {
5468 let mut tasks = Vec::with_capacity(server_ids.len());
5469 this.update(cx, |lsp_store, cx| {
5470 for server_id in server_ids {
5471 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5472 let lsp_timeout = lsp_timeout
5473 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5474 let mut timeout = cx.background_spawn(async move {
5475 match lsp_timeout {
5476 Some(lsp_timeout) => {
5477 lsp_timeout.await;
5478 true
5479 },
5480 None => false,
5481 }
5482 }).fuse();
5483 let mut lsp_request = lsp_store.request_lsp(
5484 buffer.clone(),
5485 LanguageServerToQuery::Other(server_id),
5486 GetCompletions {
5487 position,
5488 context: context.clone(),
5489 },
5490 cx,
5491 ).fuse();
5492 let new_task = cx.background_spawn(async move {
5493 select_biased! {
5494 response = lsp_request => anyhow::Ok(Some(response?)),
5495 timeout_happened = timeout => {
5496 if timeout_happened {
5497 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5498 Ok(None)
5499 } else {
5500 let completions = lsp_request.await?;
5501 Ok(Some(completions))
5502 }
5503 },
5504 }
5505 });
5506 tasks.push((lsp_adapter, new_task));
5507 }
5508 })?;
5509
5510 let futures = tasks.into_iter().map(async |(lsp_adapter, task)| {
5511 let completion_response = task.await.ok()??;
5512 let completions = populate_labels_for_completions(
5513 completion_response.completions,
5514 language.clone(),
5515 lsp_adapter,
5516 )
5517 .await;
5518 Some(CompletionResponse {
5519 completions,
5520 is_incomplete: completion_response.is_incomplete,
5521 })
5522 });
5523
5524 let responses: Vec<Option<CompletionResponse>> = join_all(futures).await;
5525
5526 Ok(responses.into_iter().flatten().collect())
5527 })
5528 } else {
5529 Task::ready(Err(anyhow!("No upstream client or local language server")))
5530 }
5531 }
5532
5533 pub fn resolve_completions(
5534 &self,
5535 buffer: Entity<Buffer>,
5536 completion_indices: Vec<usize>,
5537 completions: Rc<RefCell<Box<[Completion]>>>,
5538 cx: &mut Context<Self>,
5539 ) -> Task<Result<bool>> {
5540 let client = self.upstream_client();
5541
5542 let buffer_id = buffer.read(cx).remote_id();
5543 let buffer_snapshot = buffer.read(cx).snapshot();
5544
5545 cx.spawn(async move |this, cx| {
5546 let mut did_resolve = false;
5547 if let Some((client, project_id)) = client {
5548 for completion_index in completion_indices {
5549 let server_id = {
5550 let completion = &completions.borrow()[completion_index];
5551 completion.source.server_id()
5552 };
5553 if let Some(server_id) = server_id {
5554 if Self::resolve_completion_remote(
5555 project_id,
5556 server_id,
5557 buffer_id,
5558 completions.clone(),
5559 completion_index,
5560 client.clone(),
5561 )
5562 .await
5563 .log_err()
5564 .is_some()
5565 {
5566 did_resolve = true;
5567 }
5568 } else {
5569 resolve_word_completion(
5570 &buffer_snapshot,
5571 &mut completions.borrow_mut()[completion_index],
5572 );
5573 }
5574 }
5575 } else {
5576 for completion_index in completion_indices {
5577 let server_id = {
5578 let completion = &completions.borrow()[completion_index];
5579 completion.source.server_id()
5580 };
5581 if let Some(server_id) = server_id {
5582 let server_and_adapter = this
5583 .read_with(cx, |lsp_store, _| {
5584 let server = lsp_store.language_server_for_id(server_id)?;
5585 let adapter =
5586 lsp_store.language_server_adapter_for_id(server.server_id())?;
5587 Some((server, adapter))
5588 })
5589 .ok()
5590 .flatten();
5591 let Some((server, adapter)) = server_and_adapter else {
5592 continue;
5593 };
5594
5595 let resolved = Self::resolve_completion_local(
5596 server,
5597 &buffer_snapshot,
5598 completions.clone(),
5599 completion_index,
5600 )
5601 .await
5602 .log_err()
5603 .is_some();
5604 if resolved {
5605 Self::regenerate_completion_labels(
5606 adapter,
5607 &buffer_snapshot,
5608 completions.clone(),
5609 completion_index,
5610 )
5611 .await
5612 .log_err();
5613 did_resolve = true;
5614 }
5615 } else {
5616 resolve_word_completion(
5617 &buffer_snapshot,
5618 &mut completions.borrow_mut()[completion_index],
5619 );
5620 }
5621 }
5622 }
5623
5624 Ok(did_resolve)
5625 })
5626 }
5627
5628 async fn resolve_completion_local(
5629 server: Arc<lsp::LanguageServer>,
5630 snapshot: &BufferSnapshot,
5631 completions: Rc<RefCell<Box<[Completion]>>>,
5632 completion_index: usize,
5633 ) -> Result<()> {
5634 let server_id = server.server_id();
5635 let can_resolve = server
5636 .capabilities()
5637 .completion_provider
5638 .as_ref()
5639 .and_then(|options| options.resolve_provider)
5640 .unwrap_or(false);
5641 if !can_resolve {
5642 return Ok(());
5643 }
5644
5645 let request = {
5646 let completion = &completions.borrow()[completion_index];
5647 match &completion.source {
5648 CompletionSource::Lsp {
5649 lsp_completion,
5650 resolved,
5651 server_id: completion_server_id,
5652 ..
5653 } => {
5654 if *resolved {
5655 return Ok(());
5656 }
5657 anyhow::ensure!(
5658 server_id == *completion_server_id,
5659 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5660 );
5661 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5662 }
5663 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5664 return Ok(());
5665 }
5666 }
5667 };
5668 let resolved_completion = request
5669 .await
5670 .into_response()
5671 .context("resolve completion")?;
5672
5673 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5674 // Technically we don't have to parse the whole `text_edit`, since the only
5675 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5676 // is `typescript-language-server` and they only update `text_edit.new_text`.
5677 // But we should not rely on that.
5678 let edit = parse_completion_text_edit(text_edit, snapshot);
5679
5680 if let Some(mut parsed_edit) = edit {
5681 LineEnding::normalize(&mut parsed_edit.new_text);
5682
5683 let mut completions = completions.borrow_mut();
5684 let completion = &mut completions[completion_index];
5685
5686 completion.new_text = parsed_edit.new_text;
5687 completion.replace_range = parsed_edit.replace_range;
5688 if let CompletionSource::Lsp { insert_range, .. } = &mut completion.source {
5689 *insert_range = parsed_edit.insert_range;
5690 }
5691 }
5692 }
5693
5694 let mut completions = completions.borrow_mut();
5695 let completion = &mut completions[completion_index];
5696 if let CompletionSource::Lsp {
5697 lsp_completion,
5698 resolved,
5699 server_id: completion_server_id,
5700 ..
5701 } = &mut completion.source
5702 {
5703 if *resolved {
5704 return Ok(());
5705 }
5706 anyhow::ensure!(
5707 server_id == *completion_server_id,
5708 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5709 );
5710 *lsp_completion = Box::new(resolved_completion);
5711 *resolved = true;
5712 }
5713 Ok(())
5714 }
5715
5716 async fn regenerate_completion_labels(
5717 adapter: Arc<CachedLspAdapter>,
5718 snapshot: &BufferSnapshot,
5719 completions: Rc<RefCell<Box<[Completion]>>>,
5720 completion_index: usize,
5721 ) -> Result<()> {
5722 let completion_item = completions.borrow()[completion_index]
5723 .source
5724 .lsp_completion(true)
5725 .map(Cow::into_owned);
5726 if let Some(lsp_documentation) = completion_item
5727 .as_ref()
5728 .and_then(|completion_item| completion_item.documentation.clone())
5729 {
5730 let mut completions = completions.borrow_mut();
5731 let completion = &mut completions[completion_index];
5732 completion.documentation = Some(lsp_documentation.into());
5733 } else {
5734 let mut completions = completions.borrow_mut();
5735 let completion = &mut completions[completion_index];
5736 completion.documentation = Some(CompletionDocumentation::Undocumented);
5737 }
5738
5739 let mut new_label = match completion_item {
5740 Some(completion_item) => {
5741 // 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
5742 // So we have to update the label here anyway...
5743 let language = snapshot.language();
5744 match language {
5745 Some(language) => {
5746 adapter
5747 .labels_for_completions(
5748 std::slice::from_ref(&completion_item),
5749 language,
5750 )
5751 .await?
5752 }
5753 None => Vec::new(),
5754 }
5755 .pop()
5756 .flatten()
5757 .unwrap_or_else(|| {
5758 CodeLabel::fallback_for_completion(
5759 &completion_item,
5760 language.map(|language| language.as_ref()),
5761 )
5762 })
5763 }
5764 None => CodeLabel::plain(
5765 completions.borrow()[completion_index].new_text.clone(),
5766 None,
5767 ),
5768 };
5769 ensure_uniform_list_compatible_label(&mut new_label);
5770
5771 let mut completions = completions.borrow_mut();
5772 let completion = &mut completions[completion_index];
5773 if completion.label.filter_text() == new_label.filter_text() {
5774 completion.label = new_label;
5775 } else {
5776 log::error!(
5777 "Resolved completion changed display label from {} to {}. \
5778 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5779 completion.label.text(),
5780 new_label.text(),
5781 completion.label.filter_text(),
5782 new_label.filter_text()
5783 );
5784 }
5785
5786 Ok(())
5787 }
5788
5789 async fn resolve_completion_remote(
5790 project_id: u64,
5791 server_id: LanguageServerId,
5792 buffer_id: BufferId,
5793 completions: Rc<RefCell<Box<[Completion]>>>,
5794 completion_index: usize,
5795 client: AnyProtoClient,
5796 ) -> Result<()> {
5797 let lsp_completion = {
5798 let completion = &completions.borrow()[completion_index];
5799 match &completion.source {
5800 CompletionSource::Lsp {
5801 lsp_completion,
5802 resolved,
5803 server_id: completion_server_id,
5804 ..
5805 } => {
5806 anyhow::ensure!(
5807 server_id == *completion_server_id,
5808 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5809 );
5810 if *resolved {
5811 return Ok(());
5812 }
5813 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5814 }
5815 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5816 return Ok(());
5817 }
5818 }
5819 };
5820 let request = proto::ResolveCompletionDocumentation {
5821 project_id,
5822 language_server_id: server_id.0 as u64,
5823 lsp_completion,
5824 buffer_id: buffer_id.into(),
5825 };
5826
5827 let response = client
5828 .request(request)
5829 .await
5830 .context("completion documentation resolve proto request")?;
5831 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5832
5833 let documentation = if response.documentation.is_empty() {
5834 CompletionDocumentation::Undocumented
5835 } else if response.documentation_is_markdown {
5836 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5837 } else if response.documentation.lines().count() <= 1 {
5838 CompletionDocumentation::SingleLine(response.documentation.into())
5839 } else {
5840 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5841 };
5842
5843 let mut completions = completions.borrow_mut();
5844 let completion = &mut completions[completion_index];
5845 completion.documentation = Some(documentation);
5846 if let CompletionSource::Lsp {
5847 insert_range,
5848 lsp_completion,
5849 resolved,
5850 server_id: completion_server_id,
5851 lsp_defaults: _,
5852 } = &mut completion.source
5853 {
5854 let completion_insert_range = response
5855 .old_insert_start
5856 .and_then(deserialize_anchor)
5857 .zip(response.old_insert_end.and_then(deserialize_anchor));
5858 *insert_range = completion_insert_range.map(|(start, end)| start..end);
5859
5860 if *resolved {
5861 return Ok(());
5862 }
5863 anyhow::ensure!(
5864 server_id == *completion_server_id,
5865 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5866 );
5867 *lsp_completion = Box::new(resolved_lsp_completion);
5868 *resolved = true;
5869 }
5870
5871 let replace_range = response
5872 .old_replace_start
5873 .and_then(deserialize_anchor)
5874 .zip(response.old_replace_end.and_then(deserialize_anchor));
5875 if let Some((old_replace_start, old_replace_end)) = replace_range {
5876 if !response.new_text.is_empty() {
5877 completion.new_text = response.new_text;
5878 completion.replace_range = old_replace_start..old_replace_end;
5879 }
5880 }
5881
5882 Ok(())
5883 }
5884
5885 pub fn apply_additional_edits_for_completion(
5886 &self,
5887 buffer_handle: Entity<Buffer>,
5888 completions: Rc<RefCell<Box<[Completion]>>>,
5889 completion_index: usize,
5890 push_to_history: bool,
5891 cx: &mut Context<Self>,
5892 ) -> Task<Result<Option<Transaction>>> {
5893 if let Some((client, project_id)) = self.upstream_client() {
5894 let buffer = buffer_handle.read(cx);
5895 let buffer_id = buffer.remote_id();
5896 cx.spawn(async move |_, cx| {
5897 let request = {
5898 let completion = completions.borrow()[completion_index].clone();
5899 proto::ApplyCompletionAdditionalEdits {
5900 project_id,
5901 buffer_id: buffer_id.into(),
5902 completion: Some(Self::serialize_completion(&CoreCompletion {
5903 replace_range: completion.replace_range,
5904 new_text: completion.new_text,
5905 source: completion.source,
5906 })),
5907 }
5908 };
5909
5910 if let Some(transaction) = client.request(request).await?.transaction {
5911 let transaction = language::proto::deserialize_transaction(transaction)?;
5912 buffer_handle
5913 .update(cx, |buffer, _| {
5914 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5915 })?
5916 .await?;
5917 if push_to_history {
5918 buffer_handle.update(cx, |buffer, _| {
5919 buffer.push_transaction(transaction.clone(), Instant::now());
5920 buffer.finalize_last_transaction();
5921 })?;
5922 }
5923 Ok(Some(transaction))
5924 } else {
5925 Ok(None)
5926 }
5927 })
5928 } else {
5929 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5930 let completion = &completions.borrow()[completion_index];
5931 let server_id = completion.source.server_id()?;
5932 Some(
5933 self.language_server_for_local_buffer(buffer, server_id, cx)?
5934 .1
5935 .clone(),
5936 )
5937 }) else {
5938 return Task::ready(Ok(None));
5939 };
5940 let snapshot = buffer_handle.read(&cx).snapshot();
5941
5942 cx.spawn(async move |this, cx| {
5943 Self::resolve_completion_local(
5944 server.clone(),
5945 &snapshot,
5946 completions.clone(),
5947 completion_index,
5948 )
5949 .await
5950 .context("resolving completion")?;
5951 let completion = completions.borrow()[completion_index].clone();
5952 let additional_text_edits = completion
5953 .source
5954 .lsp_completion(true)
5955 .as_ref()
5956 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5957 if let Some(edits) = additional_text_edits {
5958 let edits = this
5959 .update(cx, |this, cx| {
5960 this.as_local_mut().unwrap().edits_from_lsp(
5961 &buffer_handle,
5962 edits,
5963 server.server_id(),
5964 None,
5965 cx,
5966 )
5967 })?
5968 .await?;
5969
5970 buffer_handle.update(cx, |buffer, cx| {
5971 buffer.finalize_last_transaction();
5972 buffer.start_transaction();
5973
5974 for (range, text) in edits {
5975 let primary = &completion.replace_range;
5976 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5977 && primary.end.cmp(&range.start, buffer).is_ge();
5978 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5979 && range.end.cmp(&primary.end, buffer).is_ge();
5980
5981 //Skip additional edits which overlap with the primary completion edit
5982 //https://github.com/zed-industries/zed/pull/1871
5983 if !start_within && !end_within {
5984 buffer.edit([(range, text)], None, cx);
5985 }
5986 }
5987
5988 let transaction = if buffer.end_transaction(cx).is_some() {
5989 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5990 if !push_to_history {
5991 buffer.forget_transaction(transaction.id);
5992 }
5993 Some(transaction)
5994 } else {
5995 None
5996 };
5997 Ok(transaction)
5998 })?
5999 } else {
6000 Ok(None)
6001 }
6002 })
6003 }
6004 }
6005
6006 pub fn pull_diagnostics(
6007 &mut self,
6008 buffer_handle: Entity<Buffer>,
6009 cx: &mut Context<Self>,
6010 ) -> Task<Result<Vec<LspPullDiagnostics>>> {
6011 let buffer = buffer_handle.read(cx);
6012 let buffer_id = buffer.remote_id();
6013
6014 if let Some((client, upstream_project_id)) = self.upstream_client() {
6015 let request_task = client.request(proto::MultiLspQuery {
6016 buffer_id: buffer_id.to_proto(),
6017 version: serialize_version(&buffer_handle.read(cx).version()),
6018 project_id: upstream_project_id,
6019 strategy: Some(proto::multi_lsp_query::Strategy::All(
6020 proto::AllLanguageServers {},
6021 )),
6022 request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
6023 proto::GetDocumentDiagnostics {
6024 project_id: upstream_project_id,
6025 buffer_id: buffer_id.to_proto(),
6026 version: serialize_version(&buffer_handle.read(cx).version()),
6027 },
6028 )),
6029 });
6030 cx.background_spawn(async move {
6031 Ok(request_task
6032 .await?
6033 .responses
6034 .into_iter()
6035 .filter_map(|lsp_response| match lsp_response.response? {
6036 proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
6037 Some(response)
6038 }
6039 unexpected => {
6040 debug_panic!("Unexpected response: {unexpected:?}");
6041 None
6042 }
6043 })
6044 .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
6045 .collect())
6046 })
6047 } else {
6048 let server_ids = buffer_handle.update(cx, |buffer, cx| {
6049 self.language_servers_for_local_buffer(buffer, cx)
6050 .map(|(_, server)| server.server_id())
6051 .collect::<Vec<_>>()
6052 });
6053 let pull_diagnostics = server_ids
6054 .into_iter()
6055 .map(|server_id| {
6056 let result_id = self.result_id(server_id, buffer_id, cx);
6057 self.request_lsp(
6058 buffer_handle.clone(),
6059 LanguageServerToQuery::Other(server_id),
6060 GetDocumentDiagnostics {
6061 previous_result_id: result_id,
6062 },
6063 cx,
6064 )
6065 })
6066 .collect::<Vec<_>>();
6067
6068 cx.background_spawn(async move {
6069 let mut responses = Vec::new();
6070 for diagnostics in join_all(pull_diagnostics).await {
6071 responses.extend(diagnostics?);
6072 }
6073 Ok(responses)
6074 })
6075 }
6076 }
6077
6078 pub fn inlay_hints(
6079 &mut self,
6080 buffer_handle: Entity<Buffer>,
6081 range: Range<Anchor>,
6082 cx: &mut Context<Self>,
6083 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6084 let buffer = buffer_handle.read(cx);
6085 let range_start = range.start;
6086 let range_end = range.end;
6087 let buffer_id = buffer.remote_id().into();
6088 let lsp_request = InlayHints { range };
6089
6090 if let Some((client, project_id)) = self.upstream_client() {
6091 let request = proto::InlayHints {
6092 project_id,
6093 buffer_id,
6094 start: Some(serialize_anchor(&range_start)),
6095 end: Some(serialize_anchor(&range_end)),
6096 version: serialize_version(&buffer_handle.read(cx).version()),
6097 };
6098 cx.spawn(async move |project, cx| {
6099 let response = client
6100 .request(request)
6101 .await
6102 .context("inlay hints proto request")?;
6103 LspCommand::response_from_proto(
6104 lsp_request,
6105 response,
6106 project.upgrade().context("No project")?,
6107 buffer_handle.clone(),
6108 cx.clone(),
6109 )
6110 .await
6111 .context("inlay hints proto response conversion")
6112 })
6113 } else {
6114 let lsp_request_task = self.request_lsp(
6115 buffer_handle.clone(),
6116 LanguageServerToQuery::FirstCapable,
6117 lsp_request,
6118 cx,
6119 );
6120 cx.spawn(async move |_, cx| {
6121 buffer_handle
6122 .update(cx, |buffer, _| {
6123 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6124 })?
6125 .await
6126 .context("waiting for inlay hint request range edits")?;
6127 lsp_request_task.await.context("inlay hints LSP request")
6128 })
6129 }
6130 }
6131
6132 pub fn pull_diagnostics_for_buffer(
6133 &mut self,
6134 buffer: Entity<Buffer>,
6135 cx: &mut Context<Self>,
6136 ) -> Task<anyhow::Result<()>> {
6137 let buffer_id = buffer.read(cx).remote_id();
6138 let diagnostics = self.pull_diagnostics(buffer, cx);
6139 cx.spawn(async move |lsp_store, cx| {
6140 let diagnostics = diagnostics.await.context("pulling diagnostics")?;
6141 lsp_store.update(cx, |lsp_store, cx| {
6142 if lsp_store.as_local().is_none() {
6143 return;
6144 }
6145
6146 for diagnostics_set in diagnostics {
6147 let LspPullDiagnostics::Response {
6148 server_id,
6149 uri,
6150 diagnostics,
6151 } = diagnostics_set
6152 else {
6153 continue;
6154 };
6155
6156 let adapter = lsp_store.language_server_adapter_for_id(server_id);
6157 let disk_based_sources = adapter
6158 .as_ref()
6159 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
6160 .unwrap_or(&[]);
6161 match diagnostics {
6162 PulledDiagnostics::Unchanged { result_id } => {
6163 lsp_store
6164 .merge_diagnostics(
6165 server_id,
6166 lsp::PublishDiagnosticsParams {
6167 uri: uri.clone(),
6168 diagnostics: Vec::new(),
6169 version: None,
6170 },
6171 Some(result_id),
6172 DiagnosticSourceKind::Pulled,
6173 disk_based_sources,
6174 |_, _, _| true,
6175 cx,
6176 )
6177 .log_err();
6178 }
6179 PulledDiagnostics::Changed {
6180 diagnostics,
6181 result_id,
6182 } => {
6183 lsp_store
6184 .merge_diagnostics(
6185 server_id,
6186 lsp::PublishDiagnosticsParams {
6187 uri: uri.clone(),
6188 diagnostics,
6189 version: None,
6190 },
6191 result_id,
6192 DiagnosticSourceKind::Pulled,
6193 disk_based_sources,
6194 |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
6195 DiagnosticSourceKind::Pulled => {
6196 buffer.remote_id() != buffer_id
6197 }
6198 DiagnosticSourceKind::Other
6199 | DiagnosticSourceKind::Pushed => true,
6200 },
6201 cx,
6202 )
6203 .log_err();
6204 }
6205 }
6206 }
6207 })
6208 })
6209 }
6210
6211 pub fn document_colors(
6212 &mut self,
6213 for_server_id: Option<LanguageServerId>,
6214 buffer: Entity<Buffer>,
6215 cx: &mut Context<Self>,
6216 ) -> Option<DocumentColorTask> {
6217 let buffer_mtime = buffer.read(cx).saved_mtime()?;
6218 let buffer_version = buffer.read(cx).version();
6219 let abs_path = File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
6220
6221 let mut received_colors_data = false;
6222 let buffer_lsp_data = self
6223 .lsp_data
6224 .as_ref()
6225 .into_iter()
6226 .filter(|lsp_data| {
6227 if buffer_mtime == lsp_data.mtime {
6228 lsp_data
6229 .last_version_queried
6230 .get(&abs_path)
6231 .is_none_or(|version_queried| {
6232 !buffer_version.changed_since(version_queried)
6233 })
6234 } else {
6235 !buffer_mtime.bad_is_greater_than(lsp_data.mtime)
6236 }
6237 })
6238 .flat_map(|lsp_data| lsp_data.buffer_lsp_data.values())
6239 .filter_map(|buffer_data| buffer_data.get(&abs_path))
6240 .filter_map(|buffer_data| {
6241 let colors = buffer_data.colors.as_ref()?;
6242 received_colors_data = true;
6243 Some(colors)
6244 })
6245 .flatten()
6246 .cloned()
6247 .collect::<HashSet<_>>();
6248
6249 if buffer_lsp_data.is_empty() || for_server_id.is_some() {
6250 if received_colors_data && for_server_id.is_none() {
6251 return None;
6252 }
6253
6254 let mut outdated_lsp_data = false;
6255 if self.lsp_data.is_none()
6256 || self.lsp_data.as_ref().is_some_and(|lsp_data| {
6257 if buffer_mtime == lsp_data.mtime {
6258 lsp_data
6259 .last_version_queried
6260 .get(&abs_path)
6261 .is_none_or(|version_queried| {
6262 buffer_version.changed_since(version_queried)
6263 })
6264 } else {
6265 buffer_mtime.bad_is_greater_than(lsp_data.mtime)
6266 }
6267 })
6268 {
6269 self.lsp_data = Some(LspData {
6270 mtime: buffer_mtime,
6271 buffer_lsp_data: HashMap::default(),
6272 colors_update: HashMap::default(),
6273 last_version_queried: HashMap::default(),
6274 });
6275 outdated_lsp_data = true;
6276 }
6277
6278 {
6279 let lsp_data = self.lsp_data.as_mut()?;
6280 match for_server_id {
6281 Some(for_server_id) if !outdated_lsp_data => {
6282 lsp_data.buffer_lsp_data.remove(&for_server_id);
6283 }
6284 None | Some(_) => {
6285 let existing_task = lsp_data.colors_update.get(&abs_path).cloned();
6286 if !outdated_lsp_data && existing_task.is_some() {
6287 return existing_task;
6288 }
6289 for buffer_data in lsp_data.buffer_lsp_data.values_mut() {
6290 if let Some(buffer_data) = buffer_data.get_mut(&abs_path) {
6291 buffer_data.colors = None;
6292 }
6293 }
6294 }
6295 }
6296 }
6297
6298 let task_abs_path = abs_path.clone();
6299 let new_task = cx
6300 .spawn(async move |lsp_store, cx| {
6301 match fetch_document_colors(
6302 lsp_store.clone(),
6303 buffer,
6304 task_abs_path.clone(),
6305 cx,
6306 )
6307 .await
6308 {
6309 Ok(colors) => Ok(colors),
6310 Err(e) => {
6311 lsp_store
6312 .update(cx, |lsp_store, _| {
6313 if let Some(lsp_data) = lsp_store.lsp_data.as_mut() {
6314 lsp_data.colors_update.remove(&task_abs_path);
6315 }
6316 })
6317 .ok();
6318 Err(Arc::new(e))
6319 }
6320 }
6321 })
6322 .shared();
6323 let lsp_data = self.lsp_data.as_mut()?;
6324 lsp_data
6325 .colors_update
6326 .insert(abs_path.clone(), new_task.clone());
6327 lsp_data
6328 .last_version_queried
6329 .insert(abs_path, buffer_version);
6330 lsp_data.mtime = buffer_mtime;
6331 Some(new_task)
6332 } else {
6333 Some(Task::ready(Ok(buffer_lsp_data)).shared())
6334 }
6335 }
6336
6337 fn fetch_document_colors_for_buffer(
6338 &mut self,
6339 buffer: Entity<Buffer>,
6340 cx: &mut Context<Self>,
6341 ) -> Task<anyhow::Result<Vec<(LanguageServerId, HashSet<DocumentColor>)>>> {
6342 if let Some((client, project_id)) = self.upstream_client() {
6343 let request_task = client.request(proto::MultiLspQuery {
6344 project_id,
6345 buffer_id: buffer.read(cx).remote_id().to_proto(),
6346 version: serialize_version(&buffer.read(cx).version()),
6347 strategy: Some(proto::multi_lsp_query::Strategy::All(
6348 proto::AllLanguageServers {},
6349 )),
6350 request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
6351 GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
6352 )),
6353 });
6354 cx.spawn(async move |project, cx| {
6355 let Some(project) = project.upgrade() else {
6356 return Ok(Vec::new());
6357 };
6358 let colors = join_all(
6359 request_task
6360 .await
6361 .log_err()
6362 .map(|response| response.responses)
6363 .unwrap_or_default()
6364 .into_iter()
6365 .filter_map(|lsp_response| match lsp_response.response? {
6366 proto::lsp_response::Response::GetDocumentColorResponse(response) => {
6367 Some((
6368 LanguageServerId::from_proto(lsp_response.server_id),
6369 response,
6370 ))
6371 }
6372 unexpected => {
6373 debug_panic!("Unexpected response: {unexpected:?}");
6374 None
6375 }
6376 })
6377 .map(|(server_id, color_response)| {
6378 let response = GetDocumentColor {}.response_from_proto(
6379 color_response,
6380 project.clone(),
6381 buffer.clone(),
6382 cx.clone(),
6383 );
6384 async move { (server_id, response.await.log_err().unwrap_or_default()) }
6385 }),
6386 )
6387 .await
6388 .into_iter()
6389 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6390 acc.entry(server_id)
6391 .or_insert_with(HashSet::default)
6392 .extend(colors);
6393 acc
6394 })
6395 .into_iter()
6396 .collect();
6397 Ok(colors)
6398 })
6399 } else {
6400 let document_colors_task =
6401 self.request_multiple_lsp_locally(&buffer, None::<usize>, GetDocumentColor, cx);
6402 cx.spawn(async move |_, _| {
6403 Ok(document_colors_task
6404 .await
6405 .into_iter()
6406 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6407 acc.entry(server_id)
6408 .or_insert_with(HashSet::default)
6409 .extend(colors);
6410 acc
6411 })
6412 .into_iter()
6413 .collect())
6414 })
6415 }
6416 }
6417
6418 pub fn signature_help<T: ToPointUtf16>(
6419 &mut self,
6420 buffer: &Entity<Buffer>,
6421 position: T,
6422 cx: &mut Context<Self>,
6423 ) -> Task<Vec<SignatureHelp>> {
6424 let position = position.to_point_utf16(buffer.read(cx));
6425
6426 if let Some((client, upstream_project_id)) = self.upstream_client() {
6427 let request_task = client.request(proto::MultiLspQuery {
6428 buffer_id: buffer.read(cx).remote_id().into(),
6429 version: serialize_version(&buffer.read(cx).version()),
6430 project_id: upstream_project_id,
6431 strategy: Some(proto::multi_lsp_query::Strategy::All(
6432 proto::AllLanguageServers {},
6433 )),
6434 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
6435 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
6436 )),
6437 });
6438 let buffer = buffer.clone();
6439 cx.spawn(async move |weak_project, cx| {
6440 let Some(project) = weak_project.upgrade() else {
6441 return Vec::new();
6442 };
6443 join_all(
6444 request_task
6445 .await
6446 .log_err()
6447 .map(|response| response.responses)
6448 .unwrap_or_default()
6449 .into_iter()
6450 .filter_map(|lsp_response| match lsp_response.response? {
6451 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
6452 Some(response)
6453 }
6454 unexpected => {
6455 debug_panic!("Unexpected response: {unexpected:?}");
6456 None
6457 }
6458 })
6459 .map(|signature_response| {
6460 let response = GetSignatureHelp { position }.response_from_proto(
6461 signature_response,
6462 project.clone(),
6463 buffer.clone(),
6464 cx.clone(),
6465 );
6466 async move { response.await.log_err().flatten() }
6467 }),
6468 )
6469 .await
6470 .into_iter()
6471 .flatten()
6472 .collect()
6473 })
6474 } else {
6475 let all_actions_task = self.request_multiple_lsp_locally(
6476 buffer,
6477 Some(position),
6478 GetSignatureHelp { position },
6479 cx,
6480 );
6481 cx.spawn(async move |_, _| {
6482 all_actions_task
6483 .await
6484 .into_iter()
6485 .flat_map(|(_, actions)| actions)
6486 .filter(|help| !help.label.is_empty())
6487 .collect::<Vec<_>>()
6488 })
6489 }
6490 }
6491
6492 pub fn hover(
6493 &mut self,
6494 buffer: &Entity<Buffer>,
6495 position: PointUtf16,
6496 cx: &mut Context<Self>,
6497 ) -> Task<Vec<Hover>> {
6498 if let Some((client, upstream_project_id)) = self.upstream_client() {
6499 let request_task = client.request(proto::MultiLspQuery {
6500 buffer_id: buffer.read(cx).remote_id().into(),
6501 version: serialize_version(&buffer.read(cx).version()),
6502 project_id: upstream_project_id,
6503 strategy: Some(proto::multi_lsp_query::Strategy::All(
6504 proto::AllLanguageServers {},
6505 )),
6506 request: Some(proto::multi_lsp_query::Request::GetHover(
6507 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
6508 )),
6509 });
6510 let buffer = buffer.clone();
6511 cx.spawn(async move |weak_project, cx| {
6512 let Some(project) = weak_project.upgrade() else {
6513 return Vec::new();
6514 };
6515 join_all(
6516 request_task
6517 .await
6518 .log_err()
6519 .map(|response| response.responses)
6520 .unwrap_or_default()
6521 .into_iter()
6522 .filter_map(|lsp_response| match lsp_response.response? {
6523 proto::lsp_response::Response::GetHoverResponse(response) => {
6524 Some(response)
6525 }
6526 unexpected => {
6527 debug_panic!("Unexpected response: {unexpected:?}");
6528 None
6529 }
6530 })
6531 .map(|hover_response| {
6532 let response = GetHover { position }.response_from_proto(
6533 hover_response,
6534 project.clone(),
6535 buffer.clone(),
6536 cx.clone(),
6537 );
6538 async move {
6539 response
6540 .await
6541 .log_err()
6542 .flatten()
6543 .and_then(remove_empty_hover_blocks)
6544 }
6545 }),
6546 )
6547 .await
6548 .into_iter()
6549 .flatten()
6550 .collect()
6551 })
6552 } else {
6553 let all_actions_task = self.request_multiple_lsp_locally(
6554 buffer,
6555 Some(position),
6556 GetHover { position },
6557 cx,
6558 );
6559 cx.spawn(async move |_, _| {
6560 all_actions_task
6561 .await
6562 .into_iter()
6563 .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
6564 .collect::<Vec<Hover>>()
6565 })
6566 }
6567 }
6568
6569 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
6570 let language_registry = self.languages.clone();
6571
6572 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
6573 let request = upstream_client.request(proto::GetProjectSymbols {
6574 project_id: *project_id,
6575 query: query.to_string(),
6576 });
6577 cx.foreground_executor().spawn(async move {
6578 let response = request.await?;
6579 let mut symbols = Vec::new();
6580 let core_symbols = response
6581 .symbols
6582 .into_iter()
6583 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
6584 .collect::<Vec<_>>();
6585 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
6586 .await;
6587 Ok(symbols)
6588 })
6589 } else if let Some(local) = self.as_local() {
6590 struct WorkspaceSymbolsResult {
6591 server_id: LanguageServerId,
6592 lsp_adapter: Arc<CachedLspAdapter>,
6593 worktree: WeakEntity<Worktree>,
6594 worktree_abs_path: Arc<Path>,
6595 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
6596 }
6597
6598 let mut requests = Vec::new();
6599 let mut requested_servers = BTreeSet::new();
6600 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
6601 let Some(worktree_handle) = self
6602 .worktree_store
6603 .read(cx)
6604 .worktree_for_id(*worktree_id, cx)
6605 else {
6606 continue;
6607 };
6608 let worktree = worktree_handle.read(cx);
6609 if !worktree.is_visible() {
6610 continue;
6611 }
6612
6613 let mut servers_to_query = server_ids
6614 .difference(&requested_servers)
6615 .cloned()
6616 .collect::<BTreeSet<_>>();
6617 for server_id in &servers_to_query {
6618 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
6619 Some(LanguageServerState::Running {
6620 adapter, server, ..
6621 }) => (adapter.clone(), server),
6622
6623 _ => continue 'next_server,
6624 };
6625 let supports_workspace_symbol_request =
6626 match server.capabilities().workspace_symbol_provider {
6627 Some(OneOf::Left(supported)) => supported,
6628 Some(OneOf::Right(_)) => true,
6629 None => false,
6630 };
6631 if !supports_workspace_symbol_request {
6632 continue 'next_server;
6633 }
6634 let worktree_abs_path = worktree.abs_path().clone();
6635 let worktree_handle = worktree_handle.clone();
6636 let server_id = server.server_id();
6637 requests.push(
6638 server
6639 .request::<lsp::request::WorkspaceSymbolRequest>(
6640 lsp::WorkspaceSymbolParams {
6641 query: query.to_string(),
6642 ..Default::default()
6643 },
6644 )
6645 .map(move |response| {
6646 let lsp_symbols = response.into_response()
6647 .context("workspace symbols request")
6648 .log_err()
6649 .flatten()
6650 .map(|symbol_response| match symbol_response {
6651 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
6652 flat_responses.into_iter().map(|lsp_symbol| {
6653 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
6654 }).collect::<Vec<_>>()
6655 }
6656 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
6657 nested_responses.into_iter().filter_map(|lsp_symbol| {
6658 let location = match lsp_symbol.location {
6659 OneOf::Left(location) => location,
6660 OneOf::Right(_) => {
6661 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
6662 return None
6663 }
6664 };
6665 Some((lsp_symbol.name, lsp_symbol.kind, location))
6666 }).collect::<Vec<_>>()
6667 }
6668 }).unwrap_or_default();
6669
6670 WorkspaceSymbolsResult {
6671 server_id,
6672 lsp_adapter,
6673 worktree: worktree_handle.downgrade(),
6674 worktree_abs_path,
6675 lsp_symbols,
6676 }
6677 }),
6678 );
6679 }
6680 requested_servers.append(&mut servers_to_query);
6681 }
6682
6683 cx.spawn(async move |this, cx| {
6684 let responses = futures::future::join_all(requests).await;
6685 let this = match this.upgrade() {
6686 Some(this) => this,
6687 None => return Ok(Vec::new()),
6688 };
6689
6690 let mut symbols = Vec::new();
6691 for result in responses {
6692 let core_symbols = this.update(cx, |this, cx| {
6693 result
6694 .lsp_symbols
6695 .into_iter()
6696 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
6697 let abs_path = symbol_location.uri.to_file_path().ok()?;
6698 let source_worktree = result.worktree.upgrade()?;
6699 let source_worktree_id = source_worktree.read(cx).id();
6700
6701 let path;
6702 let worktree;
6703 if let Some((tree, rel_path)) =
6704 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
6705 {
6706 worktree = tree;
6707 path = rel_path;
6708 } else {
6709 worktree = source_worktree.clone();
6710 path = relativize_path(&result.worktree_abs_path, &abs_path);
6711 }
6712
6713 let worktree_id = worktree.read(cx).id();
6714 let project_path = ProjectPath {
6715 worktree_id,
6716 path: path.into(),
6717 };
6718 let signature = this.symbol_signature(&project_path);
6719 Some(CoreSymbol {
6720 source_language_server_id: result.server_id,
6721 language_server_name: result.lsp_adapter.name.clone(),
6722 source_worktree_id,
6723 path: project_path,
6724 kind: symbol_kind,
6725 name: symbol_name,
6726 range: range_from_lsp(symbol_location.range),
6727 signature,
6728 })
6729 })
6730 .collect()
6731 })?;
6732
6733 populate_labels_for_symbols(
6734 core_symbols,
6735 &language_registry,
6736 Some(result.lsp_adapter),
6737 &mut symbols,
6738 )
6739 .await;
6740 }
6741
6742 Ok(symbols)
6743 })
6744 } else {
6745 Task::ready(Err(anyhow!("No upstream client or local language server")))
6746 }
6747 }
6748
6749 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
6750 let mut summary = DiagnosticSummary::default();
6751 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
6752 summary.error_count += path_summary.error_count;
6753 summary.warning_count += path_summary.warning_count;
6754 }
6755 summary
6756 }
6757
6758 pub fn diagnostic_summaries<'a>(
6759 &'a self,
6760 include_ignored: bool,
6761 cx: &'a App,
6762 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6763 self.worktree_store
6764 .read(cx)
6765 .visible_worktrees(cx)
6766 .filter_map(|worktree| {
6767 let worktree = worktree.read(cx);
6768 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
6769 })
6770 .flat_map(move |(worktree, summaries)| {
6771 let worktree_id = worktree.id();
6772 summaries
6773 .iter()
6774 .filter(move |(path, _)| {
6775 include_ignored
6776 || worktree
6777 .entry_for_path(path.as_ref())
6778 .map_or(false, |entry| !entry.is_ignored)
6779 })
6780 .flat_map(move |(path, summaries)| {
6781 summaries.iter().map(move |(server_id, summary)| {
6782 (
6783 ProjectPath {
6784 worktree_id,
6785 path: path.clone(),
6786 },
6787 *server_id,
6788 *summary,
6789 )
6790 })
6791 })
6792 })
6793 }
6794
6795 pub fn on_buffer_edited(
6796 &mut self,
6797 buffer: Entity<Buffer>,
6798 cx: &mut Context<Self>,
6799 ) -> Option<()> {
6800 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
6801 Some(
6802 self.as_local()?
6803 .language_servers_for_buffer(buffer, cx)
6804 .map(|i| i.1.clone())
6805 .collect(),
6806 )
6807 })?;
6808
6809 let buffer = buffer.read(cx);
6810 let file = File::from_dyn(buffer.file())?;
6811 let abs_path = file.as_local()?.abs_path(cx);
6812 let uri = lsp::Url::from_file_path(abs_path).unwrap();
6813 let next_snapshot = buffer.text_snapshot();
6814 for language_server in language_servers {
6815 let language_server = language_server.clone();
6816
6817 let buffer_snapshots = self
6818 .as_local_mut()
6819 .unwrap()
6820 .buffer_snapshots
6821 .get_mut(&buffer.remote_id())
6822 .and_then(|m| m.get_mut(&language_server.server_id()))?;
6823 let previous_snapshot = buffer_snapshots.last()?;
6824
6825 let build_incremental_change = || {
6826 buffer
6827 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6828 .map(|edit| {
6829 let edit_start = edit.new.start.0;
6830 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6831 let new_text = next_snapshot
6832 .text_for_range(edit.new.start.1..edit.new.end.1)
6833 .collect();
6834 lsp::TextDocumentContentChangeEvent {
6835 range: Some(lsp::Range::new(
6836 point_to_lsp(edit_start),
6837 point_to_lsp(edit_end),
6838 )),
6839 range_length: None,
6840 text: new_text,
6841 }
6842 })
6843 .collect()
6844 };
6845
6846 let document_sync_kind = language_server
6847 .capabilities()
6848 .text_document_sync
6849 .as_ref()
6850 .and_then(|sync| match sync {
6851 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6852 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6853 });
6854
6855 let content_changes: Vec<_> = match document_sync_kind {
6856 Some(lsp::TextDocumentSyncKind::FULL) => {
6857 vec![lsp::TextDocumentContentChangeEvent {
6858 range: None,
6859 range_length: None,
6860 text: next_snapshot.text(),
6861 }]
6862 }
6863 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6864 _ => {
6865 #[cfg(any(test, feature = "test-support"))]
6866 {
6867 build_incremental_change()
6868 }
6869
6870 #[cfg(not(any(test, feature = "test-support")))]
6871 {
6872 continue;
6873 }
6874 }
6875 };
6876
6877 let next_version = previous_snapshot.version + 1;
6878 buffer_snapshots.push(LspBufferSnapshot {
6879 version: next_version,
6880 snapshot: next_snapshot.clone(),
6881 });
6882
6883 language_server
6884 .notify::<lsp::notification::DidChangeTextDocument>(
6885 &lsp::DidChangeTextDocumentParams {
6886 text_document: lsp::VersionedTextDocumentIdentifier::new(
6887 uri.clone(),
6888 next_version,
6889 ),
6890 content_changes,
6891 },
6892 )
6893 .ok();
6894 self.pull_workspace_diagnostics(language_server.server_id());
6895 }
6896
6897 None
6898 }
6899
6900 pub fn on_buffer_saved(
6901 &mut self,
6902 buffer: Entity<Buffer>,
6903 cx: &mut Context<Self>,
6904 ) -> Option<()> {
6905 let file = File::from_dyn(buffer.read(cx).file())?;
6906 let worktree_id = file.worktree_id(cx);
6907 let abs_path = file.as_local()?.abs_path(cx);
6908 let text_document = lsp::TextDocumentIdentifier {
6909 uri: file_path_to_lsp_url(&abs_path).log_err()?,
6910 };
6911 let local = self.as_local()?;
6912
6913 for server in local.language_servers_for_worktree(worktree_id) {
6914 if let Some(include_text) = include_text(server.as_ref()) {
6915 let text = if include_text {
6916 Some(buffer.read(cx).text())
6917 } else {
6918 None
6919 };
6920 server
6921 .notify::<lsp::notification::DidSaveTextDocument>(
6922 &lsp::DidSaveTextDocumentParams {
6923 text_document: text_document.clone(),
6924 text,
6925 },
6926 )
6927 .ok();
6928 }
6929 }
6930
6931 let language_servers = buffer.update(cx, |buffer, cx| {
6932 local.language_server_ids_for_buffer(buffer, cx)
6933 });
6934 for language_server_id in language_servers {
6935 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6936 }
6937
6938 None
6939 }
6940
6941 pub(crate) async fn refresh_workspace_configurations(
6942 this: &WeakEntity<Self>,
6943 fs: Arc<dyn Fs>,
6944 cx: &mut AsyncApp,
6945 ) {
6946 maybe!(async move {
6947 let servers = this
6948 .update(cx, |this, cx| {
6949 let Some(local) = this.as_local() else {
6950 return Vec::default();
6951 };
6952 local
6953 .language_server_ids
6954 .iter()
6955 .flat_map(|((worktree_id, _), server_ids)| {
6956 let worktree = this
6957 .worktree_store
6958 .read(cx)
6959 .worktree_for_id(*worktree_id, cx);
6960 let delegate = worktree.map(|worktree| {
6961 LocalLspAdapterDelegate::new(
6962 local.languages.clone(),
6963 &local.environment,
6964 cx.weak_entity(),
6965 &worktree,
6966 local.http_client.clone(),
6967 local.fs.clone(),
6968 cx,
6969 )
6970 });
6971
6972 server_ids.iter().filter_map(move |server_id| {
6973 let states = local.language_servers.get(server_id)?;
6974
6975 match states {
6976 LanguageServerState::Starting { .. } => None,
6977 LanguageServerState::Running {
6978 adapter, server, ..
6979 } => Some((
6980 adapter.adapter.clone(),
6981 server.clone(),
6982 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
6983 )),
6984 }
6985 })
6986 })
6987 .collect::<Vec<_>>()
6988 })
6989 .ok()?;
6990
6991 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
6992 for (adapter, server, delegate) in servers {
6993 let settings = LocalLspStore::workspace_configuration_for_adapter(
6994 adapter,
6995 fs.as_ref(),
6996 &delegate,
6997 toolchain_store.clone(),
6998 cx,
6999 )
7000 .await
7001 .ok()?;
7002
7003 server
7004 .notify::<lsp::notification::DidChangeConfiguration>(
7005 &lsp::DidChangeConfigurationParams { settings },
7006 )
7007 .ok();
7008 }
7009 Some(())
7010 })
7011 .await;
7012 }
7013
7014 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
7015 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
7016 toolchain_store.read(cx).as_language_toolchain_store()
7017 } else {
7018 Arc::new(EmptyToolchainStore)
7019 }
7020 }
7021 fn maintain_workspace_config(
7022 fs: Arc<dyn Fs>,
7023 external_refresh_requests: watch::Receiver<()>,
7024 cx: &mut Context<Self>,
7025 ) -> Task<Result<()>> {
7026 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
7027 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
7028
7029 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
7030 *settings_changed_tx.borrow_mut() = ();
7031 });
7032
7033 let mut joint_future =
7034 futures::stream::select(settings_changed_rx, external_refresh_requests);
7035 cx.spawn(async move |this, cx| {
7036 while let Some(()) = joint_future.next().await {
7037 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
7038 }
7039
7040 drop(settings_observation);
7041 anyhow::Ok(())
7042 })
7043 }
7044
7045 pub fn language_servers_for_local_buffer<'a>(
7046 &'a self,
7047 buffer: &Buffer,
7048 cx: &mut App,
7049 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7050 let local = self.as_local();
7051 let language_server_ids = local
7052 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
7053 .unwrap_or_default();
7054
7055 language_server_ids
7056 .into_iter()
7057 .filter_map(
7058 move |server_id| match local?.language_servers.get(&server_id)? {
7059 LanguageServerState::Running {
7060 adapter, server, ..
7061 } => Some((adapter, server)),
7062 _ => None,
7063 },
7064 )
7065 }
7066
7067 pub fn language_server_for_local_buffer<'a>(
7068 &'a self,
7069 buffer: &'a Buffer,
7070 server_id: LanguageServerId,
7071 cx: &'a mut App,
7072 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
7073 self.as_local()?
7074 .language_servers_for_buffer(buffer, cx)
7075 .find(|(_, s)| s.server_id() == server_id)
7076 }
7077
7078 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
7079 self.diagnostic_summaries.remove(&id_to_remove);
7080 if let Some(local) = self.as_local_mut() {
7081 let to_remove = local.remove_worktree(id_to_remove, cx);
7082 for server in to_remove {
7083 self.language_server_statuses.remove(&server);
7084 }
7085 }
7086 }
7087
7088 pub fn shared(
7089 &mut self,
7090 project_id: u64,
7091 downstream_client: AnyProtoClient,
7092 _: &mut Context<Self>,
7093 ) {
7094 self.downstream_client = Some((downstream_client.clone(), project_id));
7095
7096 for (server_id, status) in &self.language_server_statuses {
7097 downstream_client
7098 .send(proto::StartLanguageServer {
7099 project_id,
7100 server: Some(proto::LanguageServer {
7101 id: server_id.0 as u64,
7102 name: status.name.clone(),
7103 worktree_id: None,
7104 }),
7105 })
7106 .log_err();
7107 }
7108 }
7109
7110 pub fn disconnected_from_host(&mut self) {
7111 self.downstream_client.take();
7112 }
7113
7114 pub fn disconnected_from_ssh_remote(&mut self) {
7115 if let LspStoreMode::Remote(RemoteLspStore {
7116 upstream_client, ..
7117 }) = &mut self.mode
7118 {
7119 upstream_client.take();
7120 }
7121 }
7122
7123 pub(crate) fn set_language_server_statuses_from_proto(
7124 &mut self,
7125 language_servers: Vec<proto::LanguageServer>,
7126 ) {
7127 self.language_server_statuses = language_servers
7128 .into_iter()
7129 .map(|server| {
7130 (
7131 LanguageServerId(server.id as usize),
7132 LanguageServerStatus {
7133 name: server.name,
7134 pending_work: Default::default(),
7135 has_pending_diagnostic_updates: false,
7136 progress_tokens: Default::default(),
7137 },
7138 )
7139 })
7140 .collect();
7141 }
7142
7143 fn register_local_language_server(
7144 &mut self,
7145 worktree: Entity<Worktree>,
7146 language_server_name: LanguageServerName,
7147 language_server_id: LanguageServerId,
7148 cx: &mut App,
7149 ) {
7150 let Some(local) = self.as_local_mut() else {
7151 return;
7152 };
7153
7154 let worktree_id = worktree.read(cx).id();
7155 if worktree.read(cx).is_visible() {
7156 let path = ProjectPath {
7157 worktree_id,
7158 path: Arc::from("".as_ref()),
7159 };
7160 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
7161 local.lsp_tree.update(cx, |language_server_tree, cx| {
7162 for node in language_server_tree.get(
7163 path,
7164 AdapterQuery::Adapter(&language_server_name),
7165 delegate,
7166 cx,
7167 ) {
7168 node.server_id_or_init(|disposition| {
7169 assert_eq!(disposition.server_name, &language_server_name);
7170
7171 language_server_id
7172 });
7173 }
7174 });
7175 }
7176
7177 local
7178 .language_server_ids
7179 .entry((worktree_id, language_server_name))
7180 .or_default()
7181 .insert(language_server_id);
7182 }
7183
7184 #[cfg(test)]
7185 pub fn update_diagnostic_entries(
7186 &mut self,
7187 server_id: LanguageServerId,
7188 abs_path: PathBuf,
7189 result_id: Option<String>,
7190 version: Option<i32>,
7191 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7192 cx: &mut Context<Self>,
7193 ) -> anyhow::Result<()> {
7194 self.merge_diagnostic_entries(
7195 server_id,
7196 abs_path,
7197 result_id,
7198 version,
7199 diagnostics,
7200 |_, _, _| false,
7201 cx,
7202 )
7203 }
7204
7205 pub fn merge_diagnostic_entries(
7206 &mut self,
7207 server_id: LanguageServerId,
7208 abs_path: PathBuf,
7209 result_id: Option<String>,
7210 version: Option<i32>,
7211 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7212 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
7213 cx: &mut Context<Self>,
7214 ) -> anyhow::Result<()> {
7215 let Some((worktree, relative_path)) =
7216 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
7217 else {
7218 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
7219 return Ok(());
7220 };
7221
7222 let project_path = ProjectPath {
7223 worktree_id: worktree.read(cx).id(),
7224 path: relative_path.into(),
7225 };
7226
7227 if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path) {
7228 let snapshot = buffer_handle.read(cx).snapshot();
7229 let buffer = buffer_handle.read(cx);
7230 let reused_diagnostics = buffer
7231 .get_diagnostics(server_id)
7232 .into_iter()
7233 .flat_map(|diag| {
7234 diag.iter()
7235 .filter(|v| filter(buffer, &v.diagnostic, cx))
7236 .map(|v| {
7237 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
7238 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
7239 DiagnosticEntry {
7240 range: start..end,
7241 diagnostic: v.diagnostic.clone(),
7242 }
7243 })
7244 })
7245 .collect::<Vec<_>>();
7246
7247 self.as_local_mut()
7248 .context("cannot merge diagnostics on a remote LspStore")?
7249 .update_buffer_diagnostics(
7250 &buffer_handle,
7251 server_id,
7252 result_id,
7253 version,
7254 diagnostics.clone(),
7255 reused_diagnostics.clone(),
7256 cx,
7257 )?;
7258
7259 diagnostics.extend(reused_diagnostics);
7260 }
7261
7262 let updated = worktree.update(cx, |worktree, cx| {
7263 self.update_worktree_diagnostics(
7264 worktree.id(),
7265 server_id,
7266 project_path.path.clone(),
7267 diagnostics,
7268 cx,
7269 )
7270 })?;
7271 if updated {
7272 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7273 language_server_id: server_id,
7274 path: project_path,
7275 })
7276 }
7277 Ok(())
7278 }
7279
7280 fn update_worktree_diagnostics(
7281 &mut self,
7282 worktree_id: WorktreeId,
7283 server_id: LanguageServerId,
7284 worktree_path: Arc<Path>,
7285 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7286 _: &mut Context<Worktree>,
7287 ) -> Result<bool> {
7288 let local = match &mut self.mode {
7289 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
7290 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
7291 };
7292
7293 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
7294 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
7295 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
7296
7297 let old_summary = summaries_by_server_id
7298 .remove(&server_id)
7299 .unwrap_or_default();
7300
7301 let new_summary = DiagnosticSummary::new(&diagnostics);
7302 if new_summary.is_empty() {
7303 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
7304 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7305 diagnostics_by_server_id.remove(ix);
7306 }
7307 if diagnostics_by_server_id.is_empty() {
7308 diagnostics_for_tree.remove(&worktree_path);
7309 }
7310 }
7311 } else {
7312 summaries_by_server_id.insert(server_id, new_summary);
7313 let diagnostics_by_server_id = diagnostics_for_tree
7314 .entry(worktree_path.clone())
7315 .or_default();
7316 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7317 Ok(ix) => {
7318 diagnostics_by_server_id[ix] = (server_id, diagnostics);
7319 }
7320 Err(ix) => {
7321 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
7322 }
7323 }
7324 }
7325
7326 if !old_summary.is_empty() || !new_summary.is_empty() {
7327 if let Some((downstream_client, project_id)) = &self.downstream_client {
7328 downstream_client
7329 .send(proto::UpdateDiagnosticSummary {
7330 project_id: *project_id,
7331 worktree_id: worktree_id.to_proto(),
7332 summary: Some(proto::DiagnosticSummary {
7333 path: worktree_path.to_proto(),
7334 language_server_id: server_id.0 as u64,
7335 error_count: new_summary.error_count as u32,
7336 warning_count: new_summary.warning_count as u32,
7337 }),
7338 })
7339 .log_err();
7340 }
7341 }
7342
7343 Ok(!old_summary.is_empty() || !new_summary.is_empty())
7344 }
7345
7346 pub fn open_buffer_for_symbol(
7347 &mut self,
7348 symbol: &Symbol,
7349 cx: &mut Context<Self>,
7350 ) -> Task<Result<Entity<Buffer>>> {
7351 if let Some((client, project_id)) = self.upstream_client() {
7352 let request = client.request(proto::OpenBufferForSymbol {
7353 project_id,
7354 symbol: Some(Self::serialize_symbol(symbol)),
7355 });
7356 cx.spawn(async move |this, cx| {
7357 let response = request.await?;
7358 let buffer_id = BufferId::new(response.buffer_id)?;
7359 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
7360 .await
7361 })
7362 } else if let Some(local) = self.as_local() {
7363 let Some(language_server_id) = local
7364 .language_server_ids
7365 .get(&(
7366 symbol.source_worktree_id,
7367 symbol.language_server_name.clone(),
7368 ))
7369 .and_then(|ids| {
7370 ids.contains(&symbol.source_language_server_id)
7371 .then_some(symbol.source_language_server_id)
7372 })
7373 else {
7374 return Task::ready(Err(anyhow!(
7375 "language server for worktree and language not found"
7376 )));
7377 };
7378
7379 let worktree_abs_path = if let Some(worktree_abs_path) = self
7380 .worktree_store
7381 .read(cx)
7382 .worktree_for_id(symbol.path.worktree_id, cx)
7383 .map(|worktree| worktree.read(cx).abs_path())
7384 {
7385 worktree_abs_path
7386 } else {
7387 return Task::ready(Err(anyhow!("worktree not found for symbol")));
7388 };
7389
7390 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
7391 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
7392 uri
7393 } else {
7394 return Task::ready(Err(anyhow!("invalid symbol path")));
7395 };
7396
7397 self.open_local_buffer_via_lsp(
7398 symbol_uri,
7399 language_server_id,
7400 symbol.language_server_name.clone(),
7401 cx,
7402 )
7403 } else {
7404 Task::ready(Err(anyhow!("no upstream client or local store")))
7405 }
7406 }
7407
7408 pub fn open_local_buffer_via_lsp(
7409 &mut self,
7410 mut abs_path: lsp::Url,
7411 language_server_id: LanguageServerId,
7412 language_server_name: LanguageServerName,
7413 cx: &mut Context<Self>,
7414 ) -> Task<Result<Entity<Buffer>>> {
7415 cx.spawn(async move |lsp_store, cx| {
7416 // Escape percent-encoded string.
7417 let current_scheme = abs_path.scheme().to_owned();
7418 let _ = abs_path.set_scheme("file");
7419
7420 let abs_path = abs_path
7421 .to_file_path()
7422 .map_err(|()| anyhow!("can't convert URI to path"))?;
7423 let p = abs_path.clone();
7424 let yarn_worktree = lsp_store
7425 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
7426 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
7427 cx.spawn(async move |this, cx| {
7428 let t = this
7429 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
7430 .ok()?;
7431 t.await
7432 })
7433 }),
7434 None => Task::ready(None),
7435 })?
7436 .await;
7437 let (worktree_root_target, known_relative_path) =
7438 if let Some((zip_root, relative_path)) = yarn_worktree {
7439 (zip_root, Some(relative_path))
7440 } else {
7441 (Arc::<Path>::from(abs_path.as_path()), None)
7442 };
7443 let (worktree, relative_path) = if let Some(result) =
7444 lsp_store.update(cx, |lsp_store, cx| {
7445 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7446 worktree_store.find_worktree(&worktree_root_target, cx)
7447 })
7448 })? {
7449 let relative_path =
7450 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
7451 (result.0, relative_path)
7452 } else {
7453 let worktree = lsp_store
7454 .update(cx, |lsp_store, cx| {
7455 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7456 worktree_store.create_worktree(&worktree_root_target, false, cx)
7457 })
7458 })?
7459 .await?;
7460 if worktree.read_with(cx, |worktree, _| worktree.is_local())? {
7461 lsp_store
7462 .update(cx, |lsp_store, cx| {
7463 lsp_store.register_local_language_server(
7464 worktree.clone(),
7465 language_server_name,
7466 language_server_id,
7467 cx,
7468 )
7469 })
7470 .ok();
7471 }
7472 let worktree_root = worktree.read_with(cx, |worktree, _| worktree.abs_path())?;
7473 let relative_path = if let Some(known_path) = known_relative_path {
7474 known_path
7475 } else {
7476 abs_path.strip_prefix(worktree_root)?.into()
7477 };
7478 (worktree, relative_path)
7479 };
7480 let project_path = ProjectPath {
7481 worktree_id: worktree.read_with(cx, |worktree, _| worktree.id())?,
7482 path: relative_path,
7483 };
7484 lsp_store
7485 .update(cx, |lsp_store, cx| {
7486 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
7487 buffer_store.open_buffer(project_path, cx)
7488 })
7489 })?
7490 .await
7491 })
7492 }
7493
7494 fn request_multiple_lsp_locally<P, R>(
7495 &mut self,
7496 buffer: &Entity<Buffer>,
7497 position: Option<P>,
7498 request: R,
7499 cx: &mut Context<Self>,
7500 ) -> Task<Vec<(LanguageServerId, R::Response)>>
7501 where
7502 P: ToOffset,
7503 R: LspCommand + Clone,
7504 <R::LspRequest as lsp::request::Request>::Result: Send,
7505 <R::LspRequest as lsp::request::Request>::Params: Send,
7506 {
7507 let Some(local) = self.as_local() else {
7508 return Task::ready(Vec::new());
7509 };
7510
7511 let snapshot = buffer.read(cx).snapshot();
7512 let scope = position.and_then(|position| snapshot.language_scope_at(position));
7513
7514 let server_ids = buffer.update(cx, |buffer, cx| {
7515 local
7516 .language_servers_for_buffer(buffer, cx)
7517 .filter(|(adapter, _)| {
7518 scope
7519 .as_ref()
7520 .map(|scope| scope.language_allowed(&adapter.name))
7521 .unwrap_or(true)
7522 })
7523 .map(|(_, server)| server.server_id())
7524 .collect::<Vec<_>>()
7525 });
7526
7527 let mut response_results = server_ids
7528 .into_iter()
7529 .map(|server_id| {
7530 let task = self.request_lsp(
7531 buffer.clone(),
7532 LanguageServerToQuery::Other(server_id),
7533 request.clone(),
7534 cx,
7535 );
7536 async move { (server_id, task.await) }
7537 })
7538 .collect::<FuturesUnordered<_>>();
7539
7540 cx.spawn(async move |_, _| {
7541 let mut responses = Vec::with_capacity(response_results.len());
7542 while let Some((server_id, response_result)) = response_results.next().await {
7543 if let Some(response) = response_result.log_err() {
7544 responses.push((server_id, response));
7545 }
7546 }
7547 responses
7548 })
7549 }
7550
7551 async fn handle_lsp_command<T: LspCommand>(
7552 this: Entity<Self>,
7553 envelope: TypedEnvelope<T::ProtoRequest>,
7554 mut cx: AsyncApp,
7555 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7556 where
7557 <T::LspRequest as lsp::request::Request>::Params: Send,
7558 <T::LspRequest as lsp::request::Request>::Result: Send,
7559 {
7560 let sender_id = envelope.original_sender_id().unwrap_or_default();
7561 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
7562 let buffer_handle = this.update(&mut cx, |this, cx| {
7563 this.buffer_store.read(cx).get_existing(buffer_id)
7564 })??;
7565 let request = T::from_proto(
7566 envelope.payload,
7567 this.clone(),
7568 buffer_handle.clone(),
7569 cx.clone(),
7570 )
7571 .await?;
7572 let response = this
7573 .update(&mut cx, |this, cx| {
7574 this.request_lsp(
7575 buffer_handle.clone(),
7576 LanguageServerToQuery::FirstCapable,
7577 request,
7578 cx,
7579 )
7580 })?
7581 .await?;
7582 this.update(&mut cx, |this, cx| {
7583 Ok(T::response_to_proto(
7584 response,
7585 this,
7586 sender_id,
7587 &buffer_handle.read(cx).version(),
7588 cx,
7589 ))
7590 })?
7591 }
7592
7593 async fn handle_multi_lsp_query(
7594 lsp_store: Entity<Self>,
7595 envelope: TypedEnvelope<proto::MultiLspQuery>,
7596 mut cx: AsyncApp,
7597 ) -> Result<proto::MultiLspQueryResponse> {
7598 let response_from_ssh = lsp_store.read_with(&mut cx, |this, _| {
7599 let (upstream_client, project_id) = this.upstream_client()?;
7600 let mut payload = envelope.payload.clone();
7601 payload.project_id = project_id;
7602
7603 Some(upstream_client.request(payload))
7604 })?;
7605 if let Some(response_from_ssh) = response_from_ssh {
7606 return response_from_ssh.await;
7607 }
7608
7609 let sender_id = envelope.original_sender_id().unwrap_or_default();
7610 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7611 let version = deserialize_version(&envelope.payload.version);
7612 let buffer = lsp_store.update(&mut cx, |this, cx| {
7613 this.buffer_store.read(cx).get_existing(buffer_id)
7614 })??;
7615 buffer
7616 .update(&mut cx, |buffer, _| {
7617 buffer.wait_for_version(version.clone())
7618 })?
7619 .await?;
7620 let buffer_version = buffer.read_with(&mut cx, |buffer, _| buffer.version())?;
7621 match envelope
7622 .payload
7623 .strategy
7624 .context("invalid request without the strategy")?
7625 {
7626 proto::multi_lsp_query::Strategy::All(_) => {
7627 // currently, there's only one multiple language servers query strategy,
7628 // so just ensure it's specified correctly
7629 }
7630 }
7631 match envelope.payload.request {
7632 Some(proto::multi_lsp_query::Request::GetHover(message)) => {
7633 buffer
7634 .update(&mut cx, |buffer, _| {
7635 buffer.wait_for_version(deserialize_version(&message.version))
7636 })?
7637 .await?;
7638 let get_hover =
7639 GetHover::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7640 .await?;
7641 let all_hovers = lsp_store
7642 .update(&mut cx, |this, cx| {
7643 this.request_multiple_lsp_locally(
7644 &buffer,
7645 Some(get_hover.position),
7646 get_hover,
7647 cx,
7648 )
7649 })?
7650 .await
7651 .into_iter()
7652 .filter_map(|(server_id, hover)| {
7653 Some((server_id, remove_empty_hover_blocks(hover?)?))
7654 });
7655 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7656 responses: all_hovers
7657 .map(|(server_id, hover)| proto::LspResponse {
7658 server_id: server_id.to_proto(),
7659 response: Some(proto::lsp_response::Response::GetHoverResponse(
7660 GetHover::response_to_proto(
7661 Some(hover),
7662 project,
7663 sender_id,
7664 &buffer_version,
7665 cx,
7666 ),
7667 )),
7668 })
7669 .collect(),
7670 })
7671 }
7672 Some(proto::multi_lsp_query::Request::GetCodeActions(message)) => {
7673 buffer
7674 .update(&mut cx, |buffer, _| {
7675 buffer.wait_for_version(deserialize_version(&message.version))
7676 })?
7677 .await?;
7678 let get_code_actions = GetCodeActions::from_proto(
7679 message,
7680 lsp_store.clone(),
7681 buffer.clone(),
7682 cx.clone(),
7683 )
7684 .await?;
7685
7686 let all_actions = lsp_store
7687 .update(&mut cx, |project, cx| {
7688 project.request_multiple_lsp_locally(
7689 &buffer,
7690 Some(get_code_actions.range.start),
7691 get_code_actions,
7692 cx,
7693 )
7694 })?
7695 .await
7696 .into_iter();
7697
7698 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7699 responses: all_actions
7700 .map(|(server_id, code_actions)| proto::LspResponse {
7701 server_id: server_id.to_proto(),
7702 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
7703 GetCodeActions::response_to_proto(
7704 code_actions,
7705 project,
7706 sender_id,
7707 &buffer_version,
7708 cx,
7709 ),
7710 )),
7711 })
7712 .collect(),
7713 })
7714 }
7715 Some(proto::multi_lsp_query::Request::GetSignatureHelp(message)) => {
7716 buffer
7717 .update(&mut cx, |buffer, _| {
7718 buffer.wait_for_version(deserialize_version(&message.version))
7719 })?
7720 .await?;
7721 let get_signature_help = GetSignatureHelp::from_proto(
7722 message,
7723 lsp_store.clone(),
7724 buffer.clone(),
7725 cx.clone(),
7726 )
7727 .await?;
7728
7729 let all_signatures = lsp_store
7730 .update(&mut cx, |project, cx| {
7731 project.request_multiple_lsp_locally(
7732 &buffer,
7733 Some(get_signature_help.position),
7734 get_signature_help,
7735 cx,
7736 )
7737 })?
7738 .await
7739 .into_iter();
7740
7741 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7742 responses: all_signatures
7743 .map(|(server_id, signature_help)| proto::LspResponse {
7744 server_id: server_id.to_proto(),
7745 response: Some(
7746 proto::lsp_response::Response::GetSignatureHelpResponse(
7747 GetSignatureHelp::response_to_proto(
7748 signature_help,
7749 project,
7750 sender_id,
7751 &buffer_version,
7752 cx,
7753 ),
7754 ),
7755 ),
7756 })
7757 .collect(),
7758 })
7759 }
7760 Some(proto::multi_lsp_query::Request::GetCodeLens(message)) => {
7761 buffer
7762 .update(&mut cx, |buffer, _| {
7763 buffer.wait_for_version(deserialize_version(&message.version))
7764 })?
7765 .await?;
7766 let get_code_lens =
7767 GetCodeLens::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7768 .await?;
7769
7770 let code_lens_actions = lsp_store
7771 .update(&mut cx, |project, cx| {
7772 project.request_multiple_lsp_locally(
7773 &buffer,
7774 None::<usize>,
7775 get_code_lens,
7776 cx,
7777 )
7778 })?
7779 .await
7780 .into_iter();
7781
7782 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7783 responses: code_lens_actions
7784 .map(|(server_id, actions)| proto::LspResponse {
7785 server_id: server_id.to_proto(),
7786 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
7787 GetCodeLens::response_to_proto(
7788 actions,
7789 project,
7790 sender_id,
7791 &buffer_version,
7792 cx,
7793 ),
7794 )),
7795 })
7796 .collect(),
7797 })
7798 }
7799 Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(message)) => {
7800 buffer
7801 .update(&mut cx, |buffer, _| {
7802 buffer.wait_for_version(deserialize_version(&message.version))
7803 })?
7804 .await?;
7805 lsp_store
7806 .update(&mut cx, |lsp_store, cx| {
7807 lsp_store.pull_diagnostics_for_buffer(buffer, cx)
7808 })?
7809 .await?;
7810 // `pull_diagnostics_for_buffer` will merge in the new diagnostics and send them to the client.
7811 // The client cannot merge anything into its non-local LspStore, so we do not need to return anything.
7812 Ok(proto::MultiLspQueryResponse {
7813 responses: Vec::new(),
7814 })
7815 }
7816 Some(proto::multi_lsp_query::Request::GetDocumentColor(message)) => {
7817 buffer
7818 .update(&mut cx, |buffer, _| {
7819 buffer.wait_for_version(deserialize_version(&message.version))
7820 })?
7821 .await?;
7822 let get_document_color = GetDocumentColor::from_proto(
7823 message,
7824 lsp_store.clone(),
7825 buffer.clone(),
7826 cx.clone(),
7827 )
7828 .await?;
7829
7830 let all_colors = lsp_store
7831 .update(&mut cx, |project, cx| {
7832 project.request_multiple_lsp_locally(
7833 &buffer,
7834 None::<usize>,
7835 get_document_color,
7836 cx,
7837 )
7838 })?
7839 .await
7840 .into_iter();
7841
7842 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7843 responses: all_colors
7844 .map(|(server_id, colors)| proto::LspResponse {
7845 server_id: server_id.to_proto(),
7846 response: Some(
7847 proto::lsp_response::Response::GetDocumentColorResponse(
7848 GetDocumentColor::response_to_proto(
7849 colors,
7850 project,
7851 sender_id,
7852 &buffer_version,
7853 cx,
7854 ),
7855 ),
7856 ),
7857 })
7858 .collect(),
7859 })
7860 }
7861 None => anyhow::bail!("empty multi lsp query request"),
7862 }
7863 }
7864
7865 async fn handle_apply_code_action(
7866 this: Entity<Self>,
7867 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7868 mut cx: AsyncApp,
7869 ) -> Result<proto::ApplyCodeActionResponse> {
7870 let sender_id = envelope.original_sender_id().unwrap_or_default();
7871 let action =
7872 Self::deserialize_code_action(envelope.payload.action.context("invalid action")?)?;
7873 let apply_code_action = this.update(&mut cx, |this, cx| {
7874 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7875 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7876 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
7877 })??;
7878
7879 let project_transaction = apply_code_action.await?;
7880 let project_transaction = this.update(&mut cx, |this, cx| {
7881 this.buffer_store.update(cx, |buffer_store, cx| {
7882 buffer_store.serialize_project_transaction_for_peer(
7883 project_transaction,
7884 sender_id,
7885 cx,
7886 )
7887 })
7888 })?;
7889 Ok(proto::ApplyCodeActionResponse {
7890 transaction: Some(project_transaction),
7891 })
7892 }
7893
7894 async fn handle_register_buffer_with_language_servers(
7895 this: Entity<Self>,
7896 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
7897 mut cx: AsyncApp,
7898 ) -> Result<proto::Ack> {
7899 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7900 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
7901 this.update(&mut cx, |this, cx| {
7902 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
7903 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
7904 project_id: upstream_project_id,
7905 buffer_id: buffer_id.to_proto(),
7906 only_servers: envelope.payload.only_servers,
7907 });
7908 }
7909
7910 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
7911 anyhow::bail!("buffer is not open");
7912 };
7913
7914 let handle = this.register_buffer_with_language_servers(
7915 &buffer,
7916 envelope
7917 .payload
7918 .only_servers
7919 .into_iter()
7920 .filter_map(|selector| {
7921 Some(match selector.selector? {
7922 proto::language_server_selector::Selector::ServerId(server_id) => {
7923 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
7924 }
7925 proto::language_server_selector::Selector::Name(name) => {
7926 LanguageServerSelector::Name(LanguageServerName(
7927 SharedString::from(name),
7928 ))
7929 }
7930 })
7931 })
7932 .collect(),
7933 false,
7934 cx,
7935 );
7936 this.buffer_store().update(cx, |buffer_store, _| {
7937 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
7938 });
7939
7940 Ok(())
7941 })??;
7942 Ok(proto::Ack {})
7943 }
7944
7945 async fn handle_language_server_id_for_name(
7946 lsp_store: Entity<Self>,
7947 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7948 mut cx: AsyncApp,
7949 ) -> Result<proto::LanguageServerIdForNameResponse> {
7950 let name = &envelope.payload.name;
7951 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7952 lsp_store
7953 .update(&mut cx, |lsp_store, cx| {
7954 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7955 let server_id = buffer.update(cx, |buffer, cx| {
7956 lsp_store
7957 .language_servers_for_local_buffer(buffer, cx)
7958 .find_map(|(adapter, server)| {
7959 if adapter.name.0.as_ref() == name {
7960 Some(server.server_id())
7961 } else {
7962 None
7963 }
7964 })
7965 });
7966 Ok(server_id)
7967 })?
7968 .map(|server_id| proto::LanguageServerIdForNameResponse {
7969 server_id: server_id.map(|id| id.to_proto()),
7970 })
7971 }
7972
7973 async fn handle_rename_project_entry(
7974 this: Entity<Self>,
7975 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7976 mut cx: AsyncApp,
7977 ) -> Result<proto::ProjectEntryResponse> {
7978 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7979 let (worktree_id, worktree, old_path, is_dir) = this
7980 .update(&mut cx, |this, cx| {
7981 this.worktree_store
7982 .read(cx)
7983 .worktree_and_entry_for_id(entry_id, cx)
7984 .map(|(worktree, entry)| {
7985 (
7986 worktree.read(cx).id(),
7987 worktree,
7988 entry.path.clone(),
7989 entry.is_dir(),
7990 )
7991 })
7992 })?
7993 .context("worktree not found")?;
7994 let (old_abs_path, new_abs_path) = {
7995 let root_path = worktree.read_with(&mut cx, |this, _| this.abs_path())?;
7996 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
7997 (root_path.join(&old_path), root_path.join(&new_path))
7998 };
7999
8000 Self::will_rename_entry(
8001 this.downgrade(),
8002 worktree_id,
8003 &old_abs_path,
8004 &new_abs_path,
8005 is_dir,
8006 cx.clone(),
8007 )
8008 .await;
8009 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
8010 this.read_with(&mut cx, |this, _| {
8011 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
8012 })
8013 .ok();
8014 response
8015 }
8016
8017 async fn handle_update_diagnostic_summary(
8018 this: Entity<Self>,
8019 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
8020 mut cx: AsyncApp,
8021 ) -> Result<()> {
8022 this.update(&mut cx, |this, cx| {
8023 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8024 if let Some(message) = envelope.payload.summary {
8025 let project_path = ProjectPath {
8026 worktree_id,
8027 path: Arc::<Path>::from_proto(message.path),
8028 };
8029 let path = project_path.path.clone();
8030 let server_id = LanguageServerId(message.language_server_id as usize);
8031 let summary = DiagnosticSummary {
8032 error_count: message.error_count as usize,
8033 warning_count: message.warning_count as usize,
8034 };
8035
8036 if summary.is_empty() {
8037 if let Some(worktree_summaries) =
8038 this.diagnostic_summaries.get_mut(&worktree_id)
8039 {
8040 if let Some(summaries) = worktree_summaries.get_mut(&path) {
8041 summaries.remove(&server_id);
8042 if summaries.is_empty() {
8043 worktree_summaries.remove(&path);
8044 }
8045 }
8046 }
8047 } else {
8048 this.diagnostic_summaries
8049 .entry(worktree_id)
8050 .or_default()
8051 .entry(path)
8052 .or_default()
8053 .insert(server_id, summary);
8054 }
8055 if let Some((downstream_client, project_id)) = &this.downstream_client {
8056 downstream_client
8057 .send(proto::UpdateDiagnosticSummary {
8058 project_id: *project_id,
8059 worktree_id: worktree_id.to_proto(),
8060 summary: Some(proto::DiagnosticSummary {
8061 path: project_path.path.as_ref().to_proto(),
8062 language_server_id: server_id.0 as u64,
8063 error_count: summary.error_count as u32,
8064 warning_count: summary.warning_count as u32,
8065 }),
8066 })
8067 .log_err();
8068 }
8069 cx.emit(LspStoreEvent::DiagnosticsUpdated {
8070 language_server_id: LanguageServerId(message.language_server_id as usize),
8071 path: project_path,
8072 });
8073 }
8074 Ok(())
8075 })?
8076 }
8077
8078 async fn handle_start_language_server(
8079 this: Entity<Self>,
8080 envelope: TypedEnvelope<proto::StartLanguageServer>,
8081 mut cx: AsyncApp,
8082 ) -> Result<()> {
8083 let server = envelope.payload.server.context("invalid server")?;
8084
8085 this.update(&mut cx, |this, cx| {
8086 let server_id = LanguageServerId(server.id as usize);
8087 this.language_server_statuses.insert(
8088 server_id,
8089 LanguageServerStatus {
8090 name: server.name.clone(),
8091 pending_work: Default::default(),
8092 has_pending_diagnostic_updates: false,
8093 progress_tokens: Default::default(),
8094 },
8095 );
8096 cx.emit(LspStoreEvent::LanguageServerAdded(
8097 server_id,
8098 LanguageServerName(server.name.into()),
8099 server.worktree_id.map(WorktreeId::from_proto),
8100 ));
8101 cx.notify();
8102 })?;
8103 Ok(())
8104 }
8105
8106 async fn handle_update_language_server(
8107 lsp_store: Entity<Self>,
8108 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
8109 mut cx: AsyncApp,
8110 ) -> Result<()> {
8111 lsp_store.update(&mut cx, |lsp_store, cx| {
8112 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8113
8114 match envelope.payload.variant.context("invalid variant")? {
8115 proto::update_language_server::Variant::WorkStart(payload) => {
8116 lsp_store.on_lsp_work_start(
8117 language_server_id,
8118 payload.token,
8119 LanguageServerProgress {
8120 title: payload.title,
8121 is_disk_based_diagnostics_progress: false,
8122 is_cancellable: payload.is_cancellable.unwrap_or(false),
8123 message: payload.message,
8124 percentage: payload.percentage.map(|p| p as usize),
8125 last_update_at: cx.background_executor().now(),
8126 },
8127 cx,
8128 );
8129 }
8130 proto::update_language_server::Variant::WorkProgress(payload) => {
8131 lsp_store.on_lsp_work_progress(
8132 language_server_id,
8133 payload.token,
8134 LanguageServerProgress {
8135 title: None,
8136 is_disk_based_diagnostics_progress: false,
8137 is_cancellable: payload.is_cancellable.unwrap_or(false),
8138 message: payload.message,
8139 percentage: payload.percentage.map(|p| p as usize),
8140 last_update_at: cx.background_executor().now(),
8141 },
8142 cx,
8143 );
8144 }
8145
8146 proto::update_language_server::Variant::WorkEnd(payload) => {
8147 lsp_store.on_lsp_work_end(language_server_id, payload.token, cx);
8148 }
8149
8150 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
8151 lsp_store.disk_based_diagnostics_started(language_server_id, cx);
8152 }
8153
8154 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
8155 lsp_store.disk_based_diagnostics_finished(language_server_id, cx)
8156 }
8157
8158 non_lsp @ proto::update_language_server::Variant::StatusUpdate(_)
8159 | non_lsp @ proto::update_language_server::Variant::RegisteredForBuffer(_) => {
8160 cx.emit(LspStoreEvent::LanguageServerUpdate {
8161 language_server_id,
8162 name: envelope
8163 .payload
8164 .server_name
8165 .map(SharedString::new)
8166 .map(LanguageServerName),
8167 message: non_lsp,
8168 });
8169 }
8170 }
8171
8172 Ok(())
8173 })?
8174 }
8175
8176 async fn handle_language_server_log(
8177 this: Entity<Self>,
8178 envelope: TypedEnvelope<proto::LanguageServerLog>,
8179 mut cx: AsyncApp,
8180 ) -> Result<()> {
8181 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8182 let log_type = envelope
8183 .payload
8184 .log_type
8185 .map(LanguageServerLogType::from_proto)
8186 .context("invalid language server log type")?;
8187
8188 let message = envelope.payload.message;
8189
8190 this.update(&mut cx, |_, cx| {
8191 cx.emit(LspStoreEvent::LanguageServerLog(
8192 language_server_id,
8193 log_type,
8194 message,
8195 ));
8196 })
8197 }
8198
8199 async fn handle_lsp_ext_cancel_flycheck(
8200 lsp_store: Entity<Self>,
8201 envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
8202 mut cx: AsyncApp,
8203 ) -> Result<proto::Ack> {
8204 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8205 lsp_store.read_with(&mut cx, |lsp_store, _| {
8206 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8207 server
8208 .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
8209 .context("handling lsp ext cancel flycheck")
8210 } else {
8211 anyhow::Ok(())
8212 }
8213 })??;
8214
8215 Ok(proto::Ack {})
8216 }
8217
8218 async fn handle_lsp_ext_run_flycheck(
8219 lsp_store: Entity<Self>,
8220 envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
8221 mut cx: AsyncApp,
8222 ) -> Result<proto::Ack> {
8223 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8224 lsp_store.update(&mut cx, |lsp_store, cx| {
8225 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8226 let text_document = if envelope.payload.current_file_only {
8227 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8228 lsp_store
8229 .buffer_store()
8230 .read(cx)
8231 .get(buffer_id)
8232 .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
8233 .map(|path| make_text_document_identifier(&path))
8234 .transpose()?
8235 } else {
8236 None
8237 };
8238 server
8239 .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
8240 &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
8241 )
8242 .context("handling lsp ext run flycheck")
8243 } else {
8244 anyhow::Ok(())
8245 }
8246 })??;
8247
8248 Ok(proto::Ack {})
8249 }
8250
8251 async fn handle_lsp_ext_clear_flycheck(
8252 lsp_store: Entity<Self>,
8253 envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
8254 mut cx: AsyncApp,
8255 ) -> Result<proto::Ack> {
8256 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8257 lsp_store.read_with(&mut cx, |lsp_store, _| {
8258 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8259 server
8260 .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
8261 .context("handling lsp ext clear flycheck")
8262 } else {
8263 anyhow::Ok(())
8264 }
8265 })??;
8266
8267 Ok(proto::Ack {})
8268 }
8269
8270 pub fn disk_based_diagnostics_started(
8271 &mut self,
8272 language_server_id: LanguageServerId,
8273 cx: &mut Context<Self>,
8274 ) {
8275 if let Some(language_server_status) =
8276 self.language_server_statuses.get_mut(&language_server_id)
8277 {
8278 language_server_status.has_pending_diagnostic_updates = true;
8279 }
8280
8281 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
8282 cx.emit(LspStoreEvent::LanguageServerUpdate {
8283 language_server_id,
8284 name: self
8285 .language_server_adapter_for_id(language_server_id)
8286 .map(|adapter| adapter.name()),
8287 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
8288 Default::default(),
8289 ),
8290 })
8291 }
8292
8293 pub fn disk_based_diagnostics_finished(
8294 &mut self,
8295 language_server_id: LanguageServerId,
8296 cx: &mut Context<Self>,
8297 ) {
8298 if let Some(language_server_status) =
8299 self.language_server_statuses.get_mut(&language_server_id)
8300 {
8301 language_server_status.has_pending_diagnostic_updates = false;
8302 }
8303
8304 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
8305 cx.emit(LspStoreEvent::LanguageServerUpdate {
8306 language_server_id,
8307 name: self
8308 .language_server_adapter_for_id(language_server_id)
8309 .map(|adapter| adapter.name()),
8310 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
8311 Default::default(),
8312 ),
8313 })
8314 }
8315
8316 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
8317 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
8318 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
8319 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
8320 // the language server might take some time to publish diagnostics.
8321 fn simulate_disk_based_diagnostics_events_if_needed(
8322 &mut self,
8323 language_server_id: LanguageServerId,
8324 cx: &mut Context<Self>,
8325 ) {
8326 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
8327
8328 let Some(LanguageServerState::Running {
8329 simulate_disk_based_diagnostics_completion,
8330 adapter,
8331 ..
8332 }) = self
8333 .as_local_mut()
8334 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
8335 else {
8336 return;
8337 };
8338
8339 if adapter.disk_based_diagnostics_progress_token.is_some() {
8340 return;
8341 }
8342
8343 let prev_task =
8344 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
8345 cx.background_executor()
8346 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
8347 .await;
8348
8349 this.update(cx, |this, cx| {
8350 this.disk_based_diagnostics_finished(language_server_id, cx);
8351
8352 if let Some(LanguageServerState::Running {
8353 simulate_disk_based_diagnostics_completion,
8354 ..
8355 }) = this.as_local_mut().and_then(|local_store| {
8356 local_store.language_servers.get_mut(&language_server_id)
8357 }) {
8358 *simulate_disk_based_diagnostics_completion = None;
8359 }
8360 })
8361 .ok();
8362 }));
8363
8364 if prev_task.is_none() {
8365 self.disk_based_diagnostics_started(language_server_id, cx);
8366 }
8367 }
8368
8369 pub fn language_server_statuses(
8370 &self,
8371 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
8372 self.language_server_statuses
8373 .iter()
8374 .map(|(key, value)| (*key, value))
8375 }
8376
8377 pub(super) fn did_rename_entry(
8378 &self,
8379 worktree_id: WorktreeId,
8380 old_path: &Path,
8381 new_path: &Path,
8382 is_dir: bool,
8383 ) {
8384 maybe!({
8385 let local_store = self.as_local()?;
8386
8387 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
8388 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
8389
8390 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8391 let Some(filter) = local_store
8392 .language_server_paths_watched_for_rename
8393 .get(&language_server.server_id())
8394 else {
8395 continue;
8396 };
8397
8398 if filter.should_send_did_rename(&old_uri, is_dir) {
8399 language_server
8400 .notify::<DidRenameFiles>(&RenameFilesParams {
8401 files: vec![FileRename {
8402 old_uri: old_uri.clone(),
8403 new_uri: new_uri.clone(),
8404 }],
8405 })
8406 .ok();
8407 }
8408 }
8409 Some(())
8410 });
8411 }
8412
8413 pub(super) fn will_rename_entry(
8414 this: WeakEntity<Self>,
8415 worktree_id: WorktreeId,
8416 old_path: &Path,
8417 new_path: &Path,
8418 is_dir: bool,
8419 cx: AsyncApp,
8420 ) -> Task<()> {
8421 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
8422 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
8423 cx.spawn(async move |cx| {
8424 let mut tasks = vec![];
8425 this.update(cx, |this, cx| {
8426 let local_store = this.as_local()?;
8427 let old_uri = old_uri?;
8428 let new_uri = new_uri?;
8429 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8430 let Some(filter) = local_store
8431 .language_server_paths_watched_for_rename
8432 .get(&language_server.server_id())
8433 else {
8434 continue;
8435 };
8436 let Some(adapter) =
8437 this.language_server_adapter_for_id(language_server.server_id())
8438 else {
8439 continue;
8440 };
8441 if filter.should_send_will_rename(&old_uri, is_dir) {
8442 let apply_edit = cx.spawn({
8443 let old_uri = old_uri.clone();
8444 let new_uri = new_uri.clone();
8445 let language_server = language_server.clone();
8446 async move |this, cx| {
8447 let edit = language_server
8448 .request::<WillRenameFiles>(RenameFilesParams {
8449 files: vec![FileRename { old_uri, new_uri }],
8450 })
8451 .await
8452 .into_response()
8453 .context("will rename files")
8454 .log_err()
8455 .flatten()?;
8456
8457 LocalLspStore::deserialize_workspace_edit(
8458 this.upgrade()?,
8459 edit,
8460 false,
8461 adapter.clone(),
8462 language_server.clone(),
8463 cx,
8464 )
8465 .await
8466 .ok();
8467 Some(())
8468 }
8469 });
8470 tasks.push(apply_edit);
8471 }
8472 }
8473 Some(())
8474 })
8475 .ok()
8476 .flatten();
8477 for task in tasks {
8478 // Await on tasks sequentially so that the order of application of edits is deterministic
8479 // (at least with regards to the order of registration of language servers)
8480 task.await;
8481 }
8482 })
8483 }
8484
8485 fn lsp_notify_abs_paths_changed(
8486 &mut self,
8487 server_id: LanguageServerId,
8488 changes: Vec<PathEvent>,
8489 ) {
8490 maybe!({
8491 let server = self.language_server_for_id(server_id)?;
8492 let changes = changes
8493 .into_iter()
8494 .filter_map(|event| {
8495 let typ = match event.kind? {
8496 PathEventKind::Created => lsp::FileChangeType::CREATED,
8497 PathEventKind::Removed => lsp::FileChangeType::DELETED,
8498 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
8499 };
8500 Some(lsp::FileEvent {
8501 uri: file_path_to_lsp_url(&event.path).log_err()?,
8502 typ,
8503 })
8504 })
8505 .collect::<Vec<_>>();
8506 if !changes.is_empty() {
8507 server
8508 .notify::<lsp::notification::DidChangeWatchedFiles>(
8509 &lsp::DidChangeWatchedFilesParams { changes },
8510 )
8511 .ok();
8512 }
8513 Some(())
8514 });
8515 }
8516
8517 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8518 let local_lsp_store = self.as_local()?;
8519 if let Some(LanguageServerState::Running { server, .. }) =
8520 local_lsp_store.language_servers.get(&id)
8521 {
8522 Some(server.clone())
8523 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
8524 Some(Arc::clone(server))
8525 } else {
8526 None
8527 }
8528 }
8529
8530 fn on_lsp_progress(
8531 &mut self,
8532 progress: lsp::ProgressParams,
8533 language_server_id: LanguageServerId,
8534 disk_based_diagnostics_progress_token: Option<String>,
8535 cx: &mut Context<Self>,
8536 ) {
8537 let token = match progress.token {
8538 lsp::NumberOrString::String(token) => token,
8539 lsp::NumberOrString::Number(token) => {
8540 log::info!("skipping numeric progress token {}", token);
8541 return;
8542 }
8543 };
8544
8545 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
8546 let language_server_status =
8547 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8548 status
8549 } else {
8550 return;
8551 };
8552
8553 if !language_server_status.progress_tokens.contains(&token) {
8554 return;
8555 }
8556
8557 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
8558 .as_ref()
8559 .map_or(false, |disk_based_token| {
8560 token.starts_with(disk_based_token)
8561 });
8562
8563 match progress {
8564 lsp::WorkDoneProgress::Begin(report) => {
8565 if is_disk_based_diagnostics_progress {
8566 self.disk_based_diagnostics_started(language_server_id, cx);
8567 }
8568 self.on_lsp_work_start(
8569 language_server_id,
8570 token.clone(),
8571 LanguageServerProgress {
8572 title: Some(report.title),
8573 is_disk_based_diagnostics_progress,
8574 is_cancellable: report.cancellable.unwrap_or(false),
8575 message: report.message.clone(),
8576 percentage: report.percentage.map(|p| p as usize),
8577 last_update_at: cx.background_executor().now(),
8578 },
8579 cx,
8580 );
8581 }
8582 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
8583 language_server_id,
8584 token,
8585 LanguageServerProgress {
8586 title: None,
8587 is_disk_based_diagnostics_progress,
8588 is_cancellable: report.cancellable.unwrap_or(false),
8589 message: report.message,
8590 percentage: report.percentage.map(|p| p as usize),
8591 last_update_at: cx.background_executor().now(),
8592 },
8593 cx,
8594 ),
8595 lsp::WorkDoneProgress::End(_) => {
8596 language_server_status.progress_tokens.remove(&token);
8597 self.on_lsp_work_end(language_server_id, token.clone(), cx);
8598 if is_disk_based_diagnostics_progress {
8599 self.disk_based_diagnostics_finished(language_server_id, cx);
8600 }
8601 }
8602 }
8603 }
8604
8605 fn on_lsp_work_start(
8606 &mut self,
8607 language_server_id: LanguageServerId,
8608 token: String,
8609 progress: LanguageServerProgress,
8610 cx: &mut Context<Self>,
8611 ) {
8612 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8613 status.pending_work.insert(token.clone(), progress.clone());
8614 cx.notify();
8615 }
8616 cx.emit(LspStoreEvent::LanguageServerUpdate {
8617 language_server_id,
8618 name: self
8619 .language_server_adapter_for_id(language_server_id)
8620 .map(|adapter| adapter.name()),
8621 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
8622 token,
8623 title: progress.title,
8624 message: progress.message,
8625 percentage: progress.percentage.map(|p| p as u32),
8626 is_cancellable: Some(progress.is_cancellable),
8627 }),
8628 })
8629 }
8630
8631 fn on_lsp_work_progress(
8632 &mut self,
8633 language_server_id: LanguageServerId,
8634 token: String,
8635 progress: LanguageServerProgress,
8636 cx: &mut Context<Self>,
8637 ) {
8638 let mut did_update = false;
8639 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8640 match status.pending_work.entry(token.clone()) {
8641 btree_map::Entry::Vacant(entry) => {
8642 entry.insert(progress.clone());
8643 did_update = true;
8644 }
8645 btree_map::Entry::Occupied(mut entry) => {
8646 let entry = entry.get_mut();
8647 if (progress.last_update_at - entry.last_update_at)
8648 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
8649 {
8650 entry.last_update_at = progress.last_update_at;
8651 if progress.message.is_some() {
8652 entry.message = progress.message.clone();
8653 }
8654 if progress.percentage.is_some() {
8655 entry.percentage = progress.percentage;
8656 }
8657 if progress.is_cancellable != entry.is_cancellable {
8658 entry.is_cancellable = progress.is_cancellable;
8659 }
8660 did_update = true;
8661 }
8662 }
8663 }
8664 }
8665
8666 if did_update {
8667 cx.emit(LspStoreEvent::LanguageServerUpdate {
8668 language_server_id,
8669 name: self
8670 .language_server_adapter_for_id(language_server_id)
8671 .map(|adapter| adapter.name()),
8672 message: proto::update_language_server::Variant::WorkProgress(
8673 proto::LspWorkProgress {
8674 token,
8675 message: progress.message,
8676 percentage: progress.percentage.map(|p| p as u32),
8677 is_cancellable: Some(progress.is_cancellable),
8678 },
8679 ),
8680 })
8681 }
8682 }
8683
8684 fn on_lsp_work_end(
8685 &mut self,
8686 language_server_id: LanguageServerId,
8687 token: String,
8688 cx: &mut Context<Self>,
8689 ) {
8690 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8691 if let Some(work) = status.pending_work.remove(&token) {
8692 if !work.is_disk_based_diagnostics_progress {
8693 cx.emit(LspStoreEvent::RefreshInlayHints);
8694 }
8695 }
8696 cx.notify();
8697 }
8698
8699 cx.emit(LspStoreEvent::LanguageServerUpdate {
8700 language_server_id,
8701 name: self
8702 .language_server_adapter_for_id(language_server_id)
8703 .map(|adapter| adapter.name()),
8704 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
8705 })
8706 }
8707
8708 pub async fn handle_resolve_completion_documentation(
8709 this: Entity<Self>,
8710 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8711 mut cx: AsyncApp,
8712 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8713 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8714
8715 let completion = this
8716 .read_with(&cx, |this, cx| {
8717 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8718 let server = this
8719 .language_server_for_id(id)
8720 .with_context(|| format!("No language server {id}"))?;
8721
8722 anyhow::Ok(cx.background_spawn(async move {
8723 let can_resolve = server
8724 .capabilities()
8725 .completion_provider
8726 .as_ref()
8727 .and_then(|options| options.resolve_provider)
8728 .unwrap_or(false);
8729 if can_resolve {
8730 server
8731 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
8732 .await
8733 .into_response()
8734 .context("resolve completion item")
8735 } else {
8736 anyhow::Ok(lsp_completion)
8737 }
8738 }))
8739 })??
8740 .await?;
8741
8742 let mut documentation_is_markdown = false;
8743 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
8744 let documentation = match completion.documentation {
8745 Some(lsp::Documentation::String(text)) => text,
8746
8747 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8748 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
8749 value
8750 }
8751
8752 _ => String::new(),
8753 };
8754
8755 // If we have a new buffer_id, that means we're talking to a new client
8756 // and want to check for new text_edits in the completion too.
8757 let mut old_replace_start = None;
8758 let mut old_replace_end = None;
8759 let mut old_insert_start = None;
8760 let mut old_insert_end = None;
8761 let mut new_text = String::default();
8762 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
8763 let buffer_snapshot = this.update(&mut cx, |this, cx| {
8764 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8765 anyhow::Ok(buffer.read(cx).snapshot())
8766 })??;
8767
8768 if let Some(text_edit) = completion.text_edit.as_ref() {
8769 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
8770
8771 if let Some(mut edit) = edit {
8772 LineEnding::normalize(&mut edit.new_text);
8773
8774 new_text = edit.new_text;
8775 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
8776 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
8777 if let Some(insert_range) = edit.insert_range {
8778 old_insert_start = Some(serialize_anchor(&insert_range.start));
8779 old_insert_end = Some(serialize_anchor(&insert_range.end));
8780 }
8781 }
8782 }
8783 }
8784
8785 Ok(proto::ResolveCompletionDocumentationResponse {
8786 documentation,
8787 documentation_is_markdown,
8788 old_replace_start,
8789 old_replace_end,
8790 new_text,
8791 lsp_completion,
8792 old_insert_start,
8793 old_insert_end,
8794 })
8795 }
8796
8797 async fn handle_on_type_formatting(
8798 this: Entity<Self>,
8799 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8800 mut cx: AsyncApp,
8801 ) -> Result<proto::OnTypeFormattingResponse> {
8802 let on_type_formatting = this.update(&mut cx, |this, cx| {
8803 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8804 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8805 let position = envelope
8806 .payload
8807 .position
8808 .and_then(deserialize_anchor)
8809 .context("invalid position")?;
8810 anyhow::Ok(this.apply_on_type_formatting(
8811 buffer,
8812 position,
8813 envelope.payload.trigger.clone(),
8814 cx,
8815 ))
8816 })??;
8817
8818 let transaction = on_type_formatting
8819 .await?
8820 .as_ref()
8821 .map(language::proto::serialize_transaction);
8822 Ok(proto::OnTypeFormattingResponse { transaction })
8823 }
8824
8825 async fn handle_refresh_inlay_hints(
8826 this: Entity<Self>,
8827 _: TypedEnvelope<proto::RefreshInlayHints>,
8828 mut cx: AsyncApp,
8829 ) -> Result<proto::Ack> {
8830 this.update(&mut cx, |_, cx| {
8831 cx.emit(LspStoreEvent::RefreshInlayHints);
8832 })?;
8833 Ok(proto::Ack {})
8834 }
8835
8836 async fn handle_pull_workspace_diagnostics(
8837 lsp_store: Entity<Self>,
8838 envelope: TypedEnvelope<proto::PullWorkspaceDiagnostics>,
8839 mut cx: AsyncApp,
8840 ) -> Result<proto::Ack> {
8841 let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
8842 lsp_store.update(&mut cx, |lsp_store, _| {
8843 lsp_store.pull_workspace_diagnostics(server_id);
8844 })?;
8845 Ok(proto::Ack {})
8846 }
8847
8848 async fn handle_inlay_hints(
8849 this: Entity<Self>,
8850 envelope: TypedEnvelope<proto::InlayHints>,
8851 mut cx: AsyncApp,
8852 ) -> Result<proto::InlayHintsResponse> {
8853 let sender_id = envelope.original_sender_id().unwrap_or_default();
8854 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8855 let buffer = this.update(&mut cx, |this, cx| {
8856 this.buffer_store.read(cx).get_existing(buffer_id)
8857 })??;
8858 buffer
8859 .update(&mut cx, |buffer, _| {
8860 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8861 })?
8862 .await
8863 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8864
8865 let start = envelope
8866 .payload
8867 .start
8868 .and_then(deserialize_anchor)
8869 .context("missing range start")?;
8870 let end = envelope
8871 .payload
8872 .end
8873 .and_then(deserialize_anchor)
8874 .context("missing range end")?;
8875 let buffer_hints = this
8876 .update(&mut cx, |lsp_store, cx| {
8877 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
8878 })?
8879 .await
8880 .context("inlay hints fetch")?;
8881
8882 this.update(&mut cx, |project, cx| {
8883 InlayHints::response_to_proto(
8884 buffer_hints,
8885 project,
8886 sender_id,
8887 &buffer.read(cx).version(),
8888 cx,
8889 )
8890 })
8891 }
8892
8893 async fn handle_get_color_presentation(
8894 lsp_store: Entity<Self>,
8895 envelope: TypedEnvelope<proto::GetColorPresentation>,
8896 mut cx: AsyncApp,
8897 ) -> Result<proto::GetColorPresentationResponse> {
8898 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8899 let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
8900 lsp_store.buffer_store.read(cx).get_existing(buffer_id)
8901 })??;
8902
8903 let color = envelope
8904 .payload
8905 .color
8906 .context("invalid color resolve request")?;
8907 let start = color
8908 .lsp_range_start
8909 .context("invalid color resolve request")?;
8910 let end = color
8911 .lsp_range_end
8912 .context("invalid color resolve request")?;
8913
8914 let color = DocumentColor {
8915 lsp_range: lsp::Range {
8916 start: point_to_lsp(PointUtf16::new(start.row, start.column)),
8917 end: point_to_lsp(PointUtf16::new(end.row, end.column)),
8918 },
8919 color: lsp::Color {
8920 red: color.red,
8921 green: color.green,
8922 blue: color.blue,
8923 alpha: color.alpha,
8924 },
8925 resolved: false,
8926 color_presentations: Vec::new(),
8927 };
8928 let resolved_color = lsp_store
8929 .update(&mut cx, |lsp_store, cx| {
8930 lsp_store.resolve_color_presentation(
8931 color,
8932 buffer.clone(),
8933 LanguageServerId(envelope.payload.server_id as usize),
8934 cx,
8935 )
8936 })?
8937 .await
8938 .context("resolving color presentation")?;
8939
8940 Ok(proto::GetColorPresentationResponse {
8941 presentations: resolved_color
8942 .color_presentations
8943 .into_iter()
8944 .map(|presentation| proto::ColorPresentation {
8945 label: presentation.label,
8946 text_edit: presentation.text_edit.map(serialize_lsp_edit),
8947 additional_text_edits: presentation
8948 .additional_text_edits
8949 .into_iter()
8950 .map(serialize_lsp_edit)
8951 .collect(),
8952 })
8953 .collect(),
8954 })
8955 }
8956
8957 async fn handle_resolve_inlay_hint(
8958 this: Entity<Self>,
8959 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8960 mut cx: AsyncApp,
8961 ) -> Result<proto::ResolveInlayHintResponse> {
8962 let proto_hint = envelope
8963 .payload
8964 .hint
8965 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8966 let hint = InlayHints::proto_to_project_hint(proto_hint)
8967 .context("resolved proto inlay hint conversion")?;
8968 let buffer = this.update(&mut cx, |this, cx| {
8969 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8970 this.buffer_store.read(cx).get_existing(buffer_id)
8971 })??;
8972 let response_hint = this
8973 .update(&mut cx, |this, cx| {
8974 this.resolve_inlay_hint(
8975 hint,
8976 buffer,
8977 LanguageServerId(envelope.payload.language_server_id as usize),
8978 cx,
8979 )
8980 })?
8981 .await
8982 .context("inlay hints fetch")?;
8983 Ok(proto::ResolveInlayHintResponse {
8984 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8985 })
8986 }
8987
8988 async fn handle_refresh_code_lens(
8989 this: Entity<Self>,
8990 _: TypedEnvelope<proto::RefreshCodeLens>,
8991 mut cx: AsyncApp,
8992 ) -> Result<proto::Ack> {
8993 this.update(&mut cx, |_, cx| {
8994 cx.emit(LspStoreEvent::RefreshCodeLens);
8995 })?;
8996 Ok(proto::Ack {})
8997 }
8998
8999 async fn handle_open_buffer_for_symbol(
9000 this: Entity<Self>,
9001 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
9002 mut cx: AsyncApp,
9003 ) -> Result<proto::OpenBufferForSymbolResponse> {
9004 let peer_id = envelope.original_sender_id().unwrap_or_default();
9005 let symbol = envelope.payload.symbol.context("invalid symbol")?;
9006 let symbol = Self::deserialize_symbol(symbol)?;
9007 let symbol = this.read_with(&mut cx, |this, _| {
9008 let signature = this.symbol_signature(&symbol.path);
9009 anyhow::ensure!(signature == symbol.signature, "invalid symbol signature");
9010 Ok(symbol)
9011 })??;
9012 let buffer = this
9013 .update(&mut cx, |this, cx| {
9014 this.open_buffer_for_symbol(
9015 &Symbol {
9016 language_server_name: symbol.language_server_name,
9017 source_worktree_id: symbol.source_worktree_id,
9018 source_language_server_id: symbol.source_language_server_id,
9019 path: symbol.path,
9020 name: symbol.name,
9021 kind: symbol.kind,
9022 range: symbol.range,
9023 signature: symbol.signature,
9024 label: CodeLabel {
9025 text: Default::default(),
9026 runs: Default::default(),
9027 filter_range: Default::default(),
9028 },
9029 },
9030 cx,
9031 )
9032 })?
9033 .await?;
9034
9035 this.update(&mut cx, |this, cx| {
9036 let is_private = buffer
9037 .read(cx)
9038 .file()
9039 .map(|f| f.is_private())
9040 .unwrap_or_default();
9041 if is_private {
9042 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
9043 } else {
9044 this.buffer_store
9045 .update(cx, |buffer_store, cx| {
9046 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
9047 })
9048 .detach_and_log_err(cx);
9049 let buffer_id = buffer.read(cx).remote_id().to_proto();
9050 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
9051 }
9052 })?
9053 }
9054
9055 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
9056 let mut hasher = Sha256::new();
9057 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
9058 hasher.update(project_path.path.to_string_lossy().as_bytes());
9059 hasher.update(self.nonce.to_be_bytes());
9060 hasher.finalize().as_slice().try_into().unwrap()
9061 }
9062
9063 pub async fn handle_get_project_symbols(
9064 this: Entity<Self>,
9065 envelope: TypedEnvelope<proto::GetProjectSymbols>,
9066 mut cx: AsyncApp,
9067 ) -> Result<proto::GetProjectSymbolsResponse> {
9068 let symbols = this
9069 .update(&mut cx, |this, cx| {
9070 this.symbols(&envelope.payload.query, cx)
9071 })?
9072 .await?;
9073
9074 Ok(proto::GetProjectSymbolsResponse {
9075 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
9076 })
9077 }
9078
9079 pub async fn handle_restart_language_servers(
9080 this: Entity<Self>,
9081 envelope: TypedEnvelope<proto::RestartLanguageServers>,
9082 mut cx: AsyncApp,
9083 ) -> Result<proto::Ack> {
9084 this.update(&mut cx, |lsp_store, cx| {
9085 let buffers =
9086 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9087 lsp_store.restart_language_servers_for_buffers(
9088 buffers,
9089 envelope
9090 .payload
9091 .only_servers
9092 .into_iter()
9093 .filter_map(|selector| {
9094 Some(match selector.selector? {
9095 proto::language_server_selector::Selector::ServerId(server_id) => {
9096 LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
9097 }
9098 proto::language_server_selector::Selector::Name(name) => {
9099 LanguageServerSelector::Name(LanguageServerName(
9100 SharedString::from(name),
9101 ))
9102 }
9103 })
9104 })
9105 .collect(),
9106 cx,
9107 );
9108 })?;
9109
9110 Ok(proto::Ack {})
9111 }
9112
9113 pub async fn handle_stop_language_servers(
9114 lsp_store: Entity<Self>,
9115 envelope: TypedEnvelope<proto::StopLanguageServers>,
9116 mut cx: AsyncApp,
9117 ) -> Result<proto::Ack> {
9118 lsp_store.update(&mut cx, |lsp_store, cx| {
9119 if envelope.payload.all
9120 && envelope.payload.also_servers.is_empty()
9121 && envelope.payload.buffer_ids.is_empty()
9122 {
9123 lsp_store.stop_all_language_servers(cx);
9124 } else {
9125 let buffers =
9126 lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
9127 lsp_store.stop_language_servers_for_buffers(
9128 buffers,
9129 envelope
9130 .payload
9131 .also_servers
9132 .into_iter()
9133 .filter_map(|selector| {
9134 Some(match selector.selector? {
9135 proto::language_server_selector::Selector::ServerId(server_id) => {
9136 LanguageServerSelector::Id(LanguageServerId::from_proto(
9137 server_id,
9138 ))
9139 }
9140 proto::language_server_selector::Selector::Name(name) => {
9141 LanguageServerSelector::Name(LanguageServerName(
9142 SharedString::from(name),
9143 ))
9144 }
9145 })
9146 })
9147 .collect(),
9148 cx,
9149 );
9150 }
9151 })?;
9152
9153 Ok(proto::Ack {})
9154 }
9155
9156 pub async fn handle_cancel_language_server_work(
9157 this: Entity<Self>,
9158 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
9159 mut cx: AsyncApp,
9160 ) -> Result<proto::Ack> {
9161 this.update(&mut cx, |this, cx| {
9162 if let Some(work) = envelope.payload.work {
9163 match work {
9164 proto::cancel_language_server_work::Work::Buffers(buffers) => {
9165 let buffers =
9166 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
9167 this.cancel_language_server_work_for_buffers(buffers, cx);
9168 }
9169 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
9170 let server_id = LanguageServerId::from_proto(work.language_server_id);
9171 this.cancel_language_server_work(server_id, work.token, cx);
9172 }
9173 }
9174 }
9175 })?;
9176
9177 Ok(proto::Ack {})
9178 }
9179
9180 fn buffer_ids_to_buffers(
9181 &mut self,
9182 buffer_ids: impl Iterator<Item = u64>,
9183 cx: &mut Context<Self>,
9184 ) -> Vec<Entity<Buffer>> {
9185 buffer_ids
9186 .into_iter()
9187 .flat_map(|buffer_id| {
9188 self.buffer_store
9189 .read(cx)
9190 .get(BufferId::new(buffer_id).log_err()?)
9191 })
9192 .collect::<Vec<_>>()
9193 }
9194
9195 async fn handle_apply_additional_edits_for_completion(
9196 this: Entity<Self>,
9197 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
9198 mut cx: AsyncApp,
9199 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
9200 let (buffer, completion) = this.update(&mut cx, |this, cx| {
9201 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9202 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
9203 let completion = Self::deserialize_completion(
9204 envelope.payload.completion.context("invalid completion")?,
9205 )?;
9206 anyhow::Ok((buffer, completion))
9207 })??;
9208
9209 let apply_additional_edits = this.update(&mut cx, |this, cx| {
9210 this.apply_additional_edits_for_completion(
9211 buffer,
9212 Rc::new(RefCell::new(Box::new([Completion {
9213 replace_range: completion.replace_range,
9214 new_text: completion.new_text,
9215 source: completion.source,
9216 documentation: None,
9217 label: CodeLabel {
9218 text: Default::default(),
9219 runs: Default::default(),
9220 filter_range: Default::default(),
9221 },
9222 insert_text_mode: None,
9223 icon_path: None,
9224 confirm: None,
9225 }]))),
9226 0,
9227 false,
9228 cx,
9229 )
9230 })?;
9231
9232 Ok(proto::ApplyCompletionAdditionalEditsResponse {
9233 transaction: apply_additional_edits
9234 .await?
9235 .as_ref()
9236 .map(language::proto::serialize_transaction),
9237 })
9238 }
9239
9240 pub fn last_formatting_failure(&self) -> Option<&str> {
9241 self.last_formatting_failure.as_deref()
9242 }
9243
9244 pub fn reset_last_formatting_failure(&mut self) {
9245 self.last_formatting_failure = None;
9246 }
9247
9248 pub fn environment_for_buffer(
9249 &self,
9250 buffer: &Entity<Buffer>,
9251 cx: &mut Context<Self>,
9252 ) -> Shared<Task<Option<HashMap<String, String>>>> {
9253 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
9254 environment.update(cx, |env, cx| {
9255 env.get_buffer_environment(&buffer, &self.worktree_store, cx)
9256 })
9257 } else {
9258 Task::ready(None).shared()
9259 }
9260 }
9261
9262 pub fn format(
9263 &mut self,
9264 buffers: HashSet<Entity<Buffer>>,
9265 target: LspFormatTarget,
9266 push_to_history: bool,
9267 trigger: FormatTrigger,
9268 cx: &mut Context<Self>,
9269 ) -> Task<anyhow::Result<ProjectTransaction>> {
9270 let logger = zlog::scoped!("format");
9271 if let Some(_) = self.as_local() {
9272 zlog::trace!(logger => "Formatting locally");
9273 let logger = zlog::scoped!(logger => "local");
9274 let buffers = buffers
9275 .into_iter()
9276 .map(|buffer_handle| {
9277 let buffer = buffer_handle.read(cx);
9278 let buffer_abs_path = File::from_dyn(buffer.file())
9279 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
9280
9281 (buffer_handle, buffer_abs_path, buffer.remote_id())
9282 })
9283 .collect::<Vec<_>>();
9284
9285 cx.spawn(async move |lsp_store, cx| {
9286 let mut formattable_buffers = Vec::with_capacity(buffers.len());
9287
9288 for (handle, abs_path, id) in buffers {
9289 let env = lsp_store
9290 .update(cx, |lsp_store, cx| {
9291 lsp_store.environment_for_buffer(&handle, cx)
9292 })?
9293 .await;
9294
9295 let ranges = match &target {
9296 LspFormatTarget::Buffers => None,
9297 LspFormatTarget::Ranges(ranges) => {
9298 Some(ranges.get(&id).context("No format ranges provided for buffer")?.clone())
9299 }
9300 };
9301
9302 formattable_buffers.push(FormattableBuffer {
9303 handle,
9304 abs_path,
9305 env,
9306 ranges,
9307 });
9308 }
9309 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
9310
9311 let format_timer = zlog::time!(logger => "Formatting buffers");
9312 let result = LocalLspStore::format_locally(
9313 lsp_store.clone(),
9314 formattable_buffers,
9315 push_to_history,
9316 trigger,
9317 logger,
9318 cx,
9319 )
9320 .await;
9321 format_timer.end();
9322
9323 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
9324
9325 lsp_store.update(cx, |lsp_store, _| {
9326 lsp_store.update_last_formatting_failure(&result);
9327 })?;
9328
9329 result
9330 })
9331 } else if let Some((client, project_id)) = self.upstream_client() {
9332 zlog::trace!(logger => "Formatting remotely");
9333 let logger = zlog::scoped!(logger => "remote");
9334 // Don't support formatting ranges via remote
9335 match target {
9336 LspFormatTarget::Buffers => {}
9337 LspFormatTarget::Ranges(_) => {
9338 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
9339 return Task::ready(Ok(ProjectTransaction::default()));
9340 }
9341 }
9342
9343 let buffer_store = self.buffer_store();
9344 cx.spawn(async move |lsp_store, cx| {
9345 zlog::trace!(logger => "Sending remote format request");
9346 let request_timer = zlog::time!(logger => "remote format request");
9347 let result = client
9348 .request(proto::FormatBuffers {
9349 project_id,
9350 trigger: trigger as i32,
9351 buffer_ids: buffers
9352 .iter()
9353 .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id().into()))
9354 .collect::<Result<_>>()?,
9355 })
9356 .await
9357 .and_then(|result| result.transaction.context("missing transaction"));
9358 request_timer.end();
9359
9360 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
9361
9362 lsp_store.update(cx, |lsp_store, _| {
9363 lsp_store.update_last_formatting_failure(&result);
9364 })?;
9365
9366 let transaction_response = result?;
9367 let _timer = zlog::time!(logger => "deserializing project transaction");
9368 buffer_store
9369 .update(cx, |buffer_store, cx| {
9370 buffer_store.deserialize_project_transaction(
9371 transaction_response,
9372 push_to_history,
9373 cx,
9374 )
9375 })?
9376 .await
9377 })
9378 } else {
9379 zlog::trace!(logger => "Not formatting");
9380 Task::ready(Ok(ProjectTransaction::default()))
9381 }
9382 }
9383
9384 async fn handle_format_buffers(
9385 this: Entity<Self>,
9386 envelope: TypedEnvelope<proto::FormatBuffers>,
9387 mut cx: AsyncApp,
9388 ) -> Result<proto::FormatBuffersResponse> {
9389 let sender_id = envelope.original_sender_id().unwrap_or_default();
9390 let format = this.update(&mut cx, |this, cx| {
9391 let mut buffers = HashSet::default();
9392 for buffer_id in &envelope.payload.buffer_ids {
9393 let buffer_id = BufferId::new(*buffer_id)?;
9394 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9395 }
9396 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
9397 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
9398 })??;
9399
9400 let project_transaction = format.await?;
9401 let project_transaction = this.update(&mut cx, |this, cx| {
9402 this.buffer_store.update(cx, |buffer_store, cx| {
9403 buffer_store.serialize_project_transaction_for_peer(
9404 project_transaction,
9405 sender_id,
9406 cx,
9407 )
9408 })
9409 })?;
9410 Ok(proto::FormatBuffersResponse {
9411 transaction: Some(project_transaction),
9412 })
9413 }
9414
9415 async fn handle_apply_code_action_kind(
9416 this: Entity<Self>,
9417 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
9418 mut cx: AsyncApp,
9419 ) -> Result<proto::ApplyCodeActionKindResponse> {
9420 let sender_id = envelope.original_sender_id().unwrap_or_default();
9421 let format = this.update(&mut cx, |this, cx| {
9422 let mut buffers = HashSet::default();
9423 for buffer_id in &envelope.payload.buffer_ids {
9424 let buffer_id = BufferId::new(*buffer_id)?;
9425 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9426 }
9427 let kind = match envelope.payload.kind.as_str() {
9428 "" => CodeActionKind::EMPTY,
9429 "quickfix" => CodeActionKind::QUICKFIX,
9430 "refactor" => CodeActionKind::REFACTOR,
9431 "refactor.extract" => CodeActionKind::REFACTOR_EXTRACT,
9432 "refactor.inline" => CodeActionKind::REFACTOR_INLINE,
9433 "refactor.rewrite" => CodeActionKind::REFACTOR_REWRITE,
9434 "source" => CodeActionKind::SOURCE,
9435 "source.organizeImports" => CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
9436 "source.fixAll" => CodeActionKind::SOURCE_FIX_ALL,
9437 _ => anyhow::bail!(
9438 "Invalid code action kind {}",
9439 envelope.payload.kind.as_str()
9440 ),
9441 };
9442 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
9443 })??;
9444
9445 let project_transaction = format.await?;
9446 let project_transaction = this.update(&mut cx, |this, cx| {
9447 this.buffer_store.update(cx, |buffer_store, cx| {
9448 buffer_store.serialize_project_transaction_for_peer(
9449 project_transaction,
9450 sender_id,
9451 cx,
9452 )
9453 })
9454 })?;
9455 Ok(proto::ApplyCodeActionKindResponse {
9456 transaction: Some(project_transaction),
9457 })
9458 }
9459
9460 async fn shutdown_language_server(
9461 server_state: Option<LanguageServerState>,
9462 name: LanguageServerName,
9463 cx: &mut AsyncApp,
9464 ) {
9465 let server = match server_state {
9466 Some(LanguageServerState::Starting { startup, .. }) => {
9467 let mut timer = cx
9468 .background_executor()
9469 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
9470 .fuse();
9471
9472 select! {
9473 server = startup.fuse() => server,
9474 () = timer => {
9475 log::info!("timeout waiting for language server {name} to finish launching before stopping");
9476 None
9477 },
9478 }
9479 }
9480
9481 Some(LanguageServerState::Running { server, .. }) => Some(server),
9482
9483 None => None,
9484 };
9485
9486 if let Some(server) = server {
9487 if let Some(shutdown) = server.shutdown() {
9488 shutdown.await;
9489 }
9490 }
9491 }
9492
9493 // Returns a list of all of the worktrees which no longer have a language server and the root path
9494 // for the stopped server
9495 fn stop_local_language_server(
9496 &mut self,
9497 server_id: LanguageServerId,
9498 cx: &mut Context<Self>,
9499 ) -> Task<Vec<WorktreeId>> {
9500 let local = match &mut self.mode {
9501 LspStoreMode::Local(local) => local,
9502 _ => {
9503 return Task::ready(Vec::new());
9504 }
9505 };
9506
9507 let mut orphaned_worktrees = Vec::new();
9508 // Remove this server ID from all entries in the given worktree.
9509 local.language_server_ids.retain(|(worktree, _), ids| {
9510 if !ids.remove(&server_id) {
9511 return true;
9512 }
9513
9514 if ids.is_empty() {
9515 orphaned_worktrees.push(*worktree);
9516 false
9517 } else {
9518 true
9519 }
9520 });
9521 self.buffer_store.update(cx, |buffer_store, cx| {
9522 for buffer in buffer_store.buffers() {
9523 buffer.update(cx, |buffer, cx| {
9524 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
9525 buffer.set_completion_triggers(server_id, Default::default(), cx);
9526 });
9527 }
9528 });
9529
9530 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
9531 summaries.retain(|path, summaries_by_server_id| {
9532 if summaries_by_server_id.remove(&server_id).is_some() {
9533 if let Some((client, project_id)) = self.downstream_client.clone() {
9534 client
9535 .send(proto::UpdateDiagnosticSummary {
9536 project_id,
9537 worktree_id: worktree_id.to_proto(),
9538 summary: Some(proto::DiagnosticSummary {
9539 path: path.as_ref().to_proto(),
9540 language_server_id: server_id.0 as u64,
9541 error_count: 0,
9542 warning_count: 0,
9543 }),
9544 })
9545 .log_err();
9546 }
9547 !summaries_by_server_id.is_empty()
9548 } else {
9549 true
9550 }
9551 });
9552 }
9553
9554 let local = self.as_local_mut().unwrap();
9555 for diagnostics in local.diagnostics.values_mut() {
9556 diagnostics.retain(|_, diagnostics_by_server_id| {
9557 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
9558 diagnostics_by_server_id.remove(ix);
9559 !diagnostics_by_server_id.is_empty()
9560 } else {
9561 true
9562 }
9563 });
9564 }
9565 local.language_server_watched_paths.remove(&server_id);
9566
9567 let server_state = local.language_servers.remove(&server_id);
9568 self.cleanup_lsp_data(server_id);
9569 let name = self
9570 .language_server_statuses
9571 .remove(&server_id)
9572 .map(|status| LanguageServerName::from(status.name.as_str()))
9573 .or_else(|| {
9574 if let Some(LanguageServerState::Running { adapter, .. }) = server_state.as_ref() {
9575 Some(adapter.name())
9576 } else {
9577 None
9578 }
9579 });
9580
9581 if let Some(name) = name {
9582 log::info!("stopping language server {name}");
9583 self.languages
9584 .update_lsp_binary_status(name.clone(), BinaryStatus::Stopping);
9585 cx.notify();
9586
9587 return cx.spawn(async move |lsp_store, cx| {
9588 Self::shutdown_language_server(server_state, name.clone(), cx).await;
9589 lsp_store
9590 .update(cx, |lsp_store, cx| {
9591 lsp_store
9592 .languages
9593 .update_lsp_binary_status(name, BinaryStatus::Stopped);
9594 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
9595 cx.notify();
9596 })
9597 .ok();
9598 orphaned_worktrees
9599 });
9600 }
9601
9602 if server_state.is_some() {
9603 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
9604 }
9605 Task::ready(orphaned_worktrees)
9606 }
9607
9608 pub fn stop_all_language_servers(&mut self, cx: &mut Context<Self>) {
9609 if let Some((client, project_id)) = self.upstream_client() {
9610 let request = client.request(proto::StopLanguageServers {
9611 project_id,
9612 buffer_ids: Vec::new(),
9613 also_servers: Vec::new(),
9614 all: true,
9615 });
9616 cx.background_spawn(request).detach_and_log_err(cx);
9617 } else {
9618 let Some(local) = self.as_local_mut() else {
9619 return;
9620 };
9621 let language_servers_to_stop = local
9622 .language_server_ids
9623 .values()
9624 .flatten()
9625 .copied()
9626 .collect();
9627 local.lsp_tree.update(cx, |this, _| {
9628 this.remove_nodes(&language_servers_to_stop);
9629 });
9630 let tasks = language_servers_to_stop
9631 .into_iter()
9632 .map(|server| self.stop_local_language_server(server, cx))
9633 .collect::<Vec<_>>();
9634 cx.background_spawn(async move {
9635 futures::future::join_all(tasks).await;
9636 })
9637 .detach();
9638 }
9639 }
9640
9641 pub fn restart_language_servers_for_buffers(
9642 &mut self,
9643 buffers: Vec<Entity<Buffer>>,
9644 only_restart_servers: HashSet<LanguageServerSelector>,
9645 cx: &mut Context<Self>,
9646 ) {
9647 if let Some((client, project_id)) = self.upstream_client() {
9648 let request = client.request(proto::RestartLanguageServers {
9649 project_id,
9650 buffer_ids: buffers
9651 .into_iter()
9652 .map(|b| b.read(cx).remote_id().to_proto())
9653 .collect(),
9654 only_servers: only_restart_servers
9655 .into_iter()
9656 .map(|selector| {
9657 let selector = match selector {
9658 LanguageServerSelector::Id(language_server_id) => {
9659 proto::language_server_selector::Selector::ServerId(
9660 language_server_id.to_proto(),
9661 )
9662 }
9663 LanguageServerSelector::Name(language_server_name) => {
9664 proto::language_server_selector::Selector::Name(
9665 language_server_name.to_string(),
9666 )
9667 }
9668 };
9669 proto::LanguageServerSelector {
9670 selector: Some(selector),
9671 }
9672 })
9673 .collect(),
9674 all: false,
9675 });
9676 cx.background_spawn(request).detach_and_log_err(cx);
9677 } else {
9678 let stop_task = if only_restart_servers.is_empty() {
9679 self.stop_local_language_servers_for_buffers(&buffers, HashSet::default(), cx)
9680 } else {
9681 self.stop_local_language_servers_for_buffers(&[], only_restart_servers.clone(), cx)
9682 };
9683 cx.spawn(async move |lsp_store, cx| {
9684 stop_task.await;
9685 lsp_store
9686 .update(cx, |lsp_store, cx| {
9687 for buffer in buffers {
9688 lsp_store.register_buffer_with_language_servers(
9689 &buffer,
9690 only_restart_servers.clone(),
9691 true,
9692 cx,
9693 );
9694 }
9695 })
9696 .ok()
9697 })
9698 .detach();
9699 }
9700 }
9701
9702 pub fn stop_language_servers_for_buffers(
9703 &mut self,
9704 buffers: Vec<Entity<Buffer>>,
9705 also_restart_servers: HashSet<LanguageServerSelector>,
9706 cx: &mut Context<Self>,
9707 ) {
9708 if let Some((client, project_id)) = self.upstream_client() {
9709 let request = client.request(proto::StopLanguageServers {
9710 project_id,
9711 buffer_ids: buffers
9712 .into_iter()
9713 .map(|b| b.read(cx).remote_id().to_proto())
9714 .collect(),
9715 also_servers: also_restart_servers
9716 .into_iter()
9717 .map(|selector| {
9718 let selector = match selector {
9719 LanguageServerSelector::Id(language_server_id) => {
9720 proto::language_server_selector::Selector::ServerId(
9721 language_server_id.to_proto(),
9722 )
9723 }
9724 LanguageServerSelector::Name(language_server_name) => {
9725 proto::language_server_selector::Selector::Name(
9726 language_server_name.to_string(),
9727 )
9728 }
9729 };
9730 proto::LanguageServerSelector {
9731 selector: Some(selector),
9732 }
9733 })
9734 .collect(),
9735 all: false,
9736 });
9737 cx.background_spawn(request).detach_and_log_err(cx);
9738 } else {
9739 self.stop_local_language_servers_for_buffers(&buffers, also_restart_servers, cx)
9740 .detach();
9741 }
9742 }
9743
9744 fn stop_local_language_servers_for_buffers(
9745 &mut self,
9746 buffers: &[Entity<Buffer>],
9747 also_restart_servers: HashSet<LanguageServerSelector>,
9748 cx: &mut Context<Self>,
9749 ) -> Task<()> {
9750 let Some(local) = self.as_local_mut() else {
9751 return Task::ready(());
9752 };
9753 let mut language_server_names_to_stop = BTreeSet::default();
9754 let mut language_servers_to_stop = also_restart_servers
9755 .into_iter()
9756 .flat_map(|selector| match selector {
9757 LanguageServerSelector::Id(id) => Some(id),
9758 LanguageServerSelector::Name(name) => {
9759 language_server_names_to_stop.insert(name);
9760 None
9761 }
9762 })
9763 .collect::<BTreeSet<_>>();
9764
9765 let mut covered_worktrees = HashSet::default();
9766 for buffer in buffers {
9767 buffer.update(cx, |buffer, cx| {
9768 language_servers_to_stop.extend(local.language_server_ids_for_buffer(buffer, cx));
9769 if let Some(worktree_id) = buffer.file().map(|f| f.worktree_id(cx)) {
9770 if covered_worktrees.insert(worktree_id) {
9771 language_server_names_to_stop.retain(|name| {
9772 match local.language_server_ids.get(&(worktree_id, name.clone())) {
9773 Some(server_ids) => {
9774 language_servers_to_stop
9775 .extend(server_ids.into_iter().copied());
9776 false
9777 }
9778 None => true,
9779 }
9780 });
9781 }
9782 }
9783 });
9784 }
9785 for name in language_server_names_to_stop {
9786 if let Some(server_ids) = local
9787 .language_server_ids
9788 .iter()
9789 .filter(|((_, server_name), _)| server_name == &name)
9790 .map(|((_, _), server_ids)| server_ids)
9791 .max_by_key(|server_ids| server_ids.len())
9792 {
9793 language_servers_to_stop.extend(server_ids.into_iter().copied());
9794 }
9795 }
9796
9797 local.lsp_tree.update(cx, |this, _| {
9798 this.remove_nodes(&language_servers_to_stop);
9799 });
9800 let tasks = language_servers_to_stop
9801 .into_iter()
9802 .map(|server| self.stop_local_language_server(server, cx))
9803 .collect::<Vec<_>>();
9804
9805 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
9806 }
9807
9808 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
9809 let (worktree, relative_path) =
9810 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
9811
9812 let project_path = ProjectPath {
9813 worktree_id: worktree.read(cx).id(),
9814 path: relative_path.into(),
9815 };
9816
9817 Some(
9818 self.buffer_store()
9819 .read(cx)
9820 .get_by_path(&project_path)?
9821 .read(cx),
9822 )
9823 }
9824
9825 pub fn update_diagnostics(
9826 &mut self,
9827 language_server_id: LanguageServerId,
9828 params: lsp::PublishDiagnosticsParams,
9829 result_id: Option<String>,
9830 source_kind: DiagnosticSourceKind,
9831 disk_based_sources: &[String],
9832 cx: &mut Context<Self>,
9833 ) -> Result<()> {
9834 self.merge_diagnostics(
9835 language_server_id,
9836 params,
9837 result_id,
9838 source_kind,
9839 disk_based_sources,
9840 |_, _, _| false,
9841 cx,
9842 )
9843 }
9844
9845 pub fn merge_diagnostics(
9846 &mut self,
9847 language_server_id: LanguageServerId,
9848 mut params: lsp::PublishDiagnosticsParams,
9849 result_id: Option<String>,
9850 source_kind: DiagnosticSourceKind,
9851 disk_based_sources: &[String],
9852 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
9853 cx: &mut Context<Self>,
9854 ) -> Result<()> {
9855 anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
9856 let abs_path = params
9857 .uri
9858 .to_file_path()
9859 .map_err(|()| anyhow!("URI is not a file"))?;
9860 let mut diagnostics = Vec::default();
9861 let mut primary_diagnostic_group_ids = HashMap::default();
9862 let mut sources_by_group_id = HashMap::default();
9863 let mut supporting_diagnostics = HashMap::default();
9864
9865 let adapter = self.language_server_adapter_for_id(language_server_id);
9866
9867 // Ensure that primary diagnostics are always the most severe
9868 params.diagnostics.sort_by_key(|item| item.severity);
9869
9870 for diagnostic in ¶ms.diagnostics {
9871 let source = diagnostic.source.as_ref();
9872 let range = range_from_lsp(diagnostic.range);
9873 let is_supporting = diagnostic
9874 .related_information
9875 .as_ref()
9876 .map_or(false, |infos| {
9877 infos.iter().any(|info| {
9878 primary_diagnostic_group_ids.contains_key(&(
9879 source,
9880 diagnostic.code.clone(),
9881 range_from_lsp(info.location.range),
9882 ))
9883 })
9884 });
9885
9886 let is_unnecessary = diagnostic
9887 .tags
9888 .as_ref()
9889 .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
9890
9891 let underline = self
9892 .language_server_adapter_for_id(language_server_id)
9893 .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
9894
9895 if is_supporting {
9896 supporting_diagnostics.insert(
9897 (source, diagnostic.code.clone(), range),
9898 (diagnostic.severity, is_unnecessary),
9899 );
9900 } else {
9901 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
9902 let is_disk_based =
9903 source.map_or(false, |source| disk_based_sources.contains(source));
9904
9905 sources_by_group_id.insert(group_id, source);
9906 primary_diagnostic_group_ids
9907 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
9908
9909 diagnostics.push(DiagnosticEntry {
9910 range,
9911 diagnostic: Diagnostic {
9912 source: diagnostic.source.clone(),
9913 source_kind,
9914 code: diagnostic.code.clone(),
9915 code_description: diagnostic
9916 .code_description
9917 .as_ref()
9918 .map(|d| d.href.clone()),
9919 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
9920 markdown: adapter.as_ref().and_then(|adapter| {
9921 adapter.diagnostic_message_to_markdown(&diagnostic.message)
9922 }),
9923 message: diagnostic.message.trim().to_string(),
9924 group_id,
9925 is_primary: true,
9926 is_disk_based,
9927 is_unnecessary,
9928 underline,
9929 data: diagnostic.data.clone(),
9930 },
9931 });
9932 if let Some(infos) = &diagnostic.related_information {
9933 for info in infos {
9934 if info.location.uri == params.uri && !info.message.is_empty() {
9935 let range = range_from_lsp(info.location.range);
9936 diagnostics.push(DiagnosticEntry {
9937 range,
9938 diagnostic: Diagnostic {
9939 source: diagnostic.source.clone(),
9940 source_kind,
9941 code: diagnostic.code.clone(),
9942 code_description: diagnostic
9943 .code_description
9944 .as_ref()
9945 .map(|c| c.href.clone()),
9946 severity: DiagnosticSeverity::INFORMATION,
9947 markdown: adapter.as_ref().and_then(|adapter| {
9948 adapter.diagnostic_message_to_markdown(&info.message)
9949 }),
9950 message: info.message.trim().to_string(),
9951 group_id,
9952 is_primary: false,
9953 is_disk_based,
9954 is_unnecessary: false,
9955 underline,
9956 data: diagnostic.data.clone(),
9957 },
9958 });
9959 }
9960 }
9961 }
9962 }
9963 }
9964
9965 for entry in &mut diagnostics {
9966 let diagnostic = &mut entry.diagnostic;
9967 if !diagnostic.is_primary {
9968 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
9969 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
9970 source,
9971 diagnostic.code.clone(),
9972 entry.range.clone(),
9973 )) {
9974 if let Some(severity) = severity {
9975 diagnostic.severity = severity;
9976 }
9977 diagnostic.is_unnecessary = is_unnecessary;
9978 }
9979 }
9980 }
9981
9982 self.merge_diagnostic_entries(
9983 language_server_id,
9984 abs_path,
9985 result_id,
9986 params.version,
9987 diagnostics,
9988 filter,
9989 cx,
9990 )?;
9991 Ok(())
9992 }
9993
9994 fn insert_newly_running_language_server(
9995 &mut self,
9996 adapter: Arc<CachedLspAdapter>,
9997 language_server: Arc<LanguageServer>,
9998 server_id: LanguageServerId,
9999 key: (WorktreeId, LanguageServerName),
10000 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
10001 cx: &mut Context<Self>,
10002 ) {
10003 let Some(local) = self.as_local_mut() else {
10004 return;
10005 };
10006 // If the language server for this key doesn't match the server id, don't store the
10007 // server. Which will cause it to be dropped, killing the process
10008 if local
10009 .language_server_ids
10010 .get(&key)
10011 .map(|ids| !ids.contains(&server_id))
10012 .unwrap_or(false)
10013 {
10014 return;
10015 }
10016
10017 // Update language_servers collection with Running variant of LanguageServerState
10018 // indicating that the server is up and running and ready
10019 let workspace_folders = workspace_folders.lock().clone();
10020 language_server.set_workspace_folders(workspace_folders);
10021
10022 local.language_servers.insert(
10023 server_id,
10024 LanguageServerState::Running {
10025 workspace_refresh_task: lsp_workspace_diagnostics_refresh(
10026 language_server.clone(),
10027 cx,
10028 ),
10029 adapter: adapter.clone(),
10030 server: language_server.clone(),
10031 simulate_disk_based_diagnostics_completion: None,
10032 },
10033 );
10034 local
10035 .languages
10036 .update_lsp_binary_status(adapter.name(), BinaryStatus::None);
10037 if let Some(file_ops_caps) = language_server
10038 .capabilities()
10039 .workspace
10040 .as_ref()
10041 .and_then(|ws| ws.file_operations.as_ref())
10042 {
10043 let did_rename_caps = file_ops_caps.did_rename.as_ref();
10044 let will_rename_caps = file_ops_caps.will_rename.as_ref();
10045 if did_rename_caps.or(will_rename_caps).is_some() {
10046 let watcher = RenamePathsWatchedForServer::default()
10047 .with_did_rename_patterns(did_rename_caps)
10048 .with_will_rename_patterns(will_rename_caps);
10049 local
10050 .language_server_paths_watched_for_rename
10051 .insert(server_id, watcher);
10052 }
10053 }
10054
10055 self.language_server_statuses.insert(
10056 server_id,
10057 LanguageServerStatus {
10058 name: language_server.name().to_string(),
10059 pending_work: Default::default(),
10060 has_pending_diagnostic_updates: false,
10061 progress_tokens: Default::default(),
10062 },
10063 );
10064
10065 cx.emit(LspStoreEvent::LanguageServerAdded(
10066 server_id,
10067 language_server.name(),
10068 Some(key.0),
10069 ));
10070 cx.emit(LspStoreEvent::RefreshInlayHints);
10071
10072 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
10073 downstream_client
10074 .send(proto::StartLanguageServer {
10075 project_id: *project_id,
10076 server: Some(proto::LanguageServer {
10077 id: server_id.0 as u64,
10078 name: language_server.name().to_string(),
10079 worktree_id: Some(key.0.to_proto()),
10080 }),
10081 })
10082 .log_err();
10083 }
10084
10085 // Tell the language server about every open buffer in the worktree that matches the language.
10086 self.buffer_store.clone().update(cx, |buffer_store, cx| {
10087 for buffer_handle in buffer_store.buffers() {
10088 let buffer = buffer_handle.read(cx);
10089 let file = match File::from_dyn(buffer.file()) {
10090 Some(file) => file,
10091 None => continue,
10092 };
10093 let language = match buffer.language() {
10094 Some(language) => language,
10095 None => continue,
10096 };
10097
10098 if file.worktree.read(cx).id() != key.0
10099 || !self
10100 .languages
10101 .lsp_adapters(&language.name())
10102 .iter()
10103 .any(|a| a.name == key.1)
10104 {
10105 continue;
10106 }
10107 // didOpen
10108 let file = match file.as_local() {
10109 Some(file) => file,
10110 None => continue,
10111 };
10112
10113 let local = self.as_local_mut().unwrap();
10114
10115 if local.registered_buffers.contains_key(&buffer.remote_id()) {
10116 let versions = local
10117 .buffer_snapshots
10118 .entry(buffer.remote_id())
10119 .or_default()
10120 .entry(server_id)
10121 .and_modify(|_| {
10122 assert!(
10123 false,
10124 "There should not be an existing snapshot for a newly inserted buffer"
10125 )
10126 })
10127 .or_insert_with(|| {
10128 vec![LspBufferSnapshot {
10129 version: 0,
10130 snapshot: buffer.text_snapshot(),
10131 }]
10132 });
10133
10134 let snapshot = versions.last().unwrap();
10135 let version = snapshot.version;
10136 let initial_snapshot = &snapshot.snapshot;
10137 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
10138 language_server.register_buffer(
10139 uri,
10140 adapter.language_id(&language.name()),
10141 version,
10142 initial_snapshot.text(),
10143 );
10144 }
10145 buffer_handle.update(cx, |buffer, cx| {
10146 buffer.set_completion_triggers(
10147 server_id,
10148 language_server
10149 .capabilities()
10150 .completion_provider
10151 .as_ref()
10152 .and_then(|provider| {
10153 provider
10154 .trigger_characters
10155 .as_ref()
10156 .map(|characters| characters.iter().cloned().collect())
10157 })
10158 .unwrap_or_default(),
10159 cx,
10160 )
10161 });
10162 }
10163 });
10164
10165 cx.notify();
10166 }
10167
10168 pub fn language_servers_running_disk_based_diagnostics(
10169 &self,
10170 ) -> impl Iterator<Item = LanguageServerId> + '_ {
10171 self.language_server_statuses
10172 .iter()
10173 .filter_map(|(id, status)| {
10174 if status.has_pending_diagnostic_updates {
10175 Some(*id)
10176 } else {
10177 None
10178 }
10179 })
10180 }
10181
10182 pub(crate) fn cancel_language_server_work_for_buffers(
10183 &mut self,
10184 buffers: impl IntoIterator<Item = Entity<Buffer>>,
10185 cx: &mut Context<Self>,
10186 ) {
10187 if let Some((client, project_id)) = self.upstream_client() {
10188 let request = client.request(proto::CancelLanguageServerWork {
10189 project_id,
10190 work: Some(proto::cancel_language_server_work::Work::Buffers(
10191 proto::cancel_language_server_work::Buffers {
10192 buffer_ids: buffers
10193 .into_iter()
10194 .map(|b| b.read(cx).remote_id().to_proto())
10195 .collect(),
10196 },
10197 )),
10198 });
10199 cx.background_spawn(request).detach_and_log_err(cx);
10200 } else if let Some(local) = self.as_local() {
10201 let servers = buffers
10202 .into_iter()
10203 .flat_map(|buffer| {
10204 buffer.update(cx, |buffer, cx| {
10205 local.language_server_ids_for_buffer(buffer, cx).into_iter()
10206 })
10207 })
10208 .collect::<HashSet<_>>();
10209 for server_id in servers {
10210 self.cancel_language_server_work(server_id, None, cx);
10211 }
10212 }
10213 }
10214
10215 pub(crate) fn cancel_language_server_work(
10216 &mut self,
10217 server_id: LanguageServerId,
10218 token_to_cancel: Option<String>,
10219 cx: &mut Context<Self>,
10220 ) {
10221 if let Some(local) = self.as_local() {
10222 let status = self.language_server_statuses.get(&server_id);
10223 let server = local.language_servers.get(&server_id);
10224 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
10225 {
10226 for (token, progress) in &status.pending_work {
10227 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
10228 if token != token_to_cancel {
10229 continue;
10230 }
10231 }
10232 if progress.is_cancellable {
10233 server
10234 .notify::<lsp::notification::WorkDoneProgressCancel>(
10235 &WorkDoneProgressCancelParams {
10236 token: lsp::NumberOrString::String(token.clone()),
10237 },
10238 )
10239 .ok();
10240 }
10241 }
10242 }
10243 } else if let Some((client, project_id)) = self.upstream_client() {
10244 let request = client.request(proto::CancelLanguageServerWork {
10245 project_id,
10246 work: Some(
10247 proto::cancel_language_server_work::Work::LanguageServerWork(
10248 proto::cancel_language_server_work::LanguageServerWork {
10249 language_server_id: server_id.to_proto(),
10250 token: token_to_cancel,
10251 },
10252 ),
10253 ),
10254 });
10255 cx.background_spawn(request).detach_and_log_err(cx);
10256 }
10257 }
10258
10259 fn register_supplementary_language_server(
10260 &mut self,
10261 id: LanguageServerId,
10262 name: LanguageServerName,
10263 server: Arc<LanguageServer>,
10264 cx: &mut Context<Self>,
10265 ) {
10266 if let Some(local) = self.as_local_mut() {
10267 local
10268 .supplementary_language_servers
10269 .insert(id, (name.clone(), server));
10270 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
10271 }
10272 }
10273
10274 fn unregister_supplementary_language_server(
10275 &mut self,
10276 id: LanguageServerId,
10277 cx: &mut Context<Self>,
10278 ) {
10279 if let Some(local) = self.as_local_mut() {
10280 local.supplementary_language_servers.remove(&id);
10281 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
10282 }
10283 }
10284
10285 pub(crate) fn supplementary_language_servers(
10286 &self,
10287 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
10288 self.as_local().into_iter().flat_map(|local| {
10289 local
10290 .supplementary_language_servers
10291 .iter()
10292 .map(|(id, (name, _))| (*id, name.clone()))
10293 })
10294 }
10295
10296 pub fn language_server_adapter_for_id(
10297 &self,
10298 id: LanguageServerId,
10299 ) -> Option<Arc<CachedLspAdapter>> {
10300 self.as_local()
10301 .and_then(|local| local.language_servers.get(&id))
10302 .and_then(|language_server_state| match language_server_state {
10303 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
10304 _ => None,
10305 })
10306 }
10307
10308 pub(super) fn update_local_worktree_language_servers(
10309 &mut self,
10310 worktree_handle: &Entity<Worktree>,
10311 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
10312 cx: &mut Context<Self>,
10313 ) {
10314 if changes.is_empty() {
10315 return;
10316 }
10317
10318 let Some(local) = self.as_local() else { return };
10319
10320 local.prettier_store.update(cx, |prettier_store, cx| {
10321 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
10322 });
10323
10324 let worktree_id = worktree_handle.read(cx).id();
10325 let mut language_server_ids = local
10326 .language_server_ids
10327 .iter()
10328 .flat_map(|((server_worktree, _), server_ids)| {
10329 server_ids
10330 .iter()
10331 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
10332 })
10333 .collect::<Vec<_>>();
10334 language_server_ids.sort();
10335 language_server_ids.dedup();
10336
10337 let abs_path = worktree_handle.read(cx).abs_path();
10338 for server_id in &language_server_ids {
10339 if let Some(LanguageServerState::Running { server, .. }) =
10340 local.language_servers.get(server_id)
10341 {
10342 if let Some(watched_paths) = local
10343 .language_server_watched_paths
10344 .get(server_id)
10345 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
10346 {
10347 let params = lsp::DidChangeWatchedFilesParams {
10348 changes: changes
10349 .iter()
10350 .filter_map(|(path, _, change)| {
10351 if !watched_paths.is_match(path) {
10352 return None;
10353 }
10354 let typ = match change {
10355 PathChange::Loaded => return None,
10356 PathChange::Added => lsp::FileChangeType::CREATED,
10357 PathChange::Removed => lsp::FileChangeType::DELETED,
10358 PathChange::Updated => lsp::FileChangeType::CHANGED,
10359 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
10360 };
10361 Some(lsp::FileEvent {
10362 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
10363 typ,
10364 })
10365 })
10366 .collect(),
10367 };
10368 if !params.changes.is_empty() {
10369 server
10370 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
10371 .ok();
10372 }
10373 }
10374 }
10375 }
10376 }
10377
10378 pub fn wait_for_remote_buffer(
10379 &mut self,
10380 id: BufferId,
10381 cx: &mut Context<Self>,
10382 ) -> Task<Result<Entity<Buffer>>> {
10383 self.buffer_store.update(cx, |buffer_store, cx| {
10384 buffer_store.wait_for_remote_buffer(id, cx)
10385 })
10386 }
10387
10388 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10389 proto::Symbol {
10390 language_server_name: symbol.language_server_name.0.to_string(),
10391 source_worktree_id: symbol.source_worktree_id.to_proto(),
10392 language_server_id: symbol.source_language_server_id.to_proto(),
10393 worktree_id: symbol.path.worktree_id.to_proto(),
10394 path: symbol.path.path.as_ref().to_proto(),
10395 name: symbol.name.clone(),
10396 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
10397 start: Some(proto::PointUtf16 {
10398 row: symbol.range.start.0.row,
10399 column: symbol.range.start.0.column,
10400 }),
10401 end: Some(proto::PointUtf16 {
10402 row: symbol.range.end.0.row,
10403 column: symbol.range.end.0.column,
10404 }),
10405 signature: symbol.signature.to_vec(),
10406 }
10407 }
10408
10409 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
10410 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
10411 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
10412 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
10413 let path = ProjectPath {
10414 worktree_id,
10415 path: Arc::<Path>::from_proto(serialized_symbol.path),
10416 };
10417
10418 let start = serialized_symbol.start.context("invalid start")?;
10419 let end = serialized_symbol.end.context("invalid end")?;
10420 Ok(CoreSymbol {
10421 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
10422 source_worktree_id,
10423 source_language_server_id: LanguageServerId::from_proto(
10424 serialized_symbol.language_server_id,
10425 ),
10426 path,
10427 name: serialized_symbol.name,
10428 range: Unclipped(PointUtf16::new(start.row, start.column))
10429 ..Unclipped(PointUtf16::new(end.row, end.column)),
10430 kind,
10431 signature: serialized_symbol
10432 .signature
10433 .try_into()
10434 .map_err(|_| anyhow!("invalid signature"))?,
10435 })
10436 }
10437
10438 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10439 let mut serialized_completion = proto::Completion {
10440 old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
10441 old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
10442 new_text: completion.new_text.clone(),
10443 ..proto::Completion::default()
10444 };
10445 match &completion.source {
10446 CompletionSource::Lsp {
10447 insert_range,
10448 server_id,
10449 lsp_completion,
10450 lsp_defaults,
10451 resolved,
10452 } => {
10453 let (old_insert_start, old_insert_end) = insert_range
10454 .as_ref()
10455 .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
10456 .unzip();
10457
10458 serialized_completion.old_insert_start = old_insert_start;
10459 serialized_completion.old_insert_end = old_insert_end;
10460 serialized_completion.source = proto::completion::Source::Lsp as i32;
10461 serialized_completion.server_id = server_id.0 as u64;
10462 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
10463 serialized_completion.lsp_defaults = lsp_defaults
10464 .as_deref()
10465 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
10466 serialized_completion.resolved = *resolved;
10467 }
10468 CompletionSource::BufferWord {
10469 word_range,
10470 resolved,
10471 } => {
10472 serialized_completion.source = proto::completion::Source::BufferWord as i32;
10473 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
10474 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
10475 serialized_completion.resolved = *resolved;
10476 }
10477 CompletionSource::Custom => {
10478 serialized_completion.source = proto::completion::Source::Custom as i32;
10479 serialized_completion.resolved = true;
10480 }
10481 }
10482
10483 serialized_completion
10484 }
10485
10486 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10487 let old_replace_start = completion
10488 .old_replace_start
10489 .and_then(deserialize_anchor)
10490 .context("invalid old start")?;
10491 let old_replace_end = completion
10492 .old_replace_end
10493 .and_then(deserialize_anchor)
10494 .context("invalid old end")?;
10495 let insert_range = {
10496 match completion.old_insert_start.zip(completion.old_insert_end) {
10497 Some((start, end)) => {
10498 let start = deserialize_anchor(start).context("invalid insert old start")?;
10499 let end = deserialize_anchor(end).context("invalid insert old end")?;
10500 Some(start..end)
10501 }
10502 None => None,
10503 }
10504 };
10505 Ok(CoreCompletion {
10506 replace_range: old_replace_start..old_replace_end,
10507 new_text: completion.new_text,
10508 source: match proto::completion::Source::from_i32(completion.source) {
10509 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
10510 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
10511 insert_range,
10512 server_id: LanguageServerId::from_proto(completion.server_id),
10513 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
10514 lsp_defaults: completion
10515 .lsp_defaults
10516 .as_deref()
10517 .map(serde_json::from_slice)
10518 .transpose()?,
10519 resolved: completion.resolved,
10520 },
10521 Some(proto::completion::Source::BufferWord) => {
10522 let word_range = completion
10523 .buffer_word_start
10524 .and_then(deserialize_anchor)
10525 .context("invalid buffer word start")?
10526 ..completion
10527 .buffer_word_end
10528 .and_then(deserialize_anchor)
10529 .context("invalid buffer word end")?;
10530 CompletionSource::BufferWord {
10531 word_range,
10532 resolved: completion.resolved,
10533 }
10534 }
10535 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
10536 },
10537 })
10538 }
10539
10540 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10541 let (kind, lsp_action) = match &action.lsp_action {
10542 LspAction::Action(code_action) => (
10543 proto::code_action::Kind::Action as i32,
10544 serde_json::to_vec(code_action).unwrap(),
10545 ),
10546 LspAction::Command(command) => (
10547 proto::code_action::Kind::Command as i32,
10548 serde_json::to_vec(command).unwrap(),
10549 ),
10550 LspAction::CodeLens(code_lens) => (
10551 proto::code_action::Kind::CodeLens as i32,
10552 serde_json::to_vec(code_lens).unwrap(),
10553 ),
10554 };
10555
10556 proto::CodeAction {
10557 server_id: action.server_id.0 as u64,
10558 start: Some(serialize_anchor(&action.range.start)),
10559 end: Some(serialize_anchor(&action.range.end)),
10560 lsp_action,
10561 kind,
10562 resolved: action.resolved,
10563 }
10564 }
10565
10566 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10567 let start = action
10568 .start
10569 .and_then(deserialize_anchor)
10570 .context("invalid start")?;
10571 let end = action
10572 .end
10573 .and_then(deserialize_anchor)
10574 .context("invalid end")?;
10575 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
10576 Some(proto::code_action::Kind::Action) => {
10577 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
10578 }
10579 Some(proto::code_action::Kind::Command) => {
10580 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
10581 }
10582 Some(proto::code_action::Kind::CodeLens) => {
10583 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
10584 }
10585 None => anyhow::bail!("Unknown action kind {}", action.kind),
10586 };
10587 Ok(CodeAction {
10588 server_id: LanguageServerId(action.server_id as usize),
10589 range: start..end,
10590 resolved: action.resolved,
10591 lsp_action,
10592 })
10593 }
10594
10595 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
10596 match &formatting_result {
10597 Ok(_) => self.last_formatting_failure = None,
10598 Err(error) => {
10599 let error_string = format!("{error:#}");
10600 log::error!("Formatting failed: {error_string}");
10601 self.last_formatting_failure
10602 .replace(error_string.lines().join(" "));
10603 }
10604 }
10605 }
10606
10607 fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
10608 if let Some(lsp_data) = &mut self.lsp_data {
10609 lsp_data.buffer_lsp_data.remove(&for_server);
10610 }
10611 if let Some(local) = self.as_local_mut() {
10612 local.buffer_pull_diagnostics_result_ids.remove(&for_server);
10613 }
10614 }
10615
10616 pub fn result_id(
10617 &self,
10618 server_id: LanguageServerId,
10619 buffer_id: BufferId,
10620 cx: &App,
10621 ) -> Option<String> {
10622 let abs_path = self
10623 .buffer_store
10624 .read(cx)
10625 .get(buffer_id)
10626 .and_then(|b| File::from_dyn(b.read(cx).file()))
10627 .map(|f| f.abs_path(cx))?;
10628 self.as_local()?
10629 .buffer_pull_diagnostics_result_ids
10630 .get(&server_id)?
10631 .get(&abs_path)?
10632 .clone()
10633 }
10634
10635 pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
10636 let Some(local) = self.as_local() else {
10637 return HashMap::default();
10638 };
10639 local
10640 .buffer_pull_diagnostics_result_ids
10641 .get(&server_id)
10642 .into_iter()
10643 .flatten()
10644 .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
10645 .collect()
10646 }
10647
10648 pub fn pull_workspace_diagnostics(&mut self, server_id: LanguageServerId) {
10649 if let Some(LanguageServerState::Running {
10650 workspace_refresh_task: Some((tx, _)),
10651 ..
10652 }) = self
10653 .as_local_mut()
10654 .and_then(|local| local.language_servers.get_mut(&server_id))
10655 {
10656 tx.try_send(()).ok();
10657 }
10658 }
10659
10660 pub fn pull_workspace_diagnostics_for_buffer(&mut self, buffer_id: BufferId, cx: &mut App) {
10661 let Some(buffer) = self.buffer_store().read(cx).get_existing(buffer_id).ok() else {
10662 return;
10663 };
10664 let Some(local) = self.as_local_mut() else {
10665 return;
10666 };
10667
10668 for server_id in buffer.update(cx, |buffer, cx| {
10669 local.language_server_ids_for_buffer(buffer, cx)
10670 }) {
10671 if let Some(LanguageServerState::Running {
10672 workspace_refresh_task: Some((tx, _)),
10673 ..
10674 }) = local.language_servers.get_mut(&server_id)
10675 {
10676 tx.try_send(()).ok();
10677 }
10678 }
10679 }
10680}
10681
10682async fn fetch_document_colors(
10683 lsp_store: WeakEntity<LspStore>,
10684 buffer: Entity<Buffer>,
10685 task_abs_path: PathBuf,
10686 cx: &mut AsyncApp,
10687) -> anyhow::Result<HashSet<DocumentColor>> {
10688 cx.background_executor()
10689 .timer(Duration::from_millis(50))
10690 .await;
10691 let Some(buffer_mtime) = buffer.update(cx, |buffer, _| buffer.saved_mtime())? else {
10692 return Ok(HashSet::default());
10693 };
10694 let fetched_colors = lsp_store
10695 .update(cx, |lsp_store, cx| {
10696 lsp_store.fetch_document_colors_for_buffer(buffer, cx)
10697 })?
10698 .await
10699 .with_context(|| {
10700 format!("Fetching document colors for buffer with path {task_abs_path:?}")
10701 })?;
10702
10703 lsp_store.update(cx, |lsp_store, _| {
10704 let lsp_data = lsp_store.lsp_data.as_mut().with_context(|| {
10705 format!(
10706 "Document lsp data got updated between fetch and update for path {task_abs_path:?}"
10707 )
10708 })?;
10709 let mut lsp_colors = HashSet::default();
10710 anyhow::ensure!(
10711 lsp_data.mtime == buffer_mtime,
10712 "Buffer lsp data got updated between fetch and update for path {task_abs_path:?}"
10713 );
10714 for (server_id, colors) in fetched_colors {
10715 let colors_lsp_data = &mut lsp_data
10716 .buffer_lsp_data
10717 .entry(server_id)
10718 .or_default()
10719 .entry(task_abs_path.clone())
10720 .or_default()
10721 .colors;
10722 *colors_lsp_data = Some(colors.clone());
10723 lsp_colors.extend(colors);
10724 }
10725 Ok(lsp_colors)
10726 })?
10727}
10728
10729fn subscribe_to_binary_statuses(
10730 languages: &Arc<LanguageRegistry>,
10731 cx: &mut Context<'_, LspStore>,
10732) -> Task<()> {
10733 let mut server_statuses = languages.language_server_binary_statuses();
10734 cx.spawn(async move |lsp_store, cx| {
10735 while let Some((server_name, binary_status)) = server_statuses.next().await {
10736 if lsp_store
10737 .update(cx, |_, cx| {
10738 let mut message = None;
10739 let binary_status = match binary_status {
10740 BinaryStatus::None => proto::ServerBinaryStatus::None,
10741 BinaryStatus::CheckingForUpdate => {
10742 proto::ServerBinaryStatus::CheckingForUpdate
10743 }
10744 BinaryStatus::Downloading => proto::ServerBinaryStatus::Downloading,
10745 BinaryStatus::Starting => proto::ServerBinaryStatus::Starting,
10746 BinaryStatus::Stopping => proto::ServerBinaryStatus::Stopping,
10747 BinaryStatus::Stopped => proto::ServerBinaryStatus::Stopped,
10748 BinaryStatus::Failed { error } => {
10749 message = Some(error);
10750 proto::ServerBinaryStatus::Failed
10751 }
10752 };
10753 cx.emit(LspStoreEvent::LanguageServerUpdate {
10754 // Binary updates are about the binary that might not have any language server id at that point.
10755 // Reuse `LanguageServerUpdate` for them and provide a fake id that won't be used on the receiver side.
10756 language_server_id: LanguageServerId(0),
10757 name: Some(server_name),
10758 message: proto::update_language_server::Variant::StatusUpdate(
10759 proto::StatusUpdate {
10760 message,
10761 status: Some(proto::status_update::Status::Binary(
10762 binary_status as i32,
10763 )),
10764 },
10765 ),
10766 });
10767 })
10768 .is_err()
10769 {
10770 break;
10771 }
10772 }
10773 })
10774}
10775
10776fn lsp_workspace_diagnostics_refresh(
10777 server: Arc<LanguageServer>,
10778 cx: &mut Context<'_, LspStore>,
10779) -> Option<(mpsc::Sender<()>, Task<()>)> {
10780 let identifier = match server.capabilities().diagnostic_provider? {
10781 lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {
10782 if !diagnostic_options.workspace_diagnostics {
10783 return None;
10784 }
10785 diagnostic_options.identifier
10786 }
10787 lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {
10788 let diagnostic_options = registration_options.diagnostic_options;
10789 if !diagnostic_options.workspace_diagnostics {
10790 return None;
10791 }
10792 diagnostic_options.identifier
10793 }
10794 };
10795
10796 let (mut tx, mut rx) = mpsc::channel(1);
10797 tx.try_send(()).ok();
10798
10799 let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {
10800 let mut attempts = 0;
10801 let max_attempts = 50;
10802
10803 loop {
10804 let Some(()) = rx.recv().await else {
10805 return;
10806 };
10807
10808 'request: loop {
10809 if attempts > max_attempts {
10810 log::error!(
10811 "Failed to pull workspace diagnostics {max_attempts} times, aborting"
10812 );
10813 return;
10814 }
10815 let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);
10816 cx.background_executor()
10817 .timer(Duration::from_millis(backoff_millis))
10818 .await;
10819 attempts += 1;
10820
10821 let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
10822 lsp_store
10823 .all_result_ids(server.server_id())
10824 .into_iter()
10825 .filter_map(|(abs_path, result_id)| {
10826 let uri = file_path_to_lsp_url(&abs_path).ok()?;
10827 Some(lsp::PreviousResultId {
10828 uri,
10829 value: result_id,
10830 })
10831 })
10832 .collect()
10833 }) else {
10834 return;
10835 };
10836
10837 let response_result = server
10838 .request::<lsp::WorkspaceDiagnosticRequest>(lsp::WorkspaceDiagnosticParams {
10839 previous_result_ids,
10840 identifier: identifier.clone(),
10841 work_done_progress_params: Default::default(),
10842 partial_result_params: Default::default(),
10843 })
10844 .await;
10845 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh
10846 // > If a server closes a workspace diagnostic pull request the client should re-trigger the request.
10847 match response_result {
10848 ConnectionResult::Timeout => {
10849 log::error!("Timeout during workspace diagnostics pull");
10850 continue 'request;
10851 }
10852 ConnectionResult::ConnectionReset => {
10853 log::error!("Server closed a workspace diagnostics pull request");
10854 continue 'request;
10855 }
10856 ConnectionResult::Result(Err(e)) => {
10857 log::error!("Error during workspace diagnostics pull: {e:#}");
10858 break 'request;
10859 }
10860 ConnectionResult::Result(Ok(pulled_diagnostics)) => {
10861 attempts = 0;
10862 if lsp_store
10863 .update(cx, |lsp_store, cx| {
10864 let workspace_diagnostics =
10865 GetDocumentDiagnostics::deserialize_workspace_diagnostics_report(pulled_diagnostics, server.server_id());
10866 for workspace_diagnostics in workspace_diagnostics {
10867 let LspPullDiagnostics::Response {
10868 server_id,
10869 uri,
10870 diagnostics,
10871 } = workspace_diagnostics.diagnostics
10872 else {
10873 continue;
10874 };
10875
10876 let adapter = lsp_store.language_server_adapter_for_id(server_id);
10877 let disk_based_sources = adapter
10878 .as_ref()
10879 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
10880 .unwrap_or(&[]);
10881
10882 match diagnostics {
10883 PulledDiagnostics::Unchanged { result_id } => {
10884 lsp_store
10885 .merge_diagnostics(
10886 server_id,
10887 lsp::PublishDiagnosticsParams {
10888 uri: uri.clone(),
10889 diagnostics: Vec::new(),
10890 version: None,
10891 },
10892 Some(result_id),
10893 DiagnosticSourceKind::Pulled,
10894 disk_based_sources,
10895 |_, _, _| true,
10896 cx,
10897 )
10898 .log_err();
10899 }
10900 PulledDiagnostics::Changed {
10901 diagnostics,
10902 result_id,
10903 } => {
10904 lsp_store
10905 .merge_diagnostics(
10906 server_id,
10907 lsp::PublishDiagnosticsParams {
10908 uri: uri.clone(),
10909 diagnostics,
10910 version: workspace_diagnostics.version,
10911 },
10912 result_id,
10913 DiagnosticSourceKind::Pulled,
10914 disk_based_sources,
10915 |buffer, old_diagnostic, cx| match old_diagnostic.source_kind {
10916 DiagnosticSourceKind::Pulled => {
10917 let buffer_url = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx))
10918 .and_then(|abs_path| file_path_to_lsp_url(&abs_path).ok());
10919 buffer_url.is_none_or(|buffer_url| buffer_url != uri)
10920 },
10921 DiagnosticSourceKind::Other
10922 | DiagnosticSourceKind::Pushed => true,
10923 },
10924 cx,
10925 )
10926 .log_err();
10927 }
10928 }
10929 }
10930 })
10931 .is_err()
10932 {
10933 return;
10934 }
10935 break 'request;
10936 }
10937 }
10938 }
10939 }
10940 });
10941
10942 Some((tx, workspace_query_language_server))
10943}
10944
10945fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
10946 let CompletionSource::BufferWord {
10947 word_range,
10948 resolved,
10949 } = &mut completion.source
10950 else {
10951 return;
10952 };
10953 if *resolved {
10954 return;
10955 }
10956
10957 if completion.new_text
10958 != snapshot
10959 .text_for_range(word_range.clone())
10960 .collect::<String>()
10961 {
10962 return;
10963 }
10964
10965 let mut offset = 0;
10966 for chunk in snapshot.chunks(word_range.clone(), true) {
10967 let end_offset = offset + chunk.text.len();
10968 if let Some(highlight_id) = chunk.syntax_highlight_id {
10969 completion
10970 .label
10971 .runs
10972 .push((offset..end_offset, highlight_id));
10973 }
10974 offset = end_offset;
10975 }
10976 *resolved = true;
10977}
10978
10979impl EventEmitter<LspStoreEvent> for LspStore {}
10980
10981fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10982 hover
10983 .contents
10984 .retain(|hover_block| !hover_block.text.trim().is_empty());
10985 if hover.contents.is_empty() {
10986 None
10987 } else {
10988 Some(hover)
10989 }
10990}
10991
10992async fn populate_labels_for_completions(
10993 new_completions: Vec<CoreCompletion>,
10994 language: Option<Arc<Language>>,
10995 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10996) -> Vec<Completion> {
10997 let lsp_completions = new_completions
10998 .iter()
10999 .filter_map(|new_completion| {
11000 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
11001 Some(lsp_completion.into_owned())
11002 } else {
11003 None
11004 }
11005 })
11006 .collect::<Vec<_>>();
11007
11008 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
11009 lsp_adapter
11010 .labels_for_completions(&lsp_completions, language)
11011 .await
11012 .log_err()
11013 .unwrap_or_default()
11014 } else {
11015 Vec::new()
11016 }
11017 .into_iter()
11018 .fuse();
11019
11020 let mut completions = Vec::new();
11021 for completion in new_completions {
11022 match completion.source.lsp_completion(true) {
11023 Some(lsp_completion) => {
11024 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
11025 Some(docs.into())
11026 } else {
11027 None
11028 };
11029
11030 let mut label = labels.next().flatten().unwrap_or_else(|| {
11031 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
11032 });
11033 ensure_uniform_list_compatible_label(&mut label);
11034 completions.push(Completion {
11035 label,
11036 documentation,
11037 replace_range: completion.replace_range,
11038 new_text: completion.new_text,
11039 insert_text_mode: lsp_completion.insert_text_mode,
11040 source: completion.source,
11041 icon_path: None,
11042 confirm: None,
11043 });
11044 }
11045 None => {
11046 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
11047 ensure_uniform_list_compatible_label(&mut label);
11048 completions.push(Completion {
11049 label,
11050 documentation: None,
11051 replace_range: completion.replace_range,
11052 new_text: completion.new_text,
11053 source: completion.source,
11054 insert_text_mode: None,
11055 icon_path: None,
11056 confirm: None,
11057 });
11058 }
11059 }
11060 }
11061 completions
11062}
11063
11064#[derive(Debug)]
11065pub enum LanguageServerToQuery {
11066 /// Query language servers in order of users preference, up until one capable of handling the request is found.
11067 FirstCapable,
11068 /// Query a specific language server.
11069 Other(LanguageServerId),
11070}
11071
11072#[derive(Default)]
11073struct RenamePathsWatchedForServer {
11074 did_rename: Vec<RenameActionPredicate>,
11075 will_rename: Vec<RenameActionPredicate>,
11076}
11077
11078impl RenamePathsWatchedForServer {
11079 fn with_did_rename_patterns(
11080 mut self,
11081 did_rename: Option<&FileOperationRegistrationOptions>,
11082 ) -> Self {
11083 if let Some(did_rename) = did_rename {
11084 self.did_rename = did_rename
11085 .filters
11086 .iter()
11087 .filter_map(|filter| filter.try_into().log_err())
11088 .collect();
11089 }
11090 self
11091 }
11092 fn with_will_rename_patterns(
11093 mut self,
11094 will_rename: Option<&FileOperationRegistrationOptions>,
11095 ) -> Self {
11096 if let Some(will_rename) = will_rename {
11097 self.will_rename = will_rename
11098 .filters
11099 .iter()
11100 .filter_map(|filter| filter.try_into().log_err())
11101 .collect();
11102 }
11103 self
11104 }
11105
11106 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
11107 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
11108 }
11109 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
11110 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
11111 }
11112}
11113
11114impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
11115 type Error = globset::Error;
11116 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
11117 Ok(Self {
11118 kind: ops.pattern.matches.clone(),
11119 glob: GlobBuilder::new(&ops.pattern.glob)
11120 .case_insensitive(
11121 ops.pattern
11122 .options
11123 .as_ref()
11124 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
11125 )
11126 .build()?
11127 .compile_matcher(),
11128 })
11129 }
11130}
11131struct RenameActionPredicate {
11132 glob: GlobMatcher,
11133 kind: Option<FileOperationPatternKind>,
11134}
11135
11136impl RenameActionPredicate {
11137 // Returns true if language server should be notified
11138 fn eval(&self, path: &str, is_dir: bool) -> bool {
11139 self.kind.as_ref().map_or(true, |kind| {
11140 let expected_kind = if is_dir {
11141 FileOperationPatternKind::Folder
11142 } else {
11143 FileOperationPatternKind::File
11144 };
11145 kind == &expected_kind
11146 }) && self.glob.is_match(path)
11147 }
11148}
11149
11150#[derive(Default)]
11151struct LanguageServerWatchedPaths {
11152 worktree_paths: HashMap<WorktreeId, GlobSet>,
11153 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
11154}
11155
11156#[derive(Default)]
11157struct LanguageServerWatchedPathsBuilder {
11158 worktree_paths: HashMap<WorktreeId, GlobSet>,
11159 abs_paths: HashMap<Arc<Path>, GlobSet>,
11160}
11161
11162impl LanguageServerWatchedPathsBuilder {
11163 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
11164 self.worktree_paths.insert(worktree_id, glob_set);
11165 }
11166 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
11167 self.abs_paths.insert(path, glob_set);
11168 }
11169 fn build(
11170 self,
11171 fs: Arc<dyn Fs>,
11172 language_server_id: LanguageServerId,
11173 cx: &mut Context<LspStore>,
11174 ) -> LanguageServerWatchedPaths {
11175 let project = cx.weak_entity();
11176
11177 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
11178 let abs_paths = self
11179 .abs_paths
11180 .into_iter()
11181 .map(|(abs_path, globset)| {
11182 let task = cx.spawn({
11183 let abs_path = abs_path.clone();
11184 let fs = fs.clone();
11185
11186 let lsp_store = project.clone();
11187 async move |_, cx| {
11188 maybe!(async move {
11189 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
11190 while let Some(update) = push_updates.0.next().await {
11191 let action = lsp_store
11192 .update(cx, |this, _| {
11193 let Some(local) = this.as_local() else {
11194 return ControlFlow::Break(());
11195 };
11196 let Some(watcher) = local
11197 .language_server_watched_paths
11198 .get(&language_server_id)
11199 else {
11200 return ControlFlow::Break(());
11201 };
11202 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
11203 "Watched abs path is not registered with a watcher",
11204 );
11205 let matching_entries = update
11206 .into_iter()
11207 .filter(|event| globs.is_match(&event.path))
11208 .collect::<Vec<_>>();
11209 this.lsp_notify_abs_paths_changed(
11210 language_server_id,
11211 matching_entries,
11212 );
11213 ControlFlow::Continue(())
11214 })
11215 .ok()?;
11216
11217 if action.is_break() {
11218 break;
11219 }
11220 }
11221 Some(())
11222 })
11223 .await;
11224 }
11225 });
11226 (abs_path, (globset, task))
11227 })
11228 .collect();
11229 LanguageServerWatchedPaths {
11230 worktree_paths: self.worktree_paths,
11231 abs_paths,
11232 }
11233 }
11234}
11235
11236struct LspBufferSnapshot {
11237 version: i32,
11238 snapshot: TextBufferSnapshot,
11239}
11240
11241/// A prompt requested by LSP server.
11242#[derive(Clone, Debug)]
11243pub struct LanguageServerPromptRequest {
11244 pub level: PromptLevel,
11245 pub message: String,
11246 pub actions: Vec<MessageActionItem>,
11247 pub lsp_name: String,
11248 pub(crate) response_channel: Sender<MessageActionItem>,
11249}
11250
11251impl LanguageServerPromptRequest {
11252 pub async fn respond(self, index: usize) -> Option<()> {
11253 if let Some(response) = self.actions.into_iter().nth(index) {
11254 self.response_channel.send(response).await.ok()
11255 } else {
11256 None
11257 }
11258 }
11259}
11260impl PartialEq for LanguageServerPromptRequest {
11261 fn eq(&self, other: &Self) -> bool {
11262 self.message == other.message && self.actions == other.actions
11263 }
11264}
11265
11266#[derive(Clone, Debug, PartialEq)]
11267pub enum LanguageServerLogType {
11268 Log(MessageType),
11269 Trace(Option<String>),
11270}
11271
11272impl LanguageServerLogType {
11273 pub fn to_proto(&self) -> proto::language_server_log::LogType {
11274 match self {
11275 Self::Log(log_type) => {
11276 let message_type = match *log_type {
11277 MessageType::ERROR => 1,
11278 MessageType::WARNING => 2,
11279 MessageType::INFO => 3,
11280 MessageType::LOG => 4,
11281 other => {
11282 log::warn!("Unknown lsp log message type: {:?}", other);
11283 4
11284 }
11285 };
11286 proto::language_server_log::LogType::LogMessageType(message_type)
11287 }
11288 Self::Trace(message) => {
11289 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
11290 message: message.clone(),
11291 })
11292 }
11293 }
11294 }
11295
11296 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
11297 match log_type {
11298 proto::language_server_log::LogType::LogMessageType(message_type) => {
11299 Self::Log(match message_type {
11300 1 => MessageType::ERROR,
11301 2 => MessageType::WARNING,
11302 3 => MessageType::INFO,
11303 4 => MessageType::LOG,
11304 _ => MessageType::LOG,
11305 })
11306 }
11307 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
11308 }
11309 }
11310}
11311
11312pub enum LanguageServerState {
11313 Starting {
11314 startup: Task<Option<Arc<LanguageServer>>>,
11315 /// List of language servers that will be added to the workspace once it's initialization completes.
11316 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
11317 },
11318
11319 Running {
11320 adapter: Arc<CachedLspAdapter>,
11321 server: Arc<LanguageServer>,
11322 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
11323 workspace_refresh_task: Option<(mpsc::Sender<()>, Task<()>)>,
11324 },
11325}
11326
11327impl LanguageServerState {
11328 fn add_workspace_folder(&self, uri: Url) {
11329 match self {
11330 LanguageServerState::Starting {
11331 pending_workspace_folders,
11332 ..
11333 } => {
11334 pending_workspace_folders.lock().insert(uri);
11335 }
11336 LanguageServerState::Running { server, .. } => {
11337 server.add_workspace_folder(uri);
11338 }
11339 }
11340 }
11341 fn _remove_workspace_folder(&self, uri: Url) {
11342 match self {
11343 LanguageServerState::Starting {
11344 pending_workspace_folders,
11345 ..
11346 } => {
11347 pending_workspace_folders.lock().remove(&uri);
11348 }
11349 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
11350 }
11351 }
11352}
11353
11354impl std::fmt::Debug for LanguageServerState {
11355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11356 match self {
11357 LanguageServerState::Starting { .. } => {
11358 f.debug_struct("LanguageServerState::Starting").finish()
11359 }
11360 LanguageServerState::Running { .. } => {
11361 f.debug_struct("LanguageServerState::Running").finish()
11362 }
11363 }
11364 }
11365}
11366
11367#[derive(Clone, Debug, Serialize)]
11368pub struct LanguageServerProgress {
11369 pub is_disk_based_diagnostics_progress: bool,
11370 pub is_cancellable: bool,
11371 pub title: Option<String>,
11372 pub message: Option<String>,
11373 pub percentage: Option<usize>,
11374 #[serde(skip_serializing)]
11375 pub last_update_at: Instant,
11376}
11377
11378#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
11379pub struct DiagnosticSummary {
11380 pub error_count: usize,
11381 pub warning_count: usize,
11382}
11383
11384impl DiagnosticSummary {
11385 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
11386 let mut this = Self {
11387 error_count: 0,
11388 warning_count: 0,
11389 };
11390
11391 for entry in diagnostics {
11392 if entry.diagnostic.is_primary {
11393 match entry.diagnostic.severity {
11394 DiagnosticSeverity::ERROR => this.error_count += 1,
11395 DiagnosticSeverity::WARNING => this.warning_count += 1,
11396 _ => {}
11397 }
11398 }
11399 }
11400
11401 this
11402 }
11403
11404 pub fn is_empty(&self) -> bool {
11405 self.error_count == 0 && self.warning_count == 0
11406 }
11407
11408 pub fn to_proto(
11409 &self,
11410 language_server_id: LanguageServerId,
11411 path: &Path,
11412 ) -> proto::DiagnosticSummary {
11413 proto::DiagnosticSummary {
11414 path: path.to_proto(),
11415 language_server_id: language_server_id.0 as u64,
11416 error_count: self.error_count as u32,
11417 warning_count: self.warning_count as u32,
11418 }
11419 }
11420}
11421
11422#[derive(Clone, Debug)]
11423pub enum CompletionDocumentation {
11424 /// There is no documentation for this completion.
11425 Undocumented,
11426 /// A single line of documentation.
11427 SingleLine(SharedString),
11428 /// Multiple lines of plain text documentation.
11429 MultiLinePlainText(SharedString),
11430 /// Markdown documentation.
11431 MultiLineMarkdown(SharedString),
11432 /// Both single line and multiple lines of plain text documentation.
11433 SingleLineAndMultiLinePlainText {
11434 single_line: SharedString,
11435 plain_text: Option<SharedString>,
11436 },
11437}
11438
11439impl From<lsp::Documentation> for CompletionDocumentation {
11440 fn from(docs: lsp::Documentation) -> Self {
11441 match docs {
11442 lsp::Documentation::String(text) => {
11443 if text.lines().count() <= 1 {
11444 CompletionDocumentation::SingleLine(text.into())
11445 } else {
11446 CompletionDocumentation::MultiLinePlainText(text.into())
11447 }
11448 }
11449
11450 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
11451 lsp::MarkupKind::PlainText => {
11452 if value.lines().count() <= 1 {
11453 CompletionDocumentation::SingleLine(value.into())
11454 } else {
11455 CompletionDocumentation::MultiLinePlainText(value.into())
11456 }
11457 }
11458
11459 lsp::MarkupKind::Markdown => {
11460 CompletionDocumentation::MultiLineMarkdown(value.into())
11461 }
11462 },
11463 }
11464 }
11465}
11466
11467fn glob_literal_prefix(glob: &Path) -> PathBuf {
11468 glob.components()
11469 .take_while(|component| match component {
11470 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
11471 _ => true,
11472 })
11473 .collect()
11474}
11475
11476pub struct SshLspAdapter {
11477 name: LanguageServerName,
11478 binary: LanguageServerBinary,
11479 initialization_options: Option<String>,
11480 code_action_kinds: Option<Vec<CodeActionKind>>,
11481}
11482
11483impl SshLspAdapter {
11484 pub fn new(
11485 name: LanguageServerName,
11486 binary: LanguageServerBinary,
11487 initialization_options: Option<String>,
11488 code_action_kinds: Option<String>,
11489 ) -> Self {
11490 Self {
11491 name,
11492 binary,
11493 initialization_options,
11494 code_action_kinds: code_action_kinds
11495 .as_ref()
11496 .and_then(|c| serde_json::from_str(c).ok()),
11497 }
11498 }
11499}
11500
11501#[async_trait(?Send)]
11502impl LspAdapter for SshLspAdapter {
11503 fn name(&self) -> LanguageServerName {
11504 self.name.clone()
11505 }
11506
11507 async fn initialization_options(
11508 self: Arc<Self>,
11509 _: &dyn Fs,
11510 _: &Arc<dyn LspAdapterDelegate>,
11511 ) -> Result<Option<serde_json::Value>> {
11512 let Some(options) = &self.initialization_options else {
11513 return Ok(None);
11514 };
11515 let result = serde_json::from_str(options)?;
11516 Ok(result)
11517 }
11518
11519 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
11520 self.code_action_kinds.clone()
11521 }
11522
11523 async fn check_if_user_installed(
11524 &self,
11525 _: &dyn LspAdapterDelegate,
11526 _: Arc<dyn LanguageToolchainStore>,
11527 _: &AsyncApp,
11528 ) -> Option<LanguageServerBinary> {
11529 Some(self.binary.clone())
11530 }
11531
11532 async fn cached_server_binary(
11533 &self,
11534 _: PathBuf,
11535 _: &dyn LspAdapterDelegate,
11536 ) -> Option<LanguageServerBinary> {
11537 None
11538 }
11539
11540 async fn fetch_latest_server_version(
11541 &self,
11542 _: &dyn LspAdapterDelegate,
11543 ) -> Result<Box<dyn 'static + Send + Any>> {
11544 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
11545 }
11546
11547 async fn fetch_server_binary(
11548 &self,
11549 _: Box<dyn 'static + Send + Any>,
11550 _: PathBuf,
11551 _: &dyn LspAdapterDelegate,
11552 ) -> Result<LanguageServerBinary> {
11553 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
11554 }
11555}
11556
11557pub fn language_server_settings<'a>(
11558 delegate: &'a dyn LspAdapterDelegate,
11559 language: &LanguageServerName,
11560 cx: &'a App,
11561) -> Option<&'a LspSettings> {
11562 language_server_settings_for(
11563 SettingsLocation {
11564 worktree_id: delegate.worktree_id(),
11565 path: delegate.worktree_root_path(),
11566 },
11567 language,
11568 cx,
11569 )
11570}
11571
11572pub(crate) fn language_server_settings_for<'a>(
11573 location: SettingsLocation<'a>,
11574 language: &LanguageServerName,
11575 cx: &'a App,
11576) -> Option<&'a LspSettings> {
11577 ProjectSettings::get(Some(location), cx).lsp.get(language)
11578}
11579
11580pub struct LocalLspAdapterDelegate {
11581 lsp_store: WeakEntity<LspStore>,
11582 worktree: worktree::Snapshot,
11583 fs: Arc<dyn Fs>,
11584 http_client: Arc<dyn HttpClient>,
11585 language_registry: Arc<LanguageRegistry>,
11586 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
11587}
11588
11589impl LocalLspAdapterDelegate {
11590 pub fn new(
11591 language_registry: Arc<LanguageRegistry>,
11592 environment: &Entity<ProjectEnvironment>,
11593 lsp_store: WeakEntity<LspStore>,
11594 worktree: &Entity<Worktree>,
11595 http_client: Arc<dyn HttpClient>,
11596 fs: Arc<dyn Fs>,
11597 cx: &mut App,
11598 ) -> Arc<Self> {
11599 let load_shell_env_task = environment.update(cx, |env, cx| {
11600 env.get_worktree_environment(worktree.clone(), cx)
11601 });
11602
11603 Arc::new(Self {
11604 lsp_store,
11605 worktree: worktree.read(cx).snapshot(),
11606 fs,
11607 http_client,
11608 language_registry,
11609 load_shell_env_task,
11610 })
11611 }
11612
11613 fn from_local_lsp(
11614 local: &LocalLspStore,
11615 worktree: &Entity<Worktree>,
11616 cx: &mut App,
11617 ) -> Arc<Self> {
11618 Self::new(
11619 local.languages.clone(),
11620 &local.environment,
11621 local.weak.clone(),
11622 worktree,
11623 local.http_client.clone(),
11624 local.fs.clone(),
11625 cx,
11626 )
11627 }
11628}
11629
11630#[async_trait]
11631impl LspAdapterDelegate for LocalLspAdapterDelegate {
11632 fn show_notification(&self, message: &str, cx: &mut App) {
11633 self.lsp_store
11634 .update(cx, |_, cx| {
11635 cx.emit(LspStoreEvent::Notification(message.to_owned()))
11636 })
11637 .ok();
11638 }
11639
11640 fn http_client(&self) -> Arc<dyn HttpClient> {
11641 self.http_client.clone()
11642 }
11643
11644 fn worktree_id(&self) -> WorktreeId {
11645 self.worktree.id()
11646 }
11647
11648 fn worktree_root_path(&self) -> &Path {
11649 self.worktree.abs_path().as_ref()
11650 }
11651
11652 async fn shell_env(&self) -> HashMap<String, String> {
11653 let task = self.load_shell_env_task.clone();
11654 task.await.unwrap_or_default()
11655 }
11656
11657 async fn npm_package_installed_version(
11658 &self,
11659 package_name: &str,
11660 ) -> Result<Option<(PathBuf, String)>> {
11661 let local_package_directory = self.worktree_root_path();
11662 let node_modules_directory = local_package_directory.join("node_modules");
11663
11664 if let Some(version) =
11665 read_package_installed_version(node_modules_directory.clone(), package_name).await?
11666 {
11667 return Ok(Some((node_modules_directory, version)));
11668 }
11669 let Some(npm) = self.which("npm".as_ref()).await else {
11670 log::warn!(
11671 "Failed to find npm executable for {:?}",
11672 local_package_directory
11673 );
11674 return Ok(None);
11675 };
11676
11677 let env = self.shell_env().await;
11678 let output = util::command::new_smol_command(&npm)
11679 .args(["root", "-g"])
11680 .envs(env)
11681 .current_dir(local_package_directory)
11682 .output()
11683 .await?;
11684 let global_node_modules =
11685 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
11686
11687 if let Some(version) =
11688 read_package_installed_version(global_node_modules.clone(), package_name).await?
11689 {
11690 return Ok(Some((global_node_modules, version)));
11691 }
11692 return Ok(None);
11693 }
11694
11695 #[cfg(not(target_os = "windows"))]
11696 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11697 let worktree_abs_path = self.worktree.abs_path();
11698 let shell_path = self.shell_env().await.get("PATH").cloned();
11699 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
11700 }
11701
11702 #[cfg(target_os = "windows")]
11703 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11704 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11705 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11706 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11707 which::which(command).ok()
11708 }
11709
11710 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
11711 let working_dir = self.worktree_root_path();
11712 let output = util::command::new_smol_command(&command.path)
11713 .args(command.arguments)
11714 .envs(command.env.clone().unwrap_or_default())
11715 .current_dir(working_dir)
11716 .output()
11717 .await?;
11718
11719 anyhow::ensure!(
11720 output.status.success(),
11721 "{}, stdout: {:?}, stderr: {:?}",
11722 output.status,
11723 String::from_utf8_lossy(&output.stdout),
11724 String::from_utf8_lossy(&output.stderr)
11725 );
11726 Ok(())
11727 }
11728
11729 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
11730 self.language_registry
11731 .update_lsp_binary_status(server_name, status);
11732 }
11733
11734 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
11735 self.language_registry
11736 .all_lsp_adapters()
11737 .into_iter()
11738 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
11739 .collect()
11740 }
11741
11742 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
11743 let dir = self.language_registry.language_server_download_dir(name)?;
11744
11745 if !dir.exists() {
11746 smol::fs::create_dir_all(&dir)
11747 .await
11748 .context("failed to create container directory")
11749 .log_err()?;
11750 }
11751
11752 Some(dir)
11753 }
11754
11755 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11756 let entry = self
11757 .worktree
11758 .entry_for_path(&path)
11759 .with_context(|| format!("no worktree entry for path {path:?}"))?;
11760 let abs_path = self
11761 .worktree
11762 .absolutize(&entry.path)
11763 .with_context(|| format!("cannot absolutize path {path:?}"))?;
11764
11765 self.fs.load(&abs_path).await
11766 }
11767}
11768
11769async fn populate_labels_for_symbols(
11770 symbols: Vec<CoreSymbol>,
11771 language_registry: &Arc<LanguageRegistry>,
11772 lsp_adapter: Option<Arc<CachedLspAdapter>>,
11773 output: &mut Vec<Symbol>,
11774) {
11775 #[allow(clippy::mutable_key_type)]
11776 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
11777
11778 let mut unknown_paths = BTreeSet::new();
11779 for symbol in symbols {
11780 let language = language_registry
11781 .language_for_file_path(&symbol.path.path)
11782 .await
11783 .ok()
11784 .or_else(|| {
11785 unknown_paths.insert(symbol.path.path.clone());
11786 None
11787 });
11788 symbols_by_language
11789 .entry(language)
11790 .or_default()
11791 .push(symbol);
11792 }
11793
11794 for unknown_path in unknown_paths {
11795 log::info!(
11796 "no language found for symbol path {}",
11797 unknown_path.display()
11798 );
11799 }
11800
11801 let mut label_params = Vec::new();
11802 for (language, mut symbols) in symbols_by_language {
11803 label_params.clear();
11804 label_params.extend(
11805 symbols
11806 .iter_mut()
11807 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
11808 );
11809
11810 let mut labels = Vec::new();
11811 if let Some(language) = language {
11812 let lsp_adapter = lsp_adapter.clone().or_else(|| {
11813 language_registry
11814 .lsp_adapters(&language.name())
11815 .first()
11816 .cloned()
11817 });
11818 if let Some(lsp_adapter) = lsp_adapter {
11819 labels = lsp_adapter
11820 .labels_for_symbols(&label_params, &language)
11821 .await
11822 .log_err()
11823 .unwrap_or_default();
11824 }
11825 }
11826
11827 for ((symbol, (name, _)), label) in symbols
11828 .into_iter()
11829 .zip(label_params.drain(..))
11830 .zip(labels.into_iter().chain(iter::repeat(None)))
11831 {
11832 output.push(Symbol {
11833 language_server_name: symbol.language_server_name,
11834 source_worktree_id: symbol.source_worktree_id,
11835 source_language_server_id: symbol.source_language_server_id,
11836 path: symbol.path,
11837 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
11838 name,
11839 kind: symbol.kind,
11840 range: symbol.range,
11841 signature: symbol.signature,
11842 });
11843 }
11844 }
11845}
11846
11847fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
11848 match server.capabilities().text_document_sync.as_ref()? {
11849 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
11850 lsp::TextDocumentSyncKind::NONE => None,
11851 lsp::TextDocumentSyncKind::FULL => Some(true),
11852 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
11853 _ => None,
11854 },
11855 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
11856 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
11857 if *supported {
11858 Some(true)
11859 } else {
11860 None
11861 }
11862 }
11863 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
11864 Some(save_options.include_text.unwrap_or(false))
11865 }
11866 },
11867 }
11868}
11869
11870/// Completion items are displayed in a `UniformList`.
11871/// Usually, those items are single-line strings, but in LSP responses,
11872/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
11873/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
11874/// 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,
11875/// breaking the completions menu presentation.
11876///
11877/// 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.
11878fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
11879 let mut new_text = String::with_capacity(label.text.len());
11880 let mut offset_map = vec![0; label.text.len() + 1];
11881 let mut last_char_was_space = false;
11882 let mut new_idx = 0;
11883 let mut chars = label.text.char_indices().fuse();
11884 let mut newlines_removed = false;
11885
11886 while let Some((idx, c)) = chars.next() {
11887 offset_map[idx] = new_idx;
11888
11889 match c {
11890 '\n' if last_char_was_space => {
11891 newlines_removed = true;
11892 }
11893 '\t' | ' ' if last_char_was_space => {}
11894 '\n' if !last_char_was_space => {
11895 new_text.push(' ');
11896 new_idx += 1;
11897 last_char_was_space = true;
11898 newlines_removed = true;
11899 }
11900 ' ' | '\t' => {
11901 new_text.push(' ');
11902 new_idx += 1;
11903 last_char_was_space = true;
11904 }
11905 _ => {
11906 new_text.push(c);
11907 new_idx += c.len_utf8();
11908 last_char_was_space = false;
11909 }
11910 }
11911 }
11912 offset_map[label.text.len()] = new_idx;
11913
11914 // Only modify the label if newlines were removed.
11915 if !newlines_removed {
11916 return;
11917 }
11918
11919 let last_index = new_idx;
11920 let mut run_ranges_errors = Vec::new();
11921 label.runs.retain_mut(|(range, _)| {
11922 match offset_map.get(range.start) {
11923 Some(&start) => range.start = start,
11924 None => {
11925 run_ranges_errors.push(range.clone());
11926 return false;
11927 }
11928 }
11929
11930 match offset_map.get(range.end) {
11931 Some(&end) => range.end = end,
11932 None => {
11933 run_ranges_errors.push(range.clone());
11934 range.end = last_index;
11935 }
11936 }
11937 true
11938 });
11939 if !run_ranges_errors.is_empty() {
11940 log::error!(
11941 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
11942 label.text
11943 );
11944 }
11945
11946 let mut wrong_filter_range = None;
11947 if label.filter_range == (0..label.text.len()) {
11948 label.filter_range = 0..new_text.len();
11949 } else {
11950 let mut original_filter_range = Some(label.filter_range.clone());
11951 match offset_map.get(label.filter_range.start) {
11952 Some(&start) => label.filter_range.start = start,
11953 None => {
11954 wrong_filter_range = original_filter_range.take();
11955 label.filter_range.start = last_index;
11956 }
11957 }
11958
11959 match offset_map.get(label.filter_range.end) {
11960 Some(&end) => label.filter_range.end = end,
11961 None => {
11962 wrong_filter_range = original_filter_range.take();
11963 label.filter_range.end = last_index;
11964 }
11965 }
11966 }
11967 if let Some(wrong_filter_range) = wrong_filter_range {
11968 log::error!(
11969 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
11970 label.text
11971 );
11972 }
11973
11974 label.text = new_text;
11975}
11976
11977#[cfg(test)]
11978mod tests {
11979 use language::HighlightId;
11980
11981 use super::*;
11982
11983 #[test]
11984 fn test_glob_literal_prefix() {
11985 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
11986 assert_eq!(
11987 glob_literal_prefix(Path::new("node_modules/**/*.js")),
11988 Path::new("node_modules")
11989 );
11990 assert_eq!(
11991 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
11992 Path::new("foo")
11993 );
11994 assert_eq!(
11995 glob_literal_prefix(Path::new("foo/bar/baz.js")),
11996 Path::new("foo/bar/baz.js")
11997 );
11998
11999 #[cfg(target_os = "windows")]
12000 {
12001 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
12002 assert_eq!(
12003 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
12004 Path::new("node_modules")
12005 );
12006 assert_eq!(
12007 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12008 Path::new("foo")
12009 );
12010 assert_eq!(
12011 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
12012 Path::new("foo/bar/baz.js")
12013 );
12014 }
12015 }
12016
12017 #[test]
12018 fn test_multi_len_chars_normalization() {
12019 let mut label = CodeLabel {
12020 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
12021 runs: vec![(0..6, HighlightId(1))],
12022 filter_range: 0..6,
12023 };
12024 ensure_uniform_list_compatible_label(&mut label);
12025 assert_eq!(
12026 label,
12027 CodeLabel {
12028 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
12029 runs: vec![(0..6, HighlightId(1))],
12030 filter_range: 0..6,
12031 }
12032 );
12033 }
12034}