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