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