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