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