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