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