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