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