1pub mod clangd_ext;
2pub mod lsp_ext_command;
3pub mod rust_analyzer_ext;
4
5use crate::{
6 CodeAction, Completion, CompletionSource, CoreCompletion, Hover, InlayHint, LspAction,
7 ProjectItem, ProjectPath, ProjectTransaction, ResolveState, Symbol, ToolchainStore,
8 buffer_store::{BufferStore, BufferStoreEvent},
9 environment::ProjectEnvironment,
10 lsp_command::{self, *},
11 manifest_tree::{AdapterQuery, LanguageServerTree, LaunchDisposition, ManifestTree},
12 prettier_store::{self, PrettierStore, PrettierStoreEvent},
13 project_settings::{LspSettings, ProjectSettings},
14 relativize_path, resolve_path,
15 toolchain_store::{EmptyToolchainStore, ToolchainStoreEvent},
16 worktree_store::{WorktreeStore, WorktreeStoreEvent},
17 yarn::YarnPathStore,
18};
19use anyhow::{Context as _, Result, anyhow};
20use async_trait::async_trait;
21use client::{TypedEnvelope, proto};
22use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
23use futures::{
24 AsyncWriteExt, Future, FutureExt, StreamExt,
25 future::{Shared, join_all},
26 select, select_biased,
27 stream::FuturesUnordered,
28};
29use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
30use gpui::{
31 App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString, Task,
32 WeakEntity,
33};
34use http_client::HttpClient;
35use itertools::Itertools as _;
36use language::{
37 Bias, BinaryStatus, Buffer, BufferSnapshot, CachedLspAdapter, CodeLabel, Diagnostic,
38 DiagnosticEntry, DiagnosticSet, Diff, File as _, Language, LanguageRegistry,
39 LanguageToolchainStore, LocalFile, LspAdapter, LspAdapterDelegate, Patch, PointUtf16,
40 TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
41 language_settings::{
42 FormatOnSave, Formatter, LanguageSettings, SelectedFormatter, language_settings,
43 },
44 point_to_lsp,
45 proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
46 range_from_lsp, range_to_lsp,
47};
48use lsp::{
49 CodeActionKind, CompletionContext, DiagnosticSeverity, DiagnosticTag,
50 DidChangeWatchedFilesRegistrationOptions, Edit, FileOperationFilter, FileOperationPatternKind,
51 FileOperationRegistrationOptions, FileRename, FileSystemWatcher, LanguageServer,
52 LanguageServerBinary, LanguageServerBinaryOptions, LanguageServerId, LanguageServerName,
53 LspRequestFuture, MessageActionItem, MessageType, OneOf, RenameFilesParams, SymbolKind,
54 TextEdit, WillRenameFiles, WorkDoneProgressCancelParams, WorkspaceFolder,
55 notification::DidRenameFiles,
56};
57use node_runtime::read_package_installed_version;
58use parking_lot::Mutex;
59use postage::watch;
60use rand::prelude::*;
61
62use rpc::{
63 AnyProtoClient,
64 proto::{FromProto, ToProto},
65};
66use serde::Serialize;
67use settings::{Settings, SettingsLocation, SettingsStore};
68use sha2::{Digest, Sha256};
69use smol::channel::Sender;
70use snippet::Snippet;
71use std::{
72 any::Any,
73 borrow::Cow,
74 cell::RefCell,
75 cmp::Ordering,
76 convert::TryInto,
77 ffi::OsStr,
78 iter, mem,
79 ops::{ControlFlow, Range},
80 path::{self, Path, PathBuf},
81 rc::Rc,
82 sync::Arc,
83 time::{Duration, Instant},
84};
85use text::{Anchor, BufferId, LineEnding, OffsetRangeExt};
86use url::Url;
87use util::{
88 ResultExt, TryFutureExt as _, debug_panic, defer, maybe, merge_json_value_into,
89 paths::SanitizedPath, post_inc,
90};
91
92pub use fs::*;
93pub use language::Location;
94#[cfg(any(test, feature = "test-support"))]
95pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
96pub use worktree::{
97 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
98 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
99};
100
101const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
102pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum FormatTrigger {
106 Save,
107 Manual,
108}
109
110pub enum LspFormatTarget {
111 Buffers,
112 Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
113}
114
115pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
116
117impl FormatTrigger {
118 fn from_proto(value: i32) -> FormatTrigger {
119 match value {
120 0 => FormatTrigger::Save,
121 1 => FormatTrigger::Manual,
122 _ => FormatTrigger::Save,
123 }
124 }
125}
126
127pub struct LocalLspStore {
128 weak: WeakEntity<LspStore>,
129 worktree_store: Entity<WorktreeStore>,
130 toolchain_store: Entity<ToolchainStore>,
131 http_client: Arc<dyn HttpClient>,
132 environment: Entity<ProjectEnvironment>,
133 fs: Arc<dyn Fs>,
134 languages: Arc<LanguageRegistry>,
135 language_server_ids: HashMap<(WorktreeId, LanguageServerName), BTreeSet<LanguageServerId>>,
136 yarn: Entity<YarnPathStore>,
137 pub language_servers: HashMap<LanguageServerId, LanguageServerState>,
138 buffers_being_formatted: HashSet<BufferId>,
139 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
140 language_server_watched_paths: HashMap<LanguageServerId, LanguageServerWatchedPaths>,
141 language_server_paths_watched_for_rename:
142 HashMap<LanguageServerId, RenamePathsWatchedForServer>,
143 language_server_watcher_registrations:
144 HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
145 supplementary_language_servers:
146 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
147 prettier_store: Entity<PrettierStore>,
148 next_diagnostic_group_id: usize,
149 diagnostics: HashMap<
150 WorktreeId,
151 HashMap<
152 Arc<Path>,
153 Vec<(
154 LanguageServerId,
155 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
156 )>,
157 >,
158 >,
159 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
160 _subscription: gpui::Subscription,
161 lsp_tree: Entity<LanguageServerTree>,
162 registered_buffers: HashMap<BufferId, usize>,
163}
164
165impl LocalLspStore {
166 /// Returns the running language server for the given ID. Note if the language server is starting, it will not be returned.
167 pub fn running_language_server_for_id(
168 &self,
169 id: LanguageServerId,
170 ) -> Option<&Arc<LanguageServer>> {
171 let language_server_state = self.language_servers.get(&id)?;
172
173 match language_server_state {
174 LanguageServerState::Running { server, .. } => Some(server),
175 LanguageServerState::Starting { .. } => None,
176 }
177 }
178
179 fn start_language_server(
180 &mut self,
181 worktree_handle: &Entity<Worktree>,
182 delegate: Arc<LocalLspAdapterDelegate>,
183 adapter: Arc<CachedLspAdapter>,
184 settings: Arc<LspSettings>,
185 cx: &mut App,
186 ) -> LanguageServerId {
187 let worktree = worktree_handle.read(cx);
188 let worktree_id = worktree.id();
189 let root_path = worktree.abs_path();
190 let key = (worktree_id, adapter.name.clone());
191
192 let override_options = settings.initialization_options.clone();
193
194 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
195
196 let server_id = self.languages.next_language_server_id();
197 log::info!(
198 "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
199 adapter.name.0
200 );
201
202 let binary = self.get_language_server_binary(adapter.clone(), delegate.clone(), true, cx);
203 let pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
204 let pending_server = cx.spawn({
205 let adapter = adapter.clone();
206 let server_name = adapter.name.clone();
207 let stderr_capture = stderr_capture.clone();
208 #[cfg(any(test, feature = "test-support"))]
209 let lsp_store = self.weak.clone();
210 let pending_workspace_folders = pending_workspace_folders.clone();
211 async move |cx| {
212 let binary = binary.await?;
213 #[cfg(any(test, feature = "test-support"))]
214 if let Some(server) = lsp_store
215 .update(&mut cx.clone(), |this, cx| {
216 this.languages.create_fake_language_server(
217 server_id,
218 &server_name,
219 binary.clone(),
220 &mut cx.to_async(),
221 )
222 })
223 .ok()
224 .flatten()
225 {
226 return Ok(server);
227 }
228
229 lsp::LanguageServer::new(
230 stderr_capture,
231 server_id,
232 server_name,
233 binary,
234 &root_path,
235 adapter.code_action_kinds(),
236 pending_workspace_folders,
237 cx,
238 )
239 }
240 });
241
242 let startup = {
243 let server_name = adapter.name.0.clone();
244 let delegate = delegate as Arc<dyn LspAdapterDelegate>;
245 let key = key.clone();
246 let adapter = adapter.clone();
247 let this = self.weak.clone();
248 let pending_workspace_folders = pending_workspace_folders.clone();
249 let fs = self.fs.clone();
250 cx.spawn(async move |cx| {
251 let result = async {
252 let toolchains = this.update(cx, |this, cx| this.toolchain_store(cx))?;
253 let language_server = pending_server.await?;
254
255 let workspace_config = Self::workspace_configuration_for_adapter(
256 adapter.adapter.clone(),
257 fs.as_ref(),
258 &delegate,
259 toolchains.clone(),
260 cx,
261 )
262 .await?;
263
264 let mut initialization_options = Self::initialization_options_for_adapter(
265 adapter.adapter.clone(),
266 fs.as_ref(),
267 &delegate,
268 )
269 .await?;
270
271 match (&mut initialization_options, override_options) {
272 (Some(initialization_options), Some(override_options)) => {
273 merge_json_value_into(override_options, initialization_options);
274 }
275 (None, override_options) => initialization_options = override_options,
276 _ => {}
277 }
278
279 let initialization_params = cx.update(|cx| {
280 let mut params = language_server.default_initialize_params(cx);
281 params.initialization_options = initialization_options;
282 adapter.adapter.prepare_initialize_params(params)
283 })??;
284
285 Self::setup_lsp_messages(
286 this.clone(),
287 fs,
288 &language_server,
289 delegate.clone(),
290 adapter.clone(),
291 );
292
293 let did_change_configuration_params =
294 Arc::new(lsp::DidChangeConfigurationParams {
295 settings: workspace_config,
296 });
297 let language_server = cx
298 .update(|cx| {
299 language_server.initialize(
300 initialization_params,
301 did_change_configuration_params.clone(),
302 cx,
303 )
304 })?
305 .await
306 .inspect_err(|_| {
307 if let Some(this) = this.upgrade() {
308 this.update(cx, |_, cx| {
309 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id))
310 })
311 .ok();
312 }
313 })?;
314
315 language_server
316 .notify::<lsp::notification::DidChangeConfiguration>(
317 &did_change_configuration_params,
318 )
319 .ok();
320
321 anyhow::Ok(language_server)
322 }
323 .await;
324
325 match result {
326 Ok(server) => {
327 this.update(cx, |this, mut cx| {
328 this.insert_newly_running_language_server(
329 adapter,
330 server.clone(),
331 server_id,
332 key,
333 pending_workspace_folders,
334 &mut cx,
335 );
336 })
337 .ok();
338 stderr_capture.lock().take();
339 Some(server)
340 }
341
342 Err(err) => {
343 let log = stderr_capture.lock().take().unwrap_or_default();
344 delegate.update_status(
345 adapter.name(),
346 BinaryStatus::Failed {
347 error: format!("{err}\n-- stderr--\n{}", log),
348 },
349 );
350 log::error!("Failed to start language server {server_name:?}: {err}");
351 log::error!("server stderr: {:?}", log);
352 None
353 }
354 }
355 })
356 };
357 let state = LanguageServerState::Starting {
358 startup,
359 pending_workspace_folders,
360 };
361
362 self.language_servers.insert(server_id, state);
363 self.language_server_ids
364 .entry(key)
365 .or_default()
366 .insert(server_id);
367 server_id
368 }
369
370 fn get_language_server_binary(
371 &self,
372 adapter: Arc<CachedLspAdapter>,
373 delegate: Arc<dyn LspAdapterDelegate>,
374 allow_binary_download: bool,
375 cx: &mut App,
376 ) -> Task<Result<LanguageServerBinary>> {
377 let settings = ProjectSettings::get(
378 Some(SettingsLocation {
379 worktree_id: delegate.worktree_id(),
380 path: Path::new(""),
381 }),
382 cx,
383 )
384 .lsp
385 .get(&adapter.name)
386 .and_then(|s| s.binary.clone());
387
388 if settings.as_ref().is_some_and(|b| b.path.is_some()) {
389 let settings = settings.unwrap();
390
391 return cx.spawn(async move |_| {
392 let mut env = delegate.shell_env().await;
393 env.extend(settings.env.unwrap_or_default());
394
395 Ok(LanguageServerBinary {
396 path: PathBuf::from(&settings.path.unwrap()),
397 env: Some(env),
398 arguments: settings
399 .arguments
400 .unwrap_or_default()
401 .iter()
402 .map(Into::into)
403 .collect(),
404 })
405 });
406 }
407 let lsp_binary_options = LanguageServerBinaryOptions {
408 allow_path_lookup: !settings
409 .as_ref()
410 .and_then(|b| b.ignore_system_version)
411 .unwrap_or_default(),
412 allow_binary_download,
413 };
414 let toolchains = self.toolchain_store.read(cx).as_language_toolchain_store();
415 cx.spawn(async move |cx| {
416 let binary_result = adapter
417 .clone()
418 .get_language_server_command(delegate.clone(), toolchains, lsp_binary_options, cx)
419 .await;
420
421 delegate.update_status(adapter.name.clone(), BinaryStatus::None);
422
423 let mut binary = binary_result?;
424 let mut shell_env = delegate.shell_env().await;
425
426 if let Some(settings) = settings {
427 if let Some(arguments) = settings.arguments {
428 binary.arguments = arguments.into_iter().map(Into::into).collect();
429 }
430 if let Some(env) = settings.env {
431 shell_env.extend(env);
432 }
433 }
434
435 binary.env = Some(shell_env);
436 Ok(binary)
437 })
438 }
439
440 fn setup_lsp_messages(
441 this: WeakEntity<LspStore>,
442 fs: Arc<dyn Fs>,
443 language_server: &LanguageServer,
444 delegate: Arc<dyn LspAdapterDelegate>,
445 adapter: Arc<CachedLspAdapter>,
446 ) {
447 let name = language_server.name();
448 let server_id = language_server.server_id();
449 language_server
450 .on_notification::<lsp::notification::PublishDiagnostics, _>({
451 let adapter = adapter.clone();
452 let this = this.clone();
453 move |mut params, cx| {
454 let adapter = adapter.clone();
455 if let Some(this) = this.upgrade() {
456 this.update(cx, |this, cx| {
457 {
458 let buffer = params
459 .uri
460 .to_file_path()
461 .map(|file_path| this.get_buffer(&file_path, cx))
462 .ok()
463 .flatten();
464 adapter.process_diagnostics(&mut params, server_id, buffer);
465 }
466
467 this.update_diagnostics(
468 server_id,
469 params,
470 &adapter.disk_based_diagnostic_sources,
471 cx,
472 )
473 .log_err();
474 })
475 .ok();
476 }
477 }
478 })
479 .detach();
480 language_server
481 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
482 let adapter = adapter.adapter.clone();
483 let delegate = delegate.clone();
484 let this = this.clone();
485 let fs = fs.clone();
486 move |params, cx| {
487 let adapter = adapter.clone();
488 let delegate = delegate.clone();
489 let this = this.clone();
490 let fs = fs.clone();
491 let mut cx = cx.clone();
492 async move {
493 let toolchains =
494 this.update(&mut cx, |this, cx| this.toolchain_store(cx))?;
495
496 let workspace_config = Self::workspace_configuration_for_adapter(
497 adapter.clone(),
498 fs.as_ref(),
499 &delegate,
500 toolchains.clone(),
501 &mut cx,
502 )
503 .await?;
504
505 Ok(params
506 .items
507 .into_iter()
508 .map(|item| {
509 if let Some(section) = &item.section {
510 workspace_config
511 .get(section)
512 .cloned()
513 .unwrap_or(serde_json::Value::Null)
514 } else {
515 workspace_config.clone()
516 }
517 })
518 .collect())
519 }
520 }
521 })
522 .detach();
523
524 language_server
525 .on_request::<lsp::request::WorkspaceFoldersRequest, _, _>({
526 let this = this.clone();
527 move |_, cx| {
528 let this = this.clone();
529 let mut cx = cx.clone();
530 async move {
531 let Some(server) =
532 this.update(&mut cx, |this, _| this.language_server_for_id(server_id))?
533 else {
534 return Ok(None);
535 };
536 let root = server.workspace_folders();
537 Ok(Some(
538 root.iter()
539 .cloned()
540 .map(|uri| WorkspaceFolder {
541 uri,
542 name: Default::default(),
543 })
544 .collect(),
545 ))
546 }
547 }
548 })
549 .detach();
550 // Even though we don't have handling for these requests, respond to them to
551 // avoid stalling any language server like `gopls` which waits for a response
552 // to these requests when initializing.
553 language_server
554 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
555 let this = this.clone();
556 move |params, cx| {
557 let this = this.clone();
558 let mut cx = cx.clone();
559 async move {
560 this.update(&mut cx, |this, _| {
561 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
562 {
563 if let lsp::NumberOrString::String(token) = params.token {
564 status.progress_tokens.insert(token);
565 }
566 }
567 })?;
568
569 Ok(())
570 }
571 }
572 })
573 .detach();
574
575 language_server
576 .on_request::<lsp::request::RegisterCapability, _, _>({
577 let this = this.clone();
578 move |params, cx| {
579 let this = this.clone();
580 let mut cx = cx.clone();
581 async move {
582 for reg in params.registrations {
583 match reg.method.as_str() {
584 "workspace/didChangeWatchedFiles" => {
585 if let Some(options) = reg.register_options {
586 let options = serde_json::from_value(options)?;
587 this.update(&mut cx, |this, cx| {
588 this.as_local_mut()?.on_lsp_did_change_watched_files(
589 server_id, ®.id, options, cx,
590 );
591 Some(())
592 })?;
593 }
594 }
595 "textDocument/rangeFormatting" => {
596 this.update(&mut cx, |this, _| {
597 if let Some(server) = this.language_server_for_id(server_id)
598 {
599 let options = reg
600 .register_options
601 .map(|options| {
602 serde_json::from_value::<
603 lsp::DocumentRangeFormattingOptions,
604 >(
605 options
606 )
607 })
608 .transpose()?;
609 let provider = match options {
610 None => OneOf::Left(true),
611 Some(options) => OneOf::Right(options),
612 };
613 server.update_capabilities(|capabilities| {
614 capabilities.document_range_formatting_provider =
615 Some(provider);
616 })
617 }
618 anyhow::Ok(())
619 })??;
620 }
621 "textDocument/onTypeFormatting" => {
622 this.update(&mut cx, |this, _| {
623 if let Some(server) = this.language_server_for_id(server_id)
624 {
625 let options = reg
626 .register_options
627 .map(|options| {
628 serde_json::from_value::<
629 lsp::DocumentOnTypeFormattingOptions,
630 >(
631 options
632 )
633 })
634 .transpose()?;
635 if let Some(options) = options {
636 server.update_capabilities(|capabilities| {
637 capabilities
638 .document_on_type_formatting_provider =
639 Some(options);
640 })
641 }
642 }
643 anyhow::Ok(())
644 })??;
645 }
646 "textDocument/formatting" => {
647 this.update(&mut cx, |this, _| {
648 if let Some(server) = this.language_server_for_id(server_id)
649 {
650 let options = reg
651 .register_options
652 .map(|options| {
653 serde_json::from_value::<
654 lsp::DocumentFormattingOptions,
655 >(
656 options
657 )
658 })
659 .transpose()?;
660 let provider = match options {
661 None => OneOf::Left(true),
662 Some(options) => OneOf::Right(options),
663 };
664 server.update_capabilities(|capabilities| {
665 capabilities.document_formatting_provider =
666 Some(provider);
667 })
668 }
669 anyhow::Ok(())
670 })??;
671 }
672 "workspace/didChangeConfiguration" => {
673 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
674 }
675 "textDocument/rename" => {
676 this.update(&mut cx, |this, _| {
677 if let Some(server) = this.language_server_for_id(server_id)
678 {
679 let options = reg
680 .register_options
681 .map(|options| {
682 serde_json::from_value::<lsp::RenameOptions>(
683 options,
684 )
685 })
686 .transpose()?;
687 let options = match options {
688 None => OneOf::Left(true),
689 Some(options) => OneOf::Right(options),
690 };
691
692 server.update_capabilities(|capabilities| {
693 capabilities.rename_provider = Some(options);
694 })
695 }
696 anyhow::Ok(())
697 })??;
698 }
699 _ => log::warn!("unhandled capability registration: {reg:?}"),
700 }
701 }
702 Ok(())
703 }
704 }
705 })
706 .detach();
707
708 language_server
709 .on_request::<lsp::request::UnregisterCapability, _, _>({
710 let this = this.clone();
711 move |params, cx| {
712 let this = this.clone();
713 let mut cx = cx.clone();
714 async move {
715 for unreg in params.unregisterations.iter() {
716 match unreg.method.as_str() {
717 "workspace/didChangeWatchedFiles" => {
718 this.update(&mut cx, |this, cx| {
719 this.as_local_mut()?
720 .on_lsp_unregister_did_change_watched_files(
721 server_id, &unreg.id, cx,
722 );
723 Some(())
724 })?;
725 }
726 "workspace/didChangeConfiguration" => {
727 // Ignore payload since we notify clients of setting changes unconditionally, relying on them pulling the latest settings.
728 }
729 "textDocument/rename" => {
730 this.update(&mut cx, |this, _| {
731 if let Some(server) = this.language_server_for_id(server_id)
732 {
733 server.update_capabilities(|capabilities| {
734 capabilities.rename_provider = None
735 })
736 }
737 })?;
738 }
739 "textDocument/rangeFormatting" => {
740 this.update(&mut cx, |this, _| {
741 if let Some(server) = this.language_server_for_id(server_id)
742 {
743 server.update_capabilities(|capabilities| {
744 capabilities.document_range_formatting_provider =
745 None
746 })
747 }
748 })?;
749 }
750 "textDocument/onTypeFormatting" => {
751 this.update(&mut cx, |this, _| {
752 if let Some(server) = this.language_server_for_id(server_id)
753 {
754 server.update_capabilities(|capabilities| {
755 capabilities.document_on_type_formatting_provider =
756 None;
757 })
758 }
759 })?;
760 }
761 "textDocument/formatting" => {
762 this.update(&mut cx, |this, _| {
763 if let Some(server) = this.language_server_for_id(server_id)
764 {
765 server.update_capabilities(|capabilities| {
766 capabilities.document_formatting_provider = None;
767 })
768 }
769 })?;
770 }
771 _ => log::warn!("unhandled capability unregistration: {unreg:?}"),
772 }
773 }
774 Ok(())
775 }
776 }
777 })
778 .detach();
779
780 language_server
781 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
782 let adapter = adapter.clone();
783 let this = this.clone();
784 move |params, cx| {
785 let mut cx = cx.clone();
786 let this = this.clone();
787 let adapter = adapter.clone();
788 async move {
789 LocalLspStore::on_lsp_workspace_edit(
790 this.clone(),
791 params,
792 server_id,
793 adapter.clone(),
794 &mut cx,
795 )
796 .await
797 }
798 }
799 })
800 .detach();
801
802 language_server
803 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
804 let this = this.clone();
805 move |(), cx| {
806 let this = this.clone();
807 let mut cx = cx.clone();
808 async move {
809 this.update(&mut cx, |this, cx| {
810 cx.emit(LspStoreEvent::RefreshInlayHints);
811 this.downstream_client.as_ref().map(|(client, project_id)| {
812 client.send(proto::RefreshInlayHints {
813 project_id: *project_id,
814 })
815 })
816 })?
817 .transpose()?;
818 Ok(())
819 }
820 }
821 })
822 .detach();
823
824 language_server
825 .on_request::<lsp::request::CodeLensRefresh, _, _>({
826 let this = this.clone();
827 move |(), cx| {
828 let this = this.clone();
829 let mut cx = cx.clone();
830 async move {
831 this.update(&mut cx, |this, cx| {
832 cx.emit(LspStoreEvent::RefreshCodeLens);
833 this.downstream_client.as_ref().map(|(client, project_id)| {
834 client.send(proto::RefreshCodeLens {
835 project_id: *project_id,
836 })
837 })
838 })?
839 .transpose()?;
840 Ok(())
841 }
842 }
843 })
844 .detach();
845
846 language_server
847 .on_request::<lsp::request::ShowMessageRequest, _, _>({
848 let this = this.clone();
849 let name = name.to_string();
850 move |params, cx| {
851 let this = this.clone();
852 let name = name.to_string();
853 let mut cx = cx.clone();
854 async move {
855 let actions = params.actions.unwrap_or_default();
856 let (tx, rx) = smol::channel::bounded(1);
857 let request = LanguageServerPromptRequest {
858 level: match params.typ {
859 lsp::MessageType::ERROR => PromptLevel::Critical,
860 lsp::MessageType::WARNING => PromptLevel::Warning,
861 _ => PromptLevel::Info,
862 },
863 message: params.message,
864 actions,
865 response_channel: tx,
866 lsp_name: name.clone(),
867 };
868
869 let did_update = this
870 .update(&mut cx, |_, cx| {
871 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
872 })
873 .is_ok();
874 if did_update {
875 let response = rx.recv().await.ok();
876 Ok(response)
877 } else {
878 Ok(None)
879 }
880 }
881 }
882 })
883 .detach();
884 language_server
885 .on_notification::<lsp::notification::ShowMessage, _>({
886 let this = this.clone();
887 let name = name.to_string();
888 move |params, cx| {
889 let this = this.clone();
890 let name = name.to_string();
891 let mut cx = cx.clone();
892
893 let (tx, _) = smol::channel::bounded(1);
894 let request = LanguageServerPromptRequest {
895 level: match params.typ {
896 lsp::MessageType::ERROR => PromptLevel::Critical,
897 lsp::MessageType::WARNING => PromptLevel::Warning,
898 _ => PromptLevel::Info,
899 },
900 message: params.message,
901 actions: vec![],
902 response_channel: tx,
903 lsp_name: name.clone(),
904 };
905
906 let _ = this.update(&mut cx, |_, cx| {
907 cx.emit(LspStoreEvent::LanguageServerPrompt(request));
908 });
909 }
910 })
911 .detach();
912
913 let disk_based_diagnostics_progress_token =
914 adapter.disk_based_diagnostics_progress_token.clone();
915
916 language_server
917 .on_notification::<lsp::notification::Progress, _>({
918 let this = this.clone();
919 move |params, cx| {
920 if let Some(this) = this.upgrade() {
921 this.update(cx, |this, cx| {
922 this.on_lsp_progress(
923 params,
924 server_id,
925 disk_based_diagnostics_progress_token.clone(),
926 cx,
927 );
928 })
929 .ok();
930 }
931 }
932 })
933 .detach();
934
935 language_server
936 .on_notification::<lsp::notification::LogMessage, _>({
937 let this = this.clone();
938 move |params, cx| {
939 if let Some(this) = this.upgrade() {
940 this.update(cx, |_, cx| {
941 cx.emit(LspStoreEvent::LanguageServerLog(
942 server_id,
943 LanguageServerLogType::Log(params.typ),
944 params.message,
945 ));
946 })
947 .ok();
948 }
949 }
950 })
951 .detach();
952
953 language_server
954 .on_notification::<lsp::notification::LogTrace, _>({
955 let this = this.clone();
956 move |params, cx| {
957 let mut cx = cx.clone();
958 if let Some(this) = this.upgrade() {
959 this.update(&mut cx, |_, cx| {
960 cx.emit(LspStoreEvent::LanguageServerLog(
961 server_id,
962 LanguageServerLogType::Trace(params.verbose),
963 params.message,
964 ));
965 })
966 .ok();
967 }
968 }
969 })
970 .detach();
971
972 rust_analyzer_ext::register_notifications(this.clone(), language_server);
973 clangd_ext::register_notifications(this, language_server, adapter);
974 }
975
976 fn shutdown_language_servers(
977 &mut self,
978 _cx: &mut Context<LspStore>,
979 ) -> impl Future<Output = ()> + use<> {
980 let shutdown_futures = self
981 .language_servers
982 .drain()
983 .map(|(_, server_state)| async {
984 use LanguageServerState::*;
985 match server_state {
986 Running { server, .. } => server.shutdown()?.await,
987 Starting { startup, .. } => startup.await?.shutdown()?.await,
988 }
989 })
990 .collect::<Vec<_>>();
991
992 async move {
993 futures::future::join_all(shutdown_futures).await;
994 }
995 }
996
997 fn language_servers_for_worktree(
998 &self,
999 worktree_id: WorktreeId,
1000 ) -> impl Iterator<Item = &Arc<LanguageServer>> {
1001 self.language_server_ids
1002 .iter()
1003 .flat_map(move |((language_server_path, _), ids)| {
1004 ids.iter().filter_map(move |id| {
1005 if *language_server_path != worktree_id {
1006 return None;
1007 }
1008 if let Some(LanguageServerState::Running { server, .. }) =
1009 self.language_servers.get(id)
1010 {
1011 return Some(server);
1012 } else {
1013 None
1014 }
1015 })
1016 })
1017 }
1018
1019 fn language_server_ids_for_project_path(
1020 &self,
1021 project_path: ProjectPath,
1022 language: &Language,
1023 cx: &mut App,
1024 ) -> Vec<LanguageServerId> {
1025 let Some(worktree) = self
1026 .worktree_store
1027 .read(cx)
1028 .worktree_for_id(project_path.worktree_id, cx)
1029 else {
1030 return vec![];
1031 };
1032 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
1033 let root = self.lsp_tree.update(cx, |this, cx| {
1034 this.get(
1035 project_path,
1036 AdapterQuery::Language(&language.name()),
1037 delegate,
1038 cx,
1039 )
1040 .filter_map(|node| node.server_id())
1041 .collect::<Vec<_>>()
1042 });
1043
1044 root
1045 }
1046
1047 fn language_server_ids_for_buffer(
1048 &self,
1049 buffer: &Buffer,
1050 cx: &mut App,
1051 ) -> Vec<LanguageServerId> {
1052 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
1053 let worktree_id = file.worktree_id(cx);
1054
1055 let path: Arc<Path> = file
1056 .path()
1057 .parent()
1058 .map(Arc::from)
1059 .unwrap_or_else(|| file.path().clone());
1060 let worktree_path = ProjectPath { worktree_id, path };
1061 self.language_server_ids_for_project_path(worktree_path, language, cx)
1062 } else {
1063 Vec::new()
1064 }
1065 }
1066
1067 fn language_servers_for_buffer<'a>(
1068 &'a self,
1069 buffer: &'a Buffer,
1070 cx: &'a mut App,
1071 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1072 self.language_server_ids_for_buffer(buffer, cx)
1073 .into_iter()
1074 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
1075 LanguageServerState::Running {
1076 adapter, server, ..
1077 } => Some((adapter, server)),
1078 _ => None,
1079 })
1080 }
1081
1082 fn primary_language_server_for_buffer<'a>(
1083 &'a self,
1084 buffer: &'a Buffer,
1085 cx: &'a mut App,
1086 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
1087 // The list of language servers is ordered based on the `language_servers` setting
1088 // for each language, thus we can consider the first one in the list to be the
1089 // primary one.
1090 self.language_servers_for_buffer(buffer, cx).next()
1091 }
1092
1093 async fn execute_code_action_kind_locally(
1094 lsp_store: WeakEntity<LspStore>,
1095 mut buffers: Vec<Entity<Buffer>>,
1096 kind: CodeActionKind,
1097 push_to_history: bool,
1098 cx: &mut AsyncApp,
1099 ) -> anyhow::Result<ProjectTransaction> {
1100 // Do not allow multiple concurrent code actions requests for the
1101 // same buffer.
1102 lsp_store.update(cx, |this, cx| {
1103 let this = this.as_local_mut().unwrap();
1104 buffers.retain(|buffer| {
1105 this.buffers_being_formatted
1106 .insert(buffer.read(cx).remote_id())
1107 });
1108 })?;
1109 let _cleanup = defer({
1110 let this = lsp_store.clone();
1111 let mut cx = cx.clone();
1112 let buffers = &buffers;
1113 move || {
1114 this.update(&mut cx, |this, cx| {
1115 let this = this.as_local_mut().unwrap();
1116 for buffer in buffers {
1117 this.buffers_being_formatted
1118 .remove(&buffer.read(cx).remote_id());
1119 }
1120 })
1121 .ok();
1122 }
1123 });
1124 let mut project_transaction = ProjectTransaction::default();
1125
1126 for buffer in &buffers {
1127 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1128 buffer.update(cx, |buffer, cx| {
1129 lsp_store
1130 .as_local()
1131 .unwrap()
1132 .language_servers_for_buffer(buffer, cx)
1133 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1134 .collect::<Vec<_>>()
1135 })
1136 })?;
1137 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
1138 let actions = Self::get_server_code_actions_from_action_kinds(
1139 &lsp_store,
1140 language_server.server_id(),
1141 vec![kind.clone()],
1142 buffer,
1143 cx,
1144 )
1145 .await?;
1146 Self::execute_code_actions_on_server(
1147 &lsp_store,
1148 language_server,
1149 lsp_adapter,
1150 actions,
1151 push_to_history,
1152 &mut project_transaction,
1153 cx,
1154 )
1155 .await?;
1156 }
1157 }
1158 Ok(project_transaction)
1159 }
1160
1161 async fn format_locally(
1162 lsp_store: WeakEntity<LspStore>,
1163 mut buffers: Vec<FormattableBuffer>,
1164 push_to_history: bool,
1165 trigger: FormatTrigger,
1166 logger: zlog::Logger,
1167 cx: &mut AsyncApp,
1168 ) -> anyhow::Result<ProjectTransaction> {
1169 // Do not allow multiple concurrent formatting requests for the
1170 // same buffer.
1171 lsp_store.update(cx, |this, cx| {
1172 let this = this.as_local_mut().unwrap();
1173 buffers.retain(|buffer| {
1174 this.buffers_being_formatted
1175 .insert(buffer.handle.read(cx).remote_id())
1176 });
1177 })?;
1178
1179 let _cleanup = defer({
1180 let this = lsp_store.clone();
1181 let mut cx = cx.clone();
1182 let buffers = &buffers;
1183 move || {
1184 this.update(&mut cx, |this, cx| {
1185 let this = this.as_local_mut().unwrap();
1186 for buffer in buffers {
1187 this.buffers_being_formatted
1188 .remove(&buffer.handle.read(cx).remote_id());
1189 }
1190 })
1191 .ok();
1192 }
1193 });
1194
1195 let mut project_transaction = ProjectTransaction::default();
1196
1197 for buffer in &buffers {
1198 let adapters_and_servers = lsp_store.update(cx, |lsp_store, cx| {
1199 buffer.handle.update(cx, |buffer, cx| {
1200 lsp_store
1201 .as_local()
1202 .unwrap()
1203 .language_servers_for_buffer(buffer, cx)
1204 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
1205 .collect::<Vec<_>>()
1206 })
1207 })?;
1208
1209 let settings = buffer.handle.read_with(cx, |buffer, cx| {
1210 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
1211 .into_owned()
1212 })?;
1213
1214 let mut transaction_id_format = None;
1215
1216 // ensure no transactions created while formatting are
1217 // grouped with the previous transaction in the history
1218 // based on the transaction group interval
1219 buffer.handle.update(cx, |buffer, _| {
1220 buffer.finalize_last_transaction();
1221 })?;
1222
1223 // handle whitespace formatting
1224 {
1225 if settings.remove_trailing_whitespace_on_save {
1226 zlog::trace!(logger => "removing trailing whitespace");
1227 let diff = buffer
1228 .handle
1229 .read_with(cx, |buffer, cx| buffer.remove_trailing_whitespace(cx))?
1230 .await;
1231 buffer.handle.update(cx, |buffer, cx| {
1232 buffer.start_transaction();
1233 buffer.apply_diff(diff, cx);
1234 transaction_id_format =
1235 transaction_id_format.or(buffer.end_transaction(cx));
1236 if let Some(transaction_id) = transaction_id_format {
1237 buffer.group_until_transaction(transaction_id);
1238 }
1239 })?;
1240 }
1241
1242 if settings.ensure_final_newline_on_save {
1243 zlog::trace!(logger => "ensuring final newline");
1244 buffer.handle.update(cx, |buffer, cx| {
1245 buffer.start_transaction();
1246 buffer.ensure_final_newline(cx);
1247 transaction_id_format =
1248 transaction_id_format.or(buffer.end_transaction(cx));
1249 if let Some(transaction_id) = transaction_id_format {
1250 buffer.group_until_transaction(transaction_id);
1251 }
1252 })?;
1253 }
1254 }
1255
1256 // Formatter for `code_actions_on_format` that runs before
1257 // the rest of the formatters
1258 let code_actions_on_format_formatter = 'ca_formatter: {
1259 let should_run_code_actions_on_format = !matches!(
1260 (trigger, &settings.format_on_save),
1261 (FormatTrigger::Save, &FormatOnSave::Off)
1262 );
1263 let have_code_actions_to_run_on_format = settings
1264 .code_actions_on_format
1265 .values()
1266 .any(|enabled| *enabled);
1267
1268 if should_run_code_actions_on_format {
1269 if have_code_actions_to_run_on_format {
1270 zlog::trace!(logger => "going to run code actions on format");
1271 break 'ca_formatter Some(Formatter::CodeActions(
1272 settings.code_actions_on_format.clone(),
1273 ));
1274 }
1275 }
1276 break 'ca_formatter None;
1277 };
1278
1279 let formatters = match (trigger, &settings.format_on_save) {
1280 (FormatTrigger::Save, FormatOnSave::Off) => &[],
1281 (FormatTrigger::Save, FormatOnSave::List(formatters)) => formatters.as_ref(),
1282 (FormatTrigger::Manual, _) | (FormatTrigger::Save, FormatOnSave::On) => {
1283 match &settings.formatter {
1284 SelectedFormatter::Auto => {
1285 if settings.prettier.allowed {
1286 zlog::trace!(logger => "Formatter set to auto: defaulting to prettier");
1287 std::slice::from_ref(&Formatter::Prettier)
1288 } else {
1289 zlog::trace!(logger => "Formatter set to auto: defaulting to primary language server");
1290 std::slice::from_ref(&Formatter::LanguageServer { name: None })
1291 }
1292 }
1293 SelectedFormatter::List(formatter_list) => formatter_list.as_ref(),
1294 }
1295 }
1296 };
1297
1298 let formatters = code_actions_on_format_formatter.iter().chain(formatters);
1299
1300 // helper function to avoid duplicate logic between formatter handlers below
1301 // We want to avoid continuing to format the buffer if it has been edited since the start
1302 // so we check that the last transaction id on the undo stack matches the one we expect
1303 // This check should be done after each "gather" step where we generate a diff or edits to apply,
1304 // and before applying them to the buffer to avoid messing up the user's buffer
1305 fn err_if_buffer_edited_since_start(
1306 buffer: &FormattableBuffer,
1307 transaction_id_format: Option<text::TransactionId>,
1308 cx: &AsyncApp,
1309 ) -> Option<anyhow::Error> {
1310 let transaction_id_last = buffer
1311 .handle
1312 .read_with(cx, |buffer, _| {
1313 buffer.peek_undo_stack().map(|t| t.transaction_id())
1314 })
1315 .ok()
1316 .flatten();
1317 let should_continue_formatting = match (transaction_id_format, transaction_id_last)
1318 {
1319 (Some(format), Some(last)) => format == last,
1320 (Some(_), None) => false,
1321 (_, _) => true,
1322 };
1323 if !should_continue_formatting {
1324 return Some(anyhow::anyhow!("Buffer edited while formatting. Aborting"));
1325 }
1326 return None;
1327 }
1328
1329 // variable used to track errors that occur during the formatting process below,
1330 // but that need to not be returned right away (with `?` for example) because we
1331 // still need to clean up the transaction history and update the project transaction
1332 let mut result = anyhow::Ok(());
1333
1334 'formatters: for formatter in formatters {
1335 match formatter {
1336 Formatter::Prettier => {
1337 let logger = zlog::scoped!(logger => "prettier");
1338 zlog::trace!(logger => "formatting");
1339 let _timer = zlog::time!(logger => "Formatting buffer via prettier");
1340
1341 let prettier = lsp_store.read_with(cx, |lsp_store, _cx| {
1342 lsp_store.prettier_store().unwrap().downgrade()
1343 })?;
1344 let diff_result =
1345 prettier_store::format_with_prettier(&prettier, &buffer.handle, cx)
1346 .await
1347 .transpose();
1348 let Ok(diff) = diff_result else {
1349 result = Err(diff_result.unwrap_err());
1350 zlog::error!(logger => "failed, reason: {:?}", result.as_ref());
1351 break 'formatters;
1352 };
1353 let Some(diff) = diff else {
1354 zlog::trace!(logger => "No changes");
1355 continue 'formatters;
1356 };
1357 if let Some(err) =
1358 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1359 {
1360 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1361 result = Err(err);
1362 break 'formatters;
1363 }
1364 zlog::trace!(logger => "Applying changes");
1365 buffer.handle.update(cx, |buffer, cx| {
1366 buffer.start_transaction();
1367 buffer.apply_diff(diff, cx);
1368 transaction_id_format =
1369 transaction_id_format.or(buffer.end_transaction(cx));
1370 if let Some(transaction_id) = transaction_id_format {
1371 buffer.group_until_transaction(transaction_id);
1372 }
1373 })?;
1374 }
1375 Formatter::External { command, arguments } => {
1376 let logger = zlog::scoped!(logger => "command");
1377 zlog::trace!(logger => "formatting");
1378 let _timer =
1379 zlog::time!(logger => "Formatting buffer via external command");
1380
1381 let diff_result = Self::format_via_external_command(
1382 buffer,
1383 command.as_ref(),
1384 arguments.as_deref(),
1385 cx,
1386 )
1387 .await
1388 .with_context(|| {
1389 format!("Failed to format buffer via external command: {}", command)
1390 });
1391 let Ok(diff) = diff_result else {
1392 result = Err(diff_result.unwrap_err());
1393 zlog::error!(logger => "failed, reason: {:?}", result.as_ref());
1394 break 'formatters;
1395 };
1396 let Some(diff) = diff else {
1397 zlog::trace!(logger => "No changes");
1398 continue 'formatters;
1399 };
1400 if let Some(err) =
1401 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1402 {
1403 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1404 result = Err(err);
1405 break 'formatters;
1406 }
1407 zlog::trace!(logger => "Applying changes");
1408 buffer.handle.update(cx, |buffer, cx| {
1409 buffer.start_transaction();
1410 buffer.apply_diff(diff, cx);
1411 transaction_id_format =
1412 transaction_id_format.or(buffer.end_transaction(cx));
1413 if let Some(transaction_id) = transaction_id_format {
1414 buffer.group_until_transaction(transaction_id);
1415 }
1416 })?;
1417 }
1418 Formatter::LanguageServer { name } => {
1419 let logger = zlog::scoped!(logger => "language-server");
1420 zlog::trace!(logger => "formatting");
1421 let _timer =
1422 zlog::time!(logger => "Formatting buffer using language server");
1423
1424 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1425 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using language servers. Skipping");
1426 continue 'formatters;
1427 };
1428
1429 let language_server = 'language_server: {
1430 // if a name was provided, try to find the server with that name
1431 if let Some(name) = name.as_deref() {
1432 for (adapter, server) in &adapters_and_servers {
1433 if adapter.name.0.as_ref() == name {
1434 break 'language_server server.clone();
1435 }
1436 }
1437 }
1438
1439 // otherwise, fall back to the primary language server for the buffer if one exists
1440 let default_lsp = lsp_store.update(cx, |lsp_store, cx| {
1441 buffer.handle.update(cx, |buffer, cx| {
1442 lsp_store
1443 .as_local()
1444 .unwrap()
1445 .primary_language_server_for_buffer(buffer, cx)
1446 .map(|(_, lsp)| lsp.clone())
1447 })
1448 })?;
1449
1450 if let Some(default_lsp) = default_lsp {
1451 break 'language_server default_lsp;
1452 } else {
1453 log::warn!(
1454 "No language server found to format buffer '{:?}'. Skipping",
1455 buffer_path_abs.as_path().to_string_lossy()
1456 );
1457 continue 'formatters;
1458 }
1459 };
1460
1461 zlog::trace!(
1462 logger =>
1463 "Formatting buffer '{:?}' using language server '{:?}'",
1464 buffer_path_abs.as_path().to_string_lossy(),
1465 language_server.name()
1466 );
1467
1468 let edits_result = if let Some(ranges) = buffer.ranges.as_ref() {
1469 zlog::trace!(logger => "formatting ranges");
1470 Self::format_ranges_via_lsp(
1471 &lsp_store,
1472 &buffer.handle,
1473 ranges,
1474 buffer_path_abs,
1475 &language_server,
1476 &settings,
1477 cx,
1478 )
1479 .await
1480 .context("Failed to format ranges via language server")
1481 } else {
1482 zlog::trace!(logger => "formatting full");
1483 Self::format_via_lsp(
1484 &lsp_store,
1485 &buffer.handle,
1486 buffer_path_abs,
1487 &language_server,
1488 &settings,
1489 cx,
1490 )
1491 .await
1492 .context("failed to format via language server")
1493 };
1494
1495 let Ok(edits) = edits_result else {
1496 result = Err(edits_result.unwrap_err());
1497 zlog::error!(logger => "Failed, reason: {:?}", result.as_ref());
1498 break 'formatters;
1499 };
1500
1501 if edits.is_empty() {
1502 zlog::trace!(logger => "No changes");
1503 continue 'formatters;
1504 }
1505 if let Some(err) =
1506 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1507 {
1508 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1509 result = Err(err);
1510 break 'formatters;
1511 }
1512 zlog::trace!(logger => "Applying changes");
1513 buffer.handle.update(cx, |buffer, cx| {
1514 buffer.start_transaction();
1515 buffer.edit(edits, None, cx);
1516 transaction_id_format =
1517 transaction_id_format.or(buffer.end_transaction(cx));
1518 if let Some(transaction_id) = transaction_id_format {
1519 buffer.group_until_transaction(transaction_id);
1520 }
1521 })?;
1522 }
1523 Formatter::CodeActions(code_actions) => {
1524 let logger = zlog::scoped!(logger => "code-actions");
1525 zlog::trace!(logger => "formatting");
1526 let _timer = zlog::time!(logger => "Formatting buffer using code actions");
1527
1528 let Some(buffer_path_abs) = buffer.abs_path.as_ref() else {
1529 zlog::warn!(logger => "Cannot format buffer that is not backed by a file on disk using code actions. Skipping");
1530 continue 'formatters;
1531 };
1532 let code_action_kinds = code_actions
1533 .iter()
1534 .filter_map(|(action_kind, enabled)| {
1535 enabled.then_some(action_kind.clone().into())
1536 })
1537 .collect::<Vec<_>>();
1538 if code_action_kinds.is_empty() {
1539 zlog::trace!(logger => "No code action kinds enabled, skipping");
1540 continue 'formatters;
1541 }
1542
1543 let mut actions_and_servers = Vec::new();
1544
1545 for (index, (_, language_server)) in adapters_and_servers.iter().enumerate()
1546 {
1547 let actions_result = Self::get_server_code_actions_from_action_kinds(
1548 &lsp_store,
1549 language_server.server_id(),
1550 code_action_kinds.clone(),
1551 &buffer.handle,
1552 cx,
1553 )
1554 .await
1555 .with_context(
1556 || format!("Failed to resolve code actions with kinds {:?} for language server {}",
1557 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1558 language_server.name())
1559 );
1560 let Ok(actions) = actions_result else {
1561 // note: it may be better to set result to the error and break formatters here
1562 // but for now we try to execute the actions that we can resolve and skip the rest
1563 zlog::error!(
1564 logger =>
1565 "Failed to resolve code actions with kinds {:?} with language server {}",
1566 code_action_kinds.iter().map(|kind| kind.as_str()).join(", "),
1567 language_server.name()
1568 );
1569 continue;
1570 };
1571 for action in actions {
1572 actions_and_servers.push((action, index));
1573 }
1574 }
1575
1576 if actions_and_servers.is_empty() {
1577 zlog::trace!(logger => "No code actions were resolved, continuing");
1578 continue 'formatters;
1579 }
1580
1581 'actions: for (mut action, server_index) in actions_and_servers {
1582 let server = &adapters_and_servers[server_index].1;
1583
1584 let describe_code_action = |action: &CodeAction| {
1585 format!(
1586 "code action '{}' with title \"{}\"",
1587 action
1588 .lsp_action
1589 .action_kind()
1590 .unwrap_or("unknown".into())
1591 .as_str(),
1592 action.lsp_action.title()
1593 )
1594 };
1595
1596 zlog::trace!(logger => "Executing {}", describe_code_action(&action));
1597
1598 // NOTE: code below duplicated from `Self::deserialize_workspace_edit`
1599 // but filters out and logs warnings for code actions that cause unreasonably
1600 // difficult handling on our part, such as:
1601 // - applying edits that call commands
1602 // which can result in arbitrary workspace edits being sent from the server that
1603 // have no way of being tied back to the command that initiated them (i.e. we
1604 // can't know which edits are part of the format request, or if the server is done sending
1605 // actions in response to the command)
1606 // - actions that create/delete/modify/rename files other than the one we are formatting
1607 // as we then would need to handle such changes correctly in the local history as well
1608 // as the remote history through the ProjectTransaction
1609 // - actions with snippet edits, as these simply don't make sense in the context of a format request
1610 // Supporting these actions is not impossible, but not supported as of yet.
1611
1612 if let Err(err) =
1613 Self::try_resolve_code_action(server, &mut action).await
1614 {
1615 zlog::error!(
1616 logger =>
1617 "Failed to resolve {}. Error: {}",
1618 describe_code_action(&action),
1619 err
1620 );
1621 continue 'actions;
1622 }
1623 if let Some(_) = action.lsp_action.command() {
1624 zlog::warn!(
1625 logger =>
1626 "Code actions with commands are not supported while formatting. Skipping {}",
1627 describe_code_action(&action),
1628 );
1629 continue 'actions;
1630 }
1631 let Some(edit) = action.lsp_action.edit().cloned() else {
1632 zlog::warn!(
1633 logger =>
1634 "No edit found for while formatting. Skipping {}",
1635 describe_code_action(&action),
1636 );
1637 continue 'actions;
1638 };
1639
1640 if edit.changes.is_none() && edit.document_changes.is_none() {
1641 zlog::trace!(
1642 logger =>
1643 "No changes for code action. Skipping {}",
1644 describe_code_action(&action),
1645 );
1646 continue 'actions;
1647 }
1648
1649 let mut operations = Vec::new();
1650 if let Some(document_changes) = edit.document_changes {
1651 match document_changes {
1652 lsp::DocumentChanges::Edits(edits) => operations.extend(
1653 edits.into_iter().map(lsp::DocumentChangeOperation::Edit),
1654 ),
1655 lsp::DocumentChanges::Operations(ops) => operations = ops,
1656 }
1657 } else if let Some(changes) = edit.changes {
1658 operations.extend(changes.into_iter().map(|(uri, edits)| {
1659 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1660 text_document:
1661 lsp::OptionalVersionedTextDocumentIdentifier {
1662 uri,
1663 version: None,
1664 },
1665 edits: edits.into_iter().map(Edit::Plain).collect(),
1666 })
1667 }));
1668 }
1669
1670 let mut edits = Vec::with_capacity(operations.len());
1671
1672 if operations.is_empty() {
1673 zlog::trace!(
1674 logger =>
1675 "No changes for code action. Skipping {}",
1676 describe_code_action(&action),
1677 );
1678 continue 'actions;
1679 }
1680 for operation in operations {
1681 let op = match operation {
1682 lsp::DocumentChangeOperation::Edit(op) => op,
1683 lsp::DocumentChangeOperation::Op(_) => {
1684 zlog::warn!(
1685 logger =>
1686 "Code actions which create, delete, or rename files are not supported on format. Skipping {}",
1687 describe_code_action(&action),
1688 );
1689 continue 'actions;
1690 }
1691 };
1692 let Ok(file_path) = op.text_document.uri.to_file_path() else {
1693 zlog::warn!(
1694 logger =>
1695 "Failed to convert URI '{:?}' to file path. Skipping {}",
1696 &op.text_document.uri,
1697 describe_code_action(&action),
1698 );
1699 continue 'actions;
1700 };
1701 if &file_path != buffer_path_abs {
1702 zlog::warn!(
1703 logger =>
1704 "File path '{:?}' does not match buffer path '{:?}'. Skipping {}",
1705 file_path,
1706 buffer_path_abs,
1707 describe_code_action(&action),
1708 );
1709 continue 'actions;
1710 }
1711
1712 let mut lsp_edits = Vec::new();
1713 for edit in op.edits {
1714 match edit {
1715 Edit::Plain(edit) => {
1716 if !lsp_edits.contains(&edit) {
1717 lsp_edits.push(edit);
1718 }
1719 }
1720 Edit::Annotated(edit) => {
1721 if !lsp_edits.contains(&edit.text_edit) {
1722 lsp_edits.push(edit.text_edit);
1723 }
1724 }
1725 Edit::Snippet(_) => {
1726 zlog::warn!(
1727 logger =>
1728 "Code actions which produce snippet edits are not supported during formatting. Skipping {}",
1729 describe_code_action(&action),
1730 );
1731 continue 'actions;
1732 }
1733 }
1734 }
1735 let edits_result = lsp_store
1736 .update(cx, |lsp_store, cx| {
1737 lsp_store.as_local_mut().unwrap().edits_from_lsp(
1738 &buffer.handle,
1739 lsp_edits,
1740 server.server_id(),
1741 op.text_document.version,
1742 cx,
1743 )
1744 })?
1745 .await;
1746 let Ok(resolved_edits) = edits_result else {
1747 zlog::warn!(
1748 logger =>
1749 "Failed to resolve edits from LSP for buffer {:?} while handling {}",
1750 buffer_path_abs.as_path(),
1751 describe_code_action(&action),
1752 );
1753 continue 'actions;
1754 };
1755 edits.extend(resolved_edits);
1756 }
1757
1758 if edits.is_empty() {
1759 zlog::warn!(logger => "No edits resolved from LSP");
1760 continue 'actions;
1761 }
1762
1763 if let Some(err) =
1764 err_if_buffer_edited_since_start(buffer, transaction_id_format, &cx)
1765 {
1766 zlog::warn!(logger => "Buffer edited while formatting. Aborting");
1767 result = Err(err);
1768 break 'formatters;
1769 }
1770 zlog::info!(logger => "Applying changes");
1771 buffer.handle.update(cx, |buffer, cx| {
1772 buffer.start_transaction();
1773 buffer.edit(edits, None, cx);
1774 transaction_id_format =
1775 transaction_id_format.or(buffer.end_transaction(cx));
1776 if let Some(transaction_id) = transaction_id_format {
1777 buffer.group_until_transaction(transaction_id);
1778 }
1779 })?;
1780 }
1781 }
1782 }
1783 }
1784
1785 let buffer_handle = buffer.handle.clone();
1786 buffer.handle.update(cx, |buffer, _| {
1787 let Some(transaction_id) = transaction_id_format else {
1788 zlog::trace!(logger => "No formatting transaction id");
1789 return result;
1790 };
1791 let Some(transaction_id_last) =
1792 buffer.peek_undo_stack().map(|t| t.transaction_id())
1793 else {
1794 // unwrapping should work here, how would we get a transaction id
1795 // with no transaction on the undo stack?
1796 // *but* it occasionally panics. Avoiding panics for now...
1797 zlog::warn!(logger => "No transaction present on undo stack, despite having a formatting transaction id?");
1798 return result;
1799 };
1800 if transaction_id_last != transaction_id {
1801 zlog::trace!(logger => "Last transaction on undo stack is not the formatting transaction, skipping finalization & update of project transaction");
1802 return result;
1803 }
1804 let transaction = buffer
1805 .finalize_last_transaction()
1806 .cloned()
1807 .expect("There is a transaction on the undo stack if we were able to peek it");
1808 // debug_assert_eq!(transaction.id, transaction_id);
1809 if !push_to_history {
1810 zlog::trace!(logger => "forgetting format transaction");
1811 buffer.forget_transaction(transaction.id);
1812 }
1813 project_transaction
1814 .0
1815 .insert(buffer_handle.clone(), transaction);
1816 return result;
1817 })??;
1818 }
1819
1820 return Ok(project_transaction);
1821 }
1822
1823 pub async fn format_ranges_via_lsp(
1824 this: &WeakEntity<LspStore>,
1825 buffer_handle: &Entity<Buffer>,
1826 ranges: &[Range<Anchor>],
1827 abs_path: &Path,
1828 language_server: &Arc<LanguageServer>,
1829 settings: &LanguageSettings,
1830 cx: &mut AsyncApp,
1831 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1832 let capabilities = &language_server.capabilities();
1833 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1834 if range_formatting_provider.map_or(false, |provider| provider == &OneOf::Left(false)) {
1835 return Err(anyhow!(
1836 "{} language server does not support range formatting",
1837 language_server.name()
1838 ));
1839 }
1840
1841 let uri = lsp::Url::from_file_path(abs_path)
1842 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
1843 let text_document = lsp::TextDocumentIdentifier::new(uri);
1844
1845 let lsp_edits = {
1846 let mut lsp_ranges = Vec::new();
1847 this.update(cx, |_this, cx| {
1848 // TODO(#22930): In the case of formatting multibuffer selections, this buffer may
1849 // not have been sent to the language server. This seems like a fairly systemic
1850 // issue, though, the resolution probably is not specific to formatting.
1851 //
1852 // TODO: Instead of using current snapshot, should use the latest snapshot sent to
1853 // LSP.
1854 let snapshot = buffer_handle.read(cx).snapshot();
1855 for range in ranges {
1856 lsp_ranges.push(range_to_lsp(range.to_point_utf16(&snapshot))?);
1857 }
1858 anyhow::Ok(())
1859 })??;
1860
1861 let mut edits = None;
1862 for range in lsp_ranges {
1863 if let Some(mut edit) = language_server
1864 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1865 text_document: text_document.clone(),
1866 range,
1867 options: lsp_command::lsp_formatting_options(settings),
1868 work_done_progress_params: Default::default(),
1869 })
1870 .await?
1871 {
1872 edits.get_or_insert_with(Vec::new).append(&mut edit);
1873 }
1874 }
1875 edits
1876 };
1877
1878 if let Some(lsp_edits) = lsp_edits {
1879 this.update(cx, |this, cx| {
1880 this.as_local_mut().unwrap().edits_from_lsp(
1881 &buffer_handle,
1882 lsp_edits,
1883 language_server.server_id(),
1884 None,
1885 cx,
1886 )
1887 })?
1888 .await
1889 } else {
1890 Ok(Vec::with_capacity(0))
1891 }
1892 }
1893
1894 async fn format_via_lsp(
1895 this: &WeakEntity<LspStore>,
1896 buffer: &Entity<Buffer>,
1897 abs_path: &Path,
1898 language_server: &Arc<LanguageServer>,
1899 settings: &LanguageSettings,
1900 cx: &mut AsyncApp,
1901 ) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
1902 let logger = zlog::scoped!("lsp_format");
1903 zlog::info!(logger => "Formatting via LSP");
1904
1905 let uri = lsp::Url::from_file_path(abs_path)
1906 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
1907 let text_document = lsp::TextDocumentIdentifier::new(uri);
1908 let capabilities = &language_server.capabilities();
1909
1910 let formatting_provider = capabilities.document_formatting_provider.as_ref();
1911 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
1912
1913 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
1914 let _timer = zlog::time!(logger => "format-full")
1915 .warn_if_gt(std::time::Duration::from_millis(0));
1916 language_server
1917 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
1918 text_document,
1919 options: lsp_command::lsp_formatting_options(settings),
1920 work_done_progress_params: Default::default(),
1921 })
1922 .await?
1923 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
1924 let _timer = zlog::time!(logger => "format-range")
1925 .warn_if_gt(std::time::Duration::from_millis(0));
1926 let buffer_start = lsp::Position::new(0, 0);
1927 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
1928 language_server
1929 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
1930 text_document: text_document.clone(),
1931 range: lsp::Range::new(buffer_start, buffer_end),
1932 options: lsp_command::lsp_formatting_options(settings),
1933 work_done_progress_params: Default::default(),
1934 })
1935 .await?
1936 } else {
1937 None
1938 };
1939
1940 if let Some(lsp_edits) = lsp_edits {
1941 this.update(cx, |this, cx| {
1942 this.as_local_mut().unwrap().edits_from_lsp(
1943 buffer,
1944 lsp_edits,
1945 language_server.server_id(),
1946 None,
1947 cx,
1948 )
1949 })?
1950 .await
1951 } else {
1952 Ok(Vec::with_capacity(0))
1953 }
1954 }
1955
1956 async fn format_via_external_command(
1957 buffer: &FormattableBuffer,
1958 command: &str,
1959 arguments: Option<&[String]>,
1960 cx: &mut AsyncApp,
1961 ) -> Result<Option<Diff>> {
1962 let working_dir_path = buffer.handle.update(cx, |buffer, cx| {
1963 let file = File::from_dyn(buffer.file())?;
1964 let worktree = file.worktree.read(cx);
1965 let mut worktree_path = worktree.abs_path().to_path_buf();
1966 if worktree.root_entry()?.is_file() {
1967 worktree_path.pop();
1968 }
1969 Some(worktree_path)
1970 })?;
1971
1972 let mut child = util::command::new_smol_command(command);
1973
1974 if let Some(buffer_env) = buffer.env.as_ref() {
1975 child.envs(buffer_env);
1976 }
1977
1978 if let Some(working_dir_path) = working_dir_path {
1979 child.current_dir(working_dir_path);
1980 }
1981
1982 if let Some(arguments) = arguments {
1983 child.args(arguments.iter().map(|arg| {
1984 if let Some(buffer_abs_path) = buffer.abs_path.as_ref() {
1985 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
1986 } else {
1987 arg.replace("{buffer_path}", "Untitled")
1988 }
1989 }));
1990 }
1991
1992 let mut child = child
1993 .stdin(smol::process::Stdio::piped())
1994 .stdout(smol::process::Stdio::piped())
1995 .stderr(smol::process::Stdio::piped())
1996 .spawn()?;
1997
1998 let stdin = child
1999 .stdin
2000 .as_mut()
2001 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
2002 let text = buffer
2003 .handle
2004 .update(cx, |buffer, _| buffer.as_rope().clone())?;
2005 for chunk in text.chunks() {
2006 stdin.write_all(chunk.as_bytes()).await?;
2007 }
2008 stdin.flush().await?;
2009
2010 let output = child.output().await?;
2011 if !output.status.success() {
2012 return Err(anyhow!(
2013 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
2014 output.status.code(),
2015 String::from_utf8_lossy(&output.stdout),
2016 String::from_utf8_lossy(&output.stderr),
2017 ));
2018 }
2019
2020 let stdout = String::from_utf8(output.stdout)?;
2021 Ok(Some(
2022 buffer
2023 .handle
2024 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
2025 .await,
2026 ))
2027 }
2028
2029 async fn try_resolve_code_action(
2030 lang_server: &LanguageServer,
2031 action: &mut CodeAction,
2032 ) -> anyhow::Result<()> {
2033 match &mut action.lsp_action {
2034 LspAction::Action(lsp_action) => {
2035 if !action.resolved
2036 && GetCodeActions::can_resolve_actions(&lang_server.capabilities())
2037 && lsp_action.data.is_some()
2038 && (lsp_action.command.is_none() || lsp_action.edit.is_none())
2039 {
2040 *lsp_action = Box::new(
2041 lang_server
2042 .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
2043 .await?,
2044 );
2045 }
2046 }
2047 LspAction::CodeLens(lens) => {
2048 if !action.resolved && GetCodeLens::can_resolve_lens(&lang_server.capabilities()) {
2049 *lens = lang_server
2050 .request::<lsp::request::CodeLensResolve>(lens.clone())
2051 .await?;
2052 }
2053 }
2054 LspAction::Command(_) => {}
2055 }
2056
2057 action.resolved = true;
2058 anyhow::Ok(())
2059 }
2060
2061 fn initialize_buffer(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<LspStore>) {
2062 let buffer = buffer_handle.read(cx);
2063
2064 let file = buffer.file().cloned();
2065 let Some(file) = File::from_dyn(file.as_ref()) else {
2066 return;
2067 };
2068 if !file.is_local() {
2069 return;
2070 }
2071
2072 let worktree_id = file.worktree_id(cx);
2073 let language = buffer.language().cloned();
2074
2075 if let Some(diagnostics) = self.diagnostics.get(&worktree_id) {
2076 for (server_id, diagnostics) in
2077 diagnostics.get(file.path()).cloned().unwrap_or_default()
2078 {
2079 self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2080 .log_err();
2081 }
2082 }
2083 let Some(language) = language else {
2084 return;
2085 };
2086 for adapter in self.languages.lsp_adapters(&language.name()) {
2087 let servers = self
2088 .language_server_ids
2089 .get(&(worktree_id, adapter.name.clone()));
2090 if let Some(server_ids) = servers {
2091 for server_id in server_ids {
2092 let server = self
2093 .language_servers
2094 .get(server_id)
2095 .and_then(|server_state| {
2096 if let LanguageServerState::Running { server, .. } = server_state {
2097 Some(server.clone())
2098 } else {
2099 None
2100 }
2101 });
2102 let server = match server {
2103 Some(server) => server,
2104 None => continue,
2105 };
2106
2107 buffer_handle.update(cx, |buffer, cx| {
2108 buffer.set_completion_triggers(
2109 server.server_id(),
2110 server
2111 .capabilities()
2112 .completion_provider
2113 .as_ref()
2114 .and_then(|provider| {
2115 provider
2116 .trigger_characters
2117 .as_ref()
2118 .map(|characters| characters.iter().cloned().collect())
2119 })
2120 .unwrap_or_default(),
2121 cx,
2122 );
2123 });
2124 }
2125 }
2126 }
2127 }
2128
2129 pub(crate) fn reset_buffer(&mut self, buffer: &Entity<Buffer>, old_file: &File, cx: &mut App) {
2130 buffer.update(cx, |buffer, cx| {
2131 let Some(language) = buffer.language() else {
2132 return;
2133 };
2134 let path = ProjectPath {
2135 worktree_id: old_file.worktree_id(cx),
2136 path: old_file.path.clone(),
2137 };
2138 for server_id in self.language_server_ids_for_project_path(path, language, cx) {
2139 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
2140 buffer.set_completion_triggers(server_id, Default::default(), cx);
2141 }
2142 });
2143 }
2144
2145 fn update_buffer_diagnostics(
2146 &mut self,
2147 buffer: &Entity<Buffer>,
2148 server_id: LanguageServerId,
2149 version: Option<i32>,
2150 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2151 cx: &mut Context<LspStore>,
2152 ) -> Result<()> {
2153 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2154 Ordering::Equal
2155 .then_with(|| b.is_primary.cmp(&a.is_primary))
2156 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2157 .then_with(|| a.severity.cmp(&b.severity))
2158 .then_with(|| a.message.cmp(&b.message))
2159 }
2160
2161 diagnostics.sort_unstable_by(|a, b| {
2162 Ordering::Equal
2163 .then_with(|| a.range.start.cmp(&b.range.start))
2164 .then_with(|| b.range.end.cmp(&a.range.end))
2165 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2166 });
2167
2168 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
2169
2170 let edits_since_save = std::cell::LazyCell::new(|| {
2171 let saved_version = buffer.read(cx).saved_version();
2172 Patch::new(snapshot.edits_since::<PointUtf16>(saved_version).collect())
2173 });
2174
2175 let mut sanitized_diagnostics = Vec::with_capacity(diagnostics.len());
2176
2177 for entry in diagnostics {
2178 let start;
2179 let end;
2180 if entry.diagnostic.is_disk_based {
2181 // Some diagnostics are based on files on disk instead of buffers'
2182 // current contents. Adjust these diagnostics' ranges to reflect
2183 // any unsaved edits.
2184 start = Unclipped((*edits_since_save).old_to_new(entry.range.start.0));
2185 end = Unclipped((*edits_since_save).old_to_new(entry.range.end.0));
2186 } else {
2187 start = entry.range.start;
2188 end = entry.range.end;
2189 }
2190
2191 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2192 ..snapshot.clip_point_utf16(end, Bias::Right);
2193
2194 // Expand empty ranges by one codepoint
2195 if range.start == range.end {
2196 // This will be go to the next boundary when being clipped
2197 range.end.column += 1;
2198 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2199 if range.start == range.end && range.end.column > 0 {
2200 range.start.column -= 1;
2201 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
2202 }
2203 }
2204
2205 sanitized_diagnostics.push(DiagnosticEntry {
2206 range,
2207 diagnostic: entry.diagnostic,
2208 });
2209 }
2210 drop(edits_since_save);
2211
2212 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2213 buffer.update(cx, |buffer, cx| {
2214 buffer.update_diagnostics(server_id, set, cx)
2215 });
2216 Ok(())
2217 }
2218
2219 fn register_buffer_with_language_servers(
2220 &mut self,
2221 buffer_handle: &Entity<Buffer>,
2222 cx: &mut Context<LspStore>,
2223 ) {
2224 let buffer = buffer_handle.read(cx);
2225 let buffer_id = buffer.remote_id();
2226
2227 let Some(file) = File::from_dyn(buffer.file()) else {
2228 return;
2229 };
2230 if !file.is_local() {
2231 return;
2232 }
2233
2234 let abs_path = file.abs_path(cx);
2235 let Some(uri) = lsp::Url::from_file_path(&abs_path).log_err() else {
2236 return;
2237 };
2238 let initial_snapshot = buffer.text_snapshot();
2239 let worktree_id = file.worktree_id(cx);
2240
2241 let Some(language) = buffer.language().cloned() else {
2242 return;
2243 };
2244 let path: Arc<Path> = file
2245 .path()
2246 .parent()
2247 .map(Arc::from)
2248 .unwrap_or_else(|| file.path().clone());
2249 let Some(worktree) = self
2250 .worktree_store
2251 .read(cx)
2252 .worktree_for_id(worktree_id, cx)
2253 else {
2254 return;
2255 };
2256 let delegate = LocalLspAdapterDelegate::from_local_lsp(self, &worktree, cx);
2257 let servers = self.lsp_tree.clone().update(cx, |this, cx| {
2258 this.get(
2259 ProjectPath { worktree_id, path },
2260 AdapterQuery::Language(&language.name()),
2261 delegate.clone(),
2262 cx,
2263 )
2264 .collect::<Vec<_>>()
2265 });
2266 let servers = servers
2267 .into_iter()
2268 .filter_map(|server_node| {
2269 let server_id = server_node.server_id_or_init(
2270 |LaunchDisposition {
2271 server_name,
2272 attach,
2273 path,
2274 settings,
2275 }| match attach {
2276 language::Attach::InstancePerRoot => {
2277 // todo: handle instance per root proper.
2278 if let Some(server_ids) = self
2279 .language_server_ids
2280 .get(&(worktree_id, server_name.clone()))
2281 {
2282 server_ids.iter().cloned().next().unwrap()
2283 } else {
2284 let language_name = language.name();
2285
2286 self.start_language_server(
2287 &worktree,
2288 delegate.clone(),
2289 self.languages
2290 .lsp_adapters(&language_name)
2291 .into_iter()
2292 .find(|adapter| &adapter.name() == server_name)
2293 .expect("To find LSP adapter"),
2294 settings,
2295 cx,
2296 )
2297 }
2298 }
2299 language::Attach::Shared => {
2300 let uri = Url::from_file_path(
2301 worktree.read(cx).abs_path().join(&path.path),
2302 );
2303 let key = (worktree_id, server_name.clone());
2304 if !self.language_server_ids.contains_key(&key) {
2305 let language_name = language.name();
2306 self.start_language_server(
2307 &worktree,
2308 delegate.clone(),
2309 self.languages
2310 .lsp_adapters(&language_name)
2311 .into_iter()
2312 .find(|adapter| &adapter.name() == server_name)
2313 .expect("To find LSP adapter"),
2314 settings,
2315 cx,
2316 );
2317 }
2318 if let Some(server_ids) = self
2319 .language_server_ids
2320 .get(&key)
2321 {
2322 debug_assert_eq!(server_ids.len(), 1);
2323 let server_id = server_ids.iter().cloned().next().unwrap();
2324
2325 if let Some(state) = self.language_servers.get(&server_id) {
2326 if let Ok(uri) = uri {
2327 state.add_workspace_folder(uri);
2328 };
2329 }
2330 server_id
2331 } else {
2332 unreachable!("Language server ID should be available, as it's registered on demand")
2333 }
2334 }
2335 },
2336 )?;
2337 let server_state = self.language_servers.get(&server_id)?;
2338 if let LanguageServerState::Running { server, .. } = server_state {
2339 Some(server.clone())
2340 } else {
2341 None
2342 }
2343 })
2344 .collect::<Vec<_>>();
2345 for server in servers {
2346 buffer_handle.update(cx, |buffer, cx| {
2347 buffer.set_completion_triggers(
2348 server.server_id(),
2349 server
2350 .capabilities()
2351 .completion_provider
2352 .as_ref()
2353 .and_then(|provider| {
2354 provider
2355 .trigger_characters
2356 .as_ref()
2357 .map(|characters| characters.iter().cloned().collect())
2358 })
2359 .unwrap_or_default(),
2360 cx,
2361 );
2362 });
2363 }
2364 for adapter in self.languages.lsp_adapters(&language.name()) {
2365 let servers = self
2366 .language_server_ids
2367 .get(&(worktree_id, adapter.name.clone()))
2368 .map(|ids| {
2369 ids.iter().flat_map(|id| {
2370 self.language_servers.get(id).and_then(|server_state| {
2371 if let LanguageServerState::Running { server, .. } = server_state {
2372 Some(server.clone())
2373 } else {
2374 None
2375 }
2376 })
2377 })
2378 });
2379 let servers = match servers {
2380 Some(server) => server,
2381 None => continue,
2382 };
2383
2384 for server in servers {
2385 let snapshot = LspBufferSnapshot {
2386 version: 0,
2387 snapshot: initial_snapshot.clone(),
2388 };
2389 self.buffer_snapshots
2390 .entry(buffer_id)
2391 .or_default()
2392 .entry(server.server_id())
2393 .or_insert_with(|| {
2394 server.register_buffer(
2395 uri.clone(),
2396 adapter.language_id(&language.name()),
2397 0,
2398 initial_snapshot.text(),
2399 );
2400
2401 vec![snapshot]
2402 });
2403 }
2404 }
2405 }
2406
2407 pub(crate) fn unregister_old_buffer_from_language_servers(
2408 &mut self,
2409 buffer: &Entity<Buffer>,
2410 old_file: &File,
2411 cx: &mut App,
2412 ) {
2413 let old_path = match old_file.as_local() {
2414 Some(local) => local.abs_path(cx),
2415 None => return,
2416 };
2417
2418 let Ok(file_url) = lsp::Url::from_file_path(old_path.as_path()) else {
2419 debug_panic!(
2420 "`{}` is not parseable as an URI",
2421 old_path.to_string_lossy()
2422 );
2423 return;
2424 };
2425 self.unregister_buffer_from_language_servers(buffer, &file_url, cx);
2426 }
2427
2428 pub(crate) fn unregister_buffer_from_language_servers(
2429 &mut self,
2430 buffer: &Entity<Buffer>,
2431 file_url: &lsp::Url,
2432 cx: &mut App,
2433 ) {
2434 buffer.update(cx, |buffer, cx| {
2435 let _ = self.buffer_snapshots.remove(&buffer.remote_id());
2436
2437 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2438 language_server.unregister_buffer(file_url.clone());
2439 }
2440 });
2441 }
2442
2443 fn buffer_snapshot_for_lsp_version(
2444 &mut self,
2445 buffer: &Entity<Buffer>,
2446 server_id: LanguageServerId,
2447 version: Option<i32>,
2448 cx: &App,
2449 ) -> Result<TextBufferSnapshot> {
2450 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
2451
2452 if let Some(version) = version {
2453 let buffer_id = buffer.read(cx).remote_id();
2454 let snapshots = if let Some(snapshots) = self
2455 .buffer_snapshots
2456 .get_mut(&buffer_id)
2457 .and_then(|m| m.get_mut(&server_id))
2458 {
2459 snapshots
2460 } else if version == 0 {
2461 // Some language servers report version 0 even if the buffer hasn't been opened yet.
2462 // We detect this case and treat it as if the version was `None`.
2463 return Ok(buffer.read(cx).text_snapshot());
2464 } else {
2465 return Err(anyhow!(
2466 "no snapshots found for buffer {buffer_id} and server {server_id}"
2467 ));
2468 };
2469
2470 let found_snapshot = snapshots
2471 .binary_search_by_key(&version, |e| e.version)
2472 .map(|ix| snapshots[ix].snapshot.clone())
2473 .map_err(|_| {
2474 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
2475 })?;
2476
2477 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
2478 Ok(found_snapshot)
2479 } else {
2480 Ok((buffer.read(cx)).text_snapshot())
2481 }
2482 }
2483
2484 async fn get_server_code_actions_from_action_kinds(
2485 lsp_store: &WeakEntity<LspStore>,
2486 language_server_id: LanguageServerId,
2487 code_action_kinds: Vec<lsp::CodeActionKind>,
2488 buffer: &Entity<Buffer>,
2489 cx: &mut AsyncApp,
2490 ) -> Result<Vec<CodeAction>> {
2491 let actions = lsp_store
2492 .update(cx, move |this, cx| {
2493 let request = GetCodeActions {
2494 range: text::Anchor::MIN..text::Anchor::MAX,
2495 kinds: Some(code_action_kinds),
2496 };
2497 let server = LanguageServerToQuery::Other(language_server_id);
2498 this.request_lsp(buffer.clone(), server, request, cx)
2499 })?
2500 .await?;
2501 return Ok(actions);
2502 }
2503
2504 pub async fn execute_code_actions_on_server(
2505 lsp_store: &WeakEntity<LspStore>,
2506 language_server: &Arc<LanguageServer>,
2507 lsp_adapter: &Arc<CachedLspAdapter>,
2508 actions: Vec<CodeAction>,
2509 push_to_history: bool,
2510 project_transaction: &mut ProjectTransaction,
2511 cx: &mut AsyncApp,
2512 ) -> Result<(), anyhow::Error> {
2513 for mut action in actions {
2514 Self::try_resolve_code_action(language_server, &mut action)
2515 .await
2516 .context("resolving a formatting code action")?;
2517
2518 if let Some(edit) = action.lsp_action.edit() {
2519 if edit.changes.is_none() && edit.document_changes.is_none() {
2520 continue;
2521 }
2522
2523 let new = Self::deserialize_workspace_edit(
2524 lsp_store.upgrade().context("project dropped")?,
2525 edit.clone(),
2526 push_to_history,
2527 lsp_adapter.clone(),
2528 language_server.clone(),
2529 cx,
2530 )
2531 .await?;
2532 project_transaction.0.extend(new.0);
2533 }
2534
2535 if let Some(command) = action.lsp_action.command() {
2536 let server_capabilities = language_server.capabilities();
2537 let available_commands = server_capabilities
2538 .execute_command_provider
2539 .as_ref()
2540 .map(|options| options.commands.as_slice())
2541 .unwrap_or_default();
2542 if available_commands.contains(&command.command) {
2543 lsp_store.update(cx, |lsp_store, _| {
2544 if let LspStoreMode::Local(mode) = &mut lsp_store.mode {
2545 mode.last_workspace_edits_by_language_server
2546 .remove(&language_server.server_id());
2547 }
2548 })?;
2549
2550 language_server
2551 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
2552 command: command.command.clone(),
2553 arguments: command.arguments.clone().unwrap_or_default(),
2554 ..Default::default()
2555 })
2556 .await?;
2557
2558 lsp_store.update(cx, |this, _| {
2559 if let LspStoreMode::Local(mode) = &mut this.mode {
2560 project_transaction.0.extend(
2561 mode.last_workspace_edits_by_language_server
2562 .remove(&language_server.server_id())
2563 .unwrap_or_default()
2564 .0,
2565 )
2566 }
2567 })?;
2568 } else {
2569 log::warn!(
2570 "Cannot execute a command {} not listed in the language server capabilities",
2571 command.command
2572 )
2573 }
2574 }
2575 }
2576 return Ok(());
2577 }
2578
2579 pub async fn deserialize_text_edits(
2580 this: Entity<LspStore>,
2581 buffer_to_edit: Entity<Buffer>,
2582 edits: Vec<lsp::TextEdit>,
2583 push_to_history: bool,
2584 _: Arc<CachedLspAdapter>,
2585 language_server: Arc<LanguageServer>,
2586 cx: &mut AsyncApp,
2587 ) -> Result<Option<Transaction>> {
2588 let edits = this
2589 .update(cx, |this, cx| {
2590 this.as_local_mut().unwrap().edits_from_lsp(
2591 &buffer_to_edit,
2592 edits,
2593 language_server.server_id(),
2594 None,
2595 cx,
2596 )
2597 })?
2598 .await?;
2599
2600 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2601 buffer.finalize_last_transaction();
2602 buffer.start_transaction();
2603 for (range, text) in edits {
2604 buffer.edit([(range, text)], None, cx);
2605 }
2606
2607 if buffer.end_transaction(cx).is_some() {
2608 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2609 if !push_to_history {
2610 buffer.forget_transaction(transaction.id);
2611 }
2612 Some(transaction)
2613 } else {
2614 None
2615 }
2616 })?;
2617
2618 Ok(transaction)
2619 }
2620
2621 #[allow(clippy::type_complexity)]
2622 pub(crate) fn edits_from_lsp(
2623 &mut self,
2624 buffer: &Entity<Buffer>,
2625 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
2626 server_id: LanguageServerId,
2627 version: Option<i32>,
2628 cx: &mut Context<LspStore>,
2629 ) -> Task<Result<Vec<(Range<Anchor>, Arc<str>)>>> {
2630 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
2631 cx.background_spawn(async move {
2632 let snapshot = snapshot?;
2633 let mut lsp_edits = lsp_edits
2634 .into_iter()
2635 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
2636 .collect::<Vec<_>>();
2637 lsp_edits.sort_by_key(|(range, _)| range.start);
2638
2639 let mut lsp_edits = lsp_edits.into_iter().peekable();
2640 let mut edits = Vec::new();
2641 while let Some((range, mut new_text)) = lsp_edits.next() {
2642 // Clip invalid ranges provided by the language server.
2643 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
2644 ..snapshot.clip_point_utf16(range.end, Bias::Left);
2645
2646 // Combine any LSP edits that are adjacent.
2647 //
2648 // Also, combine LSP edits that are separated from each other by only
2649 // a newline. This is important because for some code actions,
2650 // Rust-analyzer rewrites the entire buffer via a series of edits that
2651 // are separated by unchanged newline characters.
2652 //
2653 // In order for the diffing logic below to work properly, any edits that
2654 // cancel each other out must be combined into one.
2655 while let Some((next_range, next_text)) = lsp_edits.peek() {
2656 if next_range.start.0 > range.end {
2657 if next_range.start.0.row > range.end.row + 1
2658 || next_range.start.0.column > 0
2659 || snapshot.clip_point_utf16(
2660 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
2661 Bias::Left,
2662 ) > range.end
2663 {
2664 break;
2665 }
2666 new_text.push('\n');
2667 }
2668 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
2669 new_text.push_str(next_text);
2670 lsp_edits.next();
2671 }
2672
2673 // For multiline edits, perform a diff of the old and new text so that
2674 // we can identify the changes more precisely, preserving the locations
2675 // of any anchors positioned in the unchanged regions.
2676 if range.end.row > range.start.row {
2677 let offset = range.start.to_offset(&snapshot);
2678 let old_text = snapshot.text_for_range(range).collect::<String>();
2679 let range_edits = language::text_diff(old_text.as_str(), &new_text);
2680 edits.extend(range_edits.into_iter().map(|(range, replacement)| {
2681 (
2682 snapshot.anchor_after(offset + range.start)
2683 ..snapshot.anchor_before(offset + range.end),
2684 replacement,
2685 )
2686 }));
2687 } else if range.end == range.start {
2688 let anchor = snapshot.anchor_after(range.start);
2689 edits.push((anchor..anchor, new_text.into()));
2690 } else {
2691 let edit_start = snapshot.anchor_after(range.start);
2692 let edit_end = snapshot.anchor_before(range.end);
2693 edits.push((edit_start..edit_end, new_text.into()));
2694 }
2695 }
2696
2697 Ok(edits)
2698 })
2699 }
2700
2701 pub(crate) async fn deserialize_workspace_edit(
2702 this: Entity<LspStore>,
2703 edit: lsp::WorkspaceEdit,
2704 push_to_history: bool,
2705 lsp_adapter: Arc<CachedLspAdapter>,
2706 language_server: Arc<LanguageServer>,
2707 cx: &mut AsyncApp,
2708 ) -> Result<ProjectTransaction> {
2709 let fs = this.read_with(cx, |this, _| this.as_local().unwrap().fs.clone())?;
2710
2711 let mut operations = Vec::new();
2712 if let Some(document_changes) = edit.document_changes {
2713 match document_changes {
2714 lsp::DocumentChanges::Edits(edits) => {
2715 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2716 }
2717 lsp::DocumentChanges::Operations(ops) => operations = ops,
2718 }
2719 } else if let Some(changes) = edit.changes {
2720 operations.extend(changes.into_iter().map(|(uri, edits)| {
2721 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2722 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2723 uri,
2724 version: None,
2725 },
2726 edits: edits.into_iter().map(Edit::Plain).collect(),
2727 })
2728 }));
2729 }
2730
2731 let mut project_transaction = ProjectTransaction::default();
2732 for operation in operations {
2733 match operation {
2734 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2735 let abs_path = op
2736 .uri
2737 .to_file_path()
2738 .map_err(|_| anyhow!("can't convert URI to path"))?;
2739
2740 if let Some(parent_path) = abs_path.parent() {
2741 fs.create_dir(parent_path).await?;
2742 }
2743 if abs_path.ends_with("/") {
2744 fs.create_dir(&abs_path).await?;
2745 } else {
2746 fs.create_file(
2747 &abs_path,
2748 op.options
2749 .map(|options| fs::CreateOptions {
2750 overwrite: options.overwrite.unwrap_or(false),
2751 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2752 })
2753 .unwrap_or_default(),
2754 )
2755 .await?;
2756 }
2757 }
2758
2759 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2760 let source_abs_path = op
2761 .old_uri
2762 .to_file_path()
2763 .map_err(|_| anyhow!("can't convert URI to path"))?;
2764 let target_abs_path = op
2765 .new_uri
2766 .to_file_path()
2767 .map_err(|_| anyhow!("can't convert URI to path"))?;
2768 fs.rename(
2769 &source_abs_path,
2770 &target_abs_path,
2771 op.options
2772 .map(|options| fs::RenameOptions {
2773 overwrite: options.overwrite.unwrap_or(false),
2774 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2775 })
2776 .unwrap_or_default(),
2777 )
2778 .await?;
2779 }
2780
2781 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2782 let abs_path = op
2783 .uri
2784 .to_file_path()
2785 .map_err(|_| anyhow!("can't convert URI to path"))?;
2786 let options = op
2787 .options
2788 .map(|options| fs::RemoveOptions {
2789 recursive: options.recursive.unwrap_or(false),
2790 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2791 })
2792 .unwrap_or_default();
2793 if abs_path.ends_with("/") {
2794 fs.remove_dir(&abs_path, options).await?;
2795 } else {
2796 fs.remove_file(&abs_path, options).await?;
2797 }
2798 }
2799
2800 lsp::DocumentChangeOperation::Edit(op) => {
2801 let buffer_to_edit = this
2802 .update(cx, |this, cx| {
2803 this.open_local_buffer_via_lsp(
2804 op.text_document.uri.clone(),
2805 language_server.server_id(),
2806 lsp_adapter.name.clone(),
2807 cx,
2808 )
2809 })?
2810 .await?;
2811
2812 let edits = this
2813 .update(cx, |this, cx| {
2814 let path = buffer_to_edit.read(cx).project_path(cx);
2815 let active_entry = this.active_entry;
2816 let is_active_entry = path.clone().map_or(false, |project_path| {
2817 this.worktree_store
2818 .read(cx)
2819 .entry_for_path(&project_path, cx)
2820 .map_or(false, |entry| Some(entry.id) == active_entry)
2821 });
2822 let local = this.as_local_mut().unwrap();
2823
2824 let (mut edits, mut snippet_edits) = (vec![], vec![]);
2825 for edit in op.edits {
2826 match edit {
2827 Edit::Plain(edit) => {
2828 if !edits.contains(&edit) {
2829 edits.push(edit)
2830 }
2831 }
2832 Edit::Annotated(edit) => {
2833 if !edits.contains(&edit.text_edit) {
2834 edits.push(edit.text_edit)
2835 }
2836 }
2837 Edit::Snippet(edit) => {
2838 let Ok(snippet) = Snippet::parse(&edit.snippet.value)
2839 else {
2840 continue;
2841 };
2842
2843 if is_active_entry {
2844 snippet_edits.push((edit.range, snippet));
2845 } else {
2846 // Since this buffer is not focused, apply a normal edit.
2847 let new_edit = TextEdit {
2848 range: edit.range,
2849 new_text: snippet.text,
2850 };
2851 if !edits.contains(&new_edit) {
2852 edits.push(new_edit);
2853 }
2854 }
2855 }
2856 }
2857 }
2858 if !snippet_edits.is_empty() {
2859 let buffer_id = buffer_to_edit.read(cx).remote_id();
2860 let version = if let Some(buffer_version) = op.text_document.version
2861 {
2862 local
2863 .buffer_snapshot_for_lsp_version(
2864 &buffer_to_edit,
2865 language_server.server_id(),
2866 Some(buffer_version),
2867 cx,
2868 )
2869 .ok()
2870 .map(|snapshot| snapshot.version)
2871 } else {
2872 Some(buffer_to_edit.read(cx).saved_version().clone())
2873 };
2874
2875 let most_recent_edit = version.and_then(|version| {
2876 version.iter().max_by_key(|timestamp| timestamp.value)
2877 });
2878 // Check if the edit that triggered that edit has been made by this participant.
2879
2880 if let Some(most_recent_edit) = most_recent_edit {
2881 cx.emit(LspStoreEvent::SnippetEdit {
2882 buffer_id,
2883 edits: snippet_edits,
2884 most_recent_edit,
2885 });
2886 }
2887 }
2888
2889 local.edits_from_lsp(
2890 &buffer_to_edit,
2891 edits,
2892 language_server.server_id(),
2893 op.text_document.version,
2894 cx,
2895 )
2896 })?
2897 .await?;
2898
2899 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2900 buffer.finalize_last_transaction();
2901 buffer.start_transaction();
2902 for (range, text) in edits {
2903 buffer.edit([(range, text)], None, cx);
2904 }
2905 let transaction = if buffer.end_transaction(cx).is_some() {
2906 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2907 if !push_to_history {
2908 buffer.forget_transaction(transaction.id);
2909 }
2910 Some(transaction)
2911 } else {
2912 None
2913 };
2914
2915 transaction
2916 })?;
2917 if let Some(transaction) = transaction {
2918 project_transaction.0.insert(buffer_to_edit, transaction);
2919 }
2920 }
2921 }
2922 }
2923
2924 Ok(project_transaction)
2925 }
2926
2927 async fn on_lsp_workspace_edit(
2928 this: WeakEntity<LspStore>,
2929 params: lsp::ApplyWorkspaceEditParams,
2930 server_id: LanguageServerId,
2931 adapter: Arc<CachedLspAdapter>,
2932 cx: &mut AsyncApp,
2933 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2934 let this = this
2935 .upgrade()
2936 .ok_or_else(|| anyhow!("project project closed"))?;
2937 let language_server = this
2938 .update(cx, |this, _| this.language_server_for_id(server_id))?
2939 .ok_or_else(|| anyhow!("language server not found"))?;
2940 let transaction = Self::deserialize_workspace_edit(
2941 this.clone(),
2942 params.edit,
2943 true,
2944 adapter.clone(),
2945 language_server.clone(),
2946 cx,
2947 )
2948 .await
2949 .log_err();
2950 this.update(cx, |this, _| {
2951 if let Some(transaction) = transaction {
2952 this.as_local_mut()
2953 .unwrap()
2954 .last_workspace_edits_by_language_server
2955 .insert(server_id, transaction);
2956 }
2957 })?;
2958 Ok(lsp::ApplyWorkspaceEditResponse {
2959 applied: true,
2960 failed_change: None,
2961 failure_reason: None,
2962 })
2963 }
2964
2965 fn remove_worktree(
2966 &mut self,
2967 id_to_remove: WorktreeId,
2968 cx: &mut Context<LspStore>,
2969 ) -> Vec<LanguageServerId> {
2970 self.diagnostics.remove(&id_to_remove);
2971 self.prettier_store.update(cx, |prettier_store, cx| {
2972 prettier_store.remove_worktree(id_to_remove, cx);
2973 });
2974
2975 let mut servers_to_remove = BTreeMap::default();
2976 let mut servers_to_preserve = HashSet::default();
2977 for ((path, server_name), ref server_ids) in &self.language_server_ids {
2978 if *path == id_to_remove {
2979 servers_to_remove.extend(server_ids.iter().map(|id| (*id, server_name.clone())));
2980 } else {
2981 servers_to_preserve.extend(server_ids.iter().cloned());
2982 }
2983 }
2984 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
2985
2986 for (server_id_to_remove, _) in &servers_to_remove {
2987 self.language_server_ids
2988 .values_mut()
2989 .for_each(|server_ids| {
2990 server_ids.remove(server_id_to_remove);
2991 });
2992 self.language_server_watched_paths
2993 .remove(&server_id_to_remove);
2994 self.language_server_paths_watched_for_rename
2995 .remove(&server_id_to_remove);
2996 self.last_workspace_edits_by_language_server
2997 .remove(&server_id_to_remove);
2998 self.language_servers.remove(&server_id_to_remove);
2999 cx.emit(LspStoreEvent::LanguageServerRemoved(*server_id_to_remove));
3000 }
3001 servers_to_remove.into_keys().collect()
3002 }
3003
3004 fn rebuild_watched_paths_inner<'a>(
3005 &'a self,
3006 language_server_id: LanguageServerId,
3007 watchers: impl Iterator<Item = &'a FileSystemWatcher>,
3008 cx: &mut Context<LspStore>,
3009 ) -> LanguageServerWatchedPathsBuilder {
3010 let worktrees = self
3011 .worktree_store
3012 .read(cx)
3013 .worktrees()
3014 .filter_map(|worktree| {
3015 self.language_servers_for_worktree(worktree.read(cx).id())
3016 .find(|server| server.server_id() == language_server_id)
3017 .map(|_| worktree)
3018 })
3019 .collect::<Vec<_>>();
3020
3021 let mut worktree_globs = HashMap::default();
3022 let mut abs_globs = HashMap::default();
3023 log::trace!(
3024 "Processing new watcher paths for language server with id {}",
3025 language_server_id
3026 );
3027
3028 enum PathToWatch {
3029 Worktree {
3030 literal_prefix: Arc<Path>,
3031 pattern: String,
3032 },
3033 Absolute {
3034 path: Arc<Path>,
3035 pattern: String,
3036 },
3037 }
3038 for watcher in watchers {
3039 let mut found_host = false;
3040 for worktree in &worktrees {
3041 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3042 let worktree_root_path = tree.abs_path();
3043 let path_to_watch = match &watcher.glob_pattern {
3044 lsp::GlobPattern::String(s) => {
3045 let watcher_path = SanitizedPath::from(s);
3046 match watcher_path.as_path().strip_prefix(&worktree_root_path) {
3047 Ok(relative) => {
3048 let pattern = relative.to_string_lossy().to_string();
3049 let literal_prefix = glob_literal_prefix(relative).into();
3050
3051 PathToWatch::Worktree {
3052 literal_prefix,
3053 pattern,
3054 }
3055 }
3056 Err(_) => {
3057 let path = glob_literal_prefix(watcher_path.as_path());
3058 let pattern = watcher_path
3059 .as_path()
3060 .strip_prefix(&path)
3061 .map(|p| p.to_string_lossy().to_string())
3062 .unwrap_or_else(|e| {
3063 debug_panic!(
3064 "Failed to strip prefix for string pattern: {}, with prefix: {}, with error: {}",
3065 s,
3066 path.display(),
3067 e
3068 );
3069 watcher_path.as_path().to_string_lossy().to_string()
3070 });
3071 let path = if path.components().next().is_none() {
3072 worktree_root_path.clone()
3073 } else {
3074 path.into()
3075 };
3076
3077 PathToWatch::Absolute { path, pattern }
3078 }
3079 }
3080 }
3081 lsp::GlobPattern::Relative(rp) => {
3082 let Ok(mut base_uri) = match &rp.base_uri {
3083 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3084 lsp::OneOf::Right(base_uri) => base_uri,
3085 }
3086 .to_file_path() else {
3087 return false;
3088 };
3089
3090 match base_uri.strip_prefix(&worktree_root_path) {
3091 Ok(relative) => {
3092 let mut literal_prefix = relative.to_owned();
3093 literal_prefix
3094 .push(glob_literal_prefix(Path::new(&rp.pattern)));
3095
3096 PathToWatch::Worktree {
3097 literal_prefix: literal_prefix.into(),
3098 pattern: rp.pattern.clone(),
3099 }
3100 }
3101 Err(_) => {
3102 let path = glob_literal_prefix(Path::new(&rp.pattern));
3103 let pattern = Path::new(&rp.pattern)
3104 .strip_prefix(&path)
3105 .map(|p| p.to_string_lossy().to_string())
3106 .unwrap_or_else(|e| {
3107 debug_panic!(
3108 "Failed to strip prefix for relative pattern: {}, with prefix: {}, with error: {}",
3109 rp.pattern,
3110 path.display(),
3111 e
3112 );
3113 rp.pattern.clone()
3114 });
3115 base_uri.push(path);
3116
3117 let path = if base_uri.components().next().is_none() {
3118 debug_panic!("base_uri is empty, {}", base_uri.display());
3119 worktree_root_path.clone()
3120 } else {
3121 base_uri.into()
3122 };
3123 PathToWatch::Absolute { path, pattern }
3124 }
3125 }
3126 }
3127 };
3128 match path_to_watch {
3129 PathToWatch::Worktree {
3130 literal_prefix,
3131 pattern,
3132 } => {
3133 if let Some((tree, glob)) =
3134 tree.as_local_mut().zip(Glob::new(&pattern).log_err())
3135 {
3136 tree.add_path_prefix_to_scan(literal_prefix);
3137 worktree_globs
3138 .entry(tree.id())
3139 .or_insert_with(GlobSetBuilder::new)
3140 .add(glob);
3141 } else {
3142 return false;
3143 }
3144 }
3145 PathToWatch::Absolute { path, pattern } => {
3146 if let Some(glob) = Glob::new(&pattern).log_err() {
3147 abs_globs
3148 .entry(path)
3149 .or_insert_with(GlobSetBuilder::new)
3150 .add(glob);
3151 }
3152 }
3153 }
3154 true
3155 });
3156 if glob_is_inside_worktree {
3157 log::trace!(
3158 "Watcher pattern `{}` has been attached to the worktree at `{}`",
3159 serde_json::to_string(&watcher.glob_pattern).unwrap(),
3160 worktree.read(cx).abs_path().display()
3161 );
3162 found_host = true;
3163 }
3164 }
3165 if !found_host {
3166 log::error!(
3167 "Watcher pattern `{}` has not been attached to any worktree or absolute path",
3168 serde_json::to_string(&watcher.glob_pattern).unwrap()
3169 )
3170 }
3171 }
3172
3173 let mut watch_builder = LanguageServerWatchedPathsBuilder::default();
3174 for (worktree_id, builder) in worktree_globs {
3175 if let Ok(globset) = builder.build() {
3176 watch_builder.watch_worktree(worktree_id, globset);
3177 }
3178 }
3179 for (abs_path, builder) in abs_globs {
3180 if let Ok(globset) = builder.build() {
3181 watch_builder.watch_abs_path(abs_path, globset);
3182 }
3183 }
3184 watch_builder
3185 }
3186
3187 fn rebuild_watched_paths(
3188 &mut self,
3189 language_server_id: LanguageServerId,
3190 cx: &mut Context<LspStore>,
3191 ) {
3192 let Some(watchers) = self
3193 .language_server_watcher_registrations
3194 .get(&language_server_id)
3195 else {
3196 return;
3197 };
3198
3199 let watch_builder =
3200 self.rebuild_watched_paths_inner(language_server_id, watchers.values().flatten(), cx);
3201 let watcher = watch_builder.build(self.fs.clone(), language_server_id, cx);
3202 self.language_server_watched_paths
3203 .insert(language_server_id, watcher);
3204
3205 cx.notify();
3206 }
3207
3208 fn on_lsp_did_change_watched_files(
3209 &mut self,
3210 language_server_id: LanguageServerId,
3211 registration_id: &str,
3212 params: DidChangeWatchedFilesRegistrationOptions,
3213 cx: &mut Context<LspStore>,
3214 ) {
3215 let registrations = self
3216 .language_server_watcher_registrations
3217 .entry(language_server_id)
3218 .or_default();
3219
3220 registrations.insert(registration_id.to_string(), params.watchers);
3221
3222 self.rebuild_watched_paths(language_server_id, cx);
3223 }
3224
3225 fn on_lsp_unregister_did_change_watched_files(
3226 &mut self,
3227 language_server_id: LanguageServerId,
3228 registration_id: &str,
3229 cx: &mut Context<LspStore>,
3230 ) {
3231 let registrations = self
3232 .language_server_watcher_registrations
3233 .entry(language_server_id)
3234 .or_default();
3235
3236 if registrations.remove(registration_id).is_some() {
3237 log::info!(
3238 "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
3239 language_server_id,
3240 registration_id
3241 );
3242 } else {
3243 log::warn!(
3244 "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
3245 language_server_id,
3246 registration_id
3247 );
3248 }
3249
3250 self.rebuild_watched_paths(language_server_id, cx);
3251 }
3252
3253 async fn initialization_options_for_adapter(
3254 adapter: Arc<dyn LspAdapter>,
3255 fs: &dyn Fs,
3256 delegate: &Arc<dyn LspAdapterDelegate>,
3257 ) -> Result<Option<serde_json::Value>> {
3258 let Some(mut initialization_config) =
3259 adapter.clone().initialization_options(fs, delegate).await?
3260 else {
3261 return Ok(None);
3262 };
3263
3264 for other_adapter in delegate.registered_lsp_adapters() {
3265 if other_adapter.name() == adapter.name() {
3266 continue;
3267 }
3268 if let Ok(Some(target_config)) = other_adapter
3269 .clone()
3270 .additional_initialization_options(adapter.name(), fs, delegate)
3271 .await
3272 {
3273 merge_json_value_into(target_config.clone(), &mut initialization_config);
3274 }
3275 }
3276
3277 Ok(Some(initialization_config))
3278 }
3279
3280 async fn workspace_configuration_for_adapter(
3281 adapter: Arc<dyn LspAdapter>,
3282 fs: &dyn Fs,
3283 delegate: &Arc<dyn LspAdapterDelegate>,
3284 toolchains: Arc<dyn LanguageToolchainStore>,
3285 cx: &mut AsyncApp,
3286 ) -> Result<serde_json::Value> {
3287 let mut workspace_config = adapter
3288 .clone()
3289 .workspace_configuration(fs, delegate, toolchains.clone(), cx)
3290 .await?;
3291
3292 for other_adapter in delegate.registered_lsp_adapters() {
3293 if other_adapter.name() == adapter.name() {
3294 continue;
3295 }
3296 if let Ok(Some(target_config)) = other_adapter
3297 .clone()
3298 .additional_workspace_configuration(
3299 adapter.name(),
3300 fs,
3301 delegate,
3302 toolchains.clone(),
3303 cx,
3304 )
3305 .await
3306 {
3307 merge_json_value_into(target_config.clone(), &mut workspace_config);
3308 }
3309 }
3310
3311 Ok(workspace_config)
3312 }
3313}
3314
3315#[derive(Debug)]
3316pub struct FormattableBuffer {
3317 handle: Entity<Buffer>,
3318 abs_path: Option<PathBuf>,
3319 env: Option<HashMap<String, String>>,
3320 ranges: Option<Vec<Range<Anchor>>>,
3321}
3322
3323pub struct RemoteLspStore {
3324 upstream_client: Option<AnyProtoClient>,
3325 upstream_project_id: u64,
3326}
3327
3328#[allow(clippy::large_enum_variant)]
3329pub(crate) enum LspStoreMode {
3330 Local(LocalLspStore), // ssh host and collab host
3331 Remote(RemoteLspStore), // collab guest
3332}
3333
3334impl LspStoreMode {
3335 fn is_local(&self) -> bool {
3336 matches!(self, LspStoreMode::Local(_))
3337 }
3338}
3339
3340pub struct LspStore {
3341 mode: LspStoreMode,
3342 last_formatting_failure: Option<String>,
3343 downstream_client: Option<(AnyProtoClient, u64)>,
3344 nonce: u128,
3345 buffer_store: Entity<BufferStore>,
3346 worktree_store: Entity<WorktreeStore>,
3347 toolchain_store: Option<Entity<ToolchainStore>>,
3348 pub languages: Arc<LanguageRegistry>,
3349 pub language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3350 active_entry: Option<ProjectEntryId>,
3351 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3352 _maintain_buffer_languages: Task<()>,
3353 diagnostic_summaries:
3354 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3355}
3356
3357pub enum LspStoreEvent {
3358 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3359 LanguageServerRemoved(LanguageServerId),
3360 LanguageServerUpdate {
3361 language_server_id: LanguageServerId,
3362 message: proto::update_language_server::Variant,
3363 },
3364 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3365 LanguageServerPrompt(LanguageServerPromptRequest),
3366 LanguageDetected {
3367 buffer: Entity<Buffer>,
3368 new_language: Option<Arc<Language>>,
3369 },
3370 Notification(String),
3371 RefreshInlayHints,
3372 RefreshCodeLens,
3373 DiagnosticsUpdated {
3374 language_server_id: LanguageServerId,
3375 path: ProjectPath,
3376 },
3377 DiskBasedDiagnosticsStarted {
3378 language_server_id: LanguageServerId,
3379 },
3380 DiskBasedDiagnosticsFinished {
3381 language_server_id: LanguageServerId,
3382 },
3383 SnippetEdit {
3384 buffer_id: BufferId,
3385 edits: Vec<(lsp::Range, Snippet)>,
3386 most_recent_edit: clock::Lamport,
3387 },
3388}
3389
3390#[derive(Clone, Debug, Serialize)]
3391pub struct LanguageServerStatus {
3392 pub name: String,
3393 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3394 pub has_pending_diagnostic_updates: bool,
3395 progress_tokens: HashSet<String>,
3396}
3397
3398#[derive(Clone, Debug)]
3399struct CoreSymbol {
3400 pub language_server_name: LanguageServerName,
3401 pub source_worktree_id: WorktreeId,
3402 pub source_language_server_id: LanguageServerId,
3403 pub path: ProjectPath,
3404 pub name: String,
3405 pub kind: lsp::SymbolKind,
3406 pub range: Range<Unclipped<PointUtf16>>,
3407 pub signature: [u8; 32],
3408}
3409
3410impl LspStore {
3411 pub fn init(client: &AnyProtoClient) {
3412 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3413 client.add_entity_request_handler(Self::handle_restart_language_servers);
3414 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3415 client.add_entity_message_handler(Self::handle_start_language_server);
3416 client.add_entity_message_handler(Self::handle_update_language_server);
3417 client.add_entity_message_handler(Self::handle_language_server_log);
3418 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3419 client.add_entity_request_handler(Self::handle_format_buffers);
3420 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3421 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3422 client.add_entity_request_handler(Self::handle_apply_code_action);
3423 client.add_entity_request_handler(Self::handle_inlay_hints);
3424 client.add_entity_request_handler(Self::handle_get_project_symbols);
3425 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3426 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3427 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3428 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3429 client.add_entity_request_handler(Self::handle_on_type_formatting);
3430 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3431 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3432 client.add_entity_request_handler(Self::handle_rename_project_entry);
3433 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3434 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3435 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3436 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3437 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3438 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3439 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3440 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3441 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3442 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3443 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3444 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3445 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3446
3447 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3448 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3449 client.add_entity_request_handler(
3450 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3451 );
3452 }
3453
3454 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3455 match &self.mode {
3456 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3457 _ => None,
3458 }
3459 }
3460
3461 pub fn as_local(&self) -> Option<&LocalLspStore> {
3462 match &self.mode {
3463 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3464 _ => None,
3465 }
3466 }
3467
3468 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3469 match &mut self.mode {
3470 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3471 _ => None,
3472 }
3473 }
3474
3475 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3476 match &self.mode {
3477 LspStoreMode::Remote(RemoteLspStore {
3478 upstream_client: Some(upstream_client),
3479 upstream_project_id,
3480 ..
3481 }) => Some((upstream_client.clone(), *upstream_project_id)),
3482
3483 LspStoreMode::Remote(RemoteLspStore {
3484 upstream_client: None,
3485 ..
3486 }) => None,
3487 LspStoreMode::Local(_) => None,
3488 }
3489 }
3490
3491 pub fn new_local(
3492 buffer_store: Entity<BufferStore>,
3493 worktree_store: Entity<WorktreeStore>,
3494 prettier_store: Entity<PrettierStore>,
3495 toolchain_store: Entity<ToolchainStore>,
3496 environment: Entity<ProjectEnvironment>,
3497 languages: Arc<LanguageRegistry>,
3498 http_client: Arc<dyn HttpClient>,
3499 fs: Arc<dyn Fs>,
3500 cx: &mut Context<Self>,
3501 ) -> Self {
3502 let yarn = YarnPathStore::new(fs.clone(), cx);
3503 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3504 .detach();
3505 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3506 .detach();
3507 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3508 .detach();
3509 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3510 .detach();
3511 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3512 cx.subscribe(
3513 extension_events,
3514 Self::reload_zed_json_schemas_on_extensions_changed,
3515 )
3516 .detach();
3517 } else {
3518 log::info!("No extension events global found. Skipping JSON schema auto-reload setup");
3519 }
3520 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3521 .detach();
3522
3523 let _maintain_workspace_config = {
3524 let (sender, receiver) = watch::channel();
3525 (
3526 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3527 sender,
3528 )
3529 };
3530 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
3531 Self {
3532 mode: LspStoreMode::Local(LocalLspStore {
3533 weak: cx.weak_entity(),
3534 worktree_store: worktree_store.clone(),
3535 toolchain_store: toolchain_store.clone(),
3536 supplementary_language_servers: Default::default(),
3537 languages: languages.clone(),
3538 language_server_ids: Default::default(),
3539 language_servers: Default::default(),
3540 last_workspace_edits_by_language_server: Default::default(),
3541 language_server_watched_paths: Default::default(),
3542 language_server_paths_watched_for_rename: Default::default(),
3543 language_server_watcher_registrations: Default::default(),
3544 buffers_being_formatted: Default::default(),
3545 buffer_snapshots: Default::default(),
3546 prettier_store,
3547 environment,
3548 http_client,
3549 fs,
3550 yarn,
3551 next_diagnostic_group_id: Default::default(),
3552 diagnostics: Default::default(),
3553 _subscription: cx.on_app_quit(|this, cx| {
3554 this.as_local_mut().unwrap().shutdown_language_servers(cx)
3555 }),
3556 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3557 registered_buffers: Default::default(),
3558 }),
3559 last_formatting_failure: None,
3560 downstream_client: None,
3561 buffer_store,
3562 worktree_store,
3563 toolchain_store: Some(toolchain_store),
3564 languages: languages.clone(),
3565 language_server_statuses: Default::default(),
3566 nonce: StdRng::from_entropy().r#gen(),
3567 diagnostic_summaries: Default::default(),
3568 active_entry: None,
3569
3570 _maintain_workspace_config,
3571 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3572 }
3573 }
3574
3575 fn send_lsp_proto_request<R: LspCommand>(
3576 &self,
3577 buffer: Entity<Buffer>,
3578 client: AnyProtoClient,
3579 upstream_project_id: u64,
3580 request: R,
3581 cx: &mut Context<LspStore>,
3582 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3583 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3584 cx.spawn(async move |this, cx| {
3585 let response = client.request(message).await?;
3586 let this = this.upgrade().context("project dropped")?;
3587 request
3588 .response_from_proto(response, this, buffer, cx.clone())
3589 .await
3590 })
3591 }
3592
3593 pub(super) fn new_remote(
3594 buffer_store: Entity<BufferStore>,
3595 worktree_store: Entity<WorktreeStore>,
3596 toolchain_store: Option<Entity<ToolchainStore>>,
3597 languages: Arc<LanguageRegistry>,
3598 upstream_client: AnyProtoClient,
3599 project_id: u64,
3600 fs: Arc<dyn Fs>,
3601 cx: &mut Context<Self>,
3602 ) -> Self {
3603 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3604 .detach();
3605 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3606 .detach();
3607 let _maintain_workspace_config = {
3608 let (sender, receiver) = watch::channel();
3609 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3610 };
3611 Self {
3612 mode: LspStoreMode::Remote(RemoteLspStore {
3613 upstream_client: Some(upstream_client),
3614 upstream_project_id: project_id,
3615 }),
3616 downstream_client: None,
3617 last_formatting_failure: None,
3618 buffer_store,
3619 worktree_store,
3620 languages: languages.clone(),
3621 language_server_statuses: Default::default(),
3622 nonce: StdRng::from_entropy().r#gen(),
3623 diagnostic_summaries: Default::default(),
3624 active_entry: None,
3625 toolchain_store,
3626 _maintain_workspace_config,
3627 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3628 }
3629 }
3630
3631 fn on_buffer_store_event(
3632 &mut self,
3633 _: Entity<BufferStore>,
3634 event: &BufferStoreEvent,
3635 cx: &mut Context<Self>,
3636 ) {
3637 match event {
3638 BufferStoreEvent::BufferAdded(buffer) => {
3639 self.on_buffer_added(buffer, cx).log_err();
3640 }
3641 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3642 let buffer_id = buffer.read(cx).remote_id();
3643 if let Some(local) = self.as_local_mut() {
3644 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3645 local.reset_buffer(buffer, old_file, cx);
3646
3647 if local.registered_buffers.contains_key(&buffer_id) {
3648 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3649 }
3650 }
3651 }
3652
3653 self.detect_language_for_buffer(buffer, cx);
3654 if let Some(local) = self.as_local_mut() {
3655 local.initialize_buffer(buffer, cx);
3656 if local.registered_buffers.contains_key(&buffer_id) {
3657 local.register_buffer_with_language_servers(buffer, cx);
3658 }
3659 }
3660 }
3661 _ => {}
3662 }
3663 }
3664
3665 fn on_worktree_store_event(
3666 &mut self,
3667 _: Entity<WorktreeStore>,
3668 event: &WorktreeStoreEvent,
3669 cx: &mut Context<Self>,
3670 ) {
3671 match event {
3672 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3673 if !worktree.read(cx).is_local() {
3674 return;
3675 }
3676 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3677 worktree::Event::UpdatedEntries(changes) => {
3678 this.update_local_worktree_language_servers(&worktree, changes, cx);
3679 }
3680 worktree::Event::UpdatedGitRepositories(_)
3681 | worktree::Event::DeletedEntry(_) => {}
3682 })
3683 .detach()
3684 }
3685 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3686 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3687 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3688 }
3689 WorktreeStoreEvent::WorktreeReleased(..)
3690 | WorktreeStoreEvent::WorktreeOrderChanged
3691 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3692 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3693 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3694 }
3695 }
3696
3697 fn on_prettier_store_event(
3698 &mut self,
3699 _: Entity<PrettierStore>,
3700 event: &PrettierStoreEvent,
3701 cx: &mut Context<Self>,
3702 ) {
3703 match event {
3704 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3705 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3706 }
3707 PrettierStoreEvent::LanguageServerAdded {
3708 new_server_id,
3709 name,
3710 prettier_server,
3711 } => {
3712 self.register_supplementary_language_server(
3713 *new_server_id,
3714 name.clone(),
3715 prettier_server.clone(),
3716 cx,
3717 );
3718 }
3719 }
3720 }
3721
3722 fn on_toolchain_store_event(
3723 &mut self,
3724 _: Entity<ToolchainStore>,
3725 event: &ToolchainStoreEvent,
3726 _: &mut Context<Self>,
3727 ) {
3728 match event {
3729 ToolchainStoreEvent::ToolchainActivated { .. } => {
3730 self.request_workspace_config_refresh()
3731 }
3732 }
3733 }
3734
3735 fn request_workspace_config_refresh(&mut self) {
3736 *self._maintain_workspace_config.1.borrow_mut() = ();
3737 }
3738
3739 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3740 self.as_local().map(|local| local.prettier_store.clone())
3741 }
3742
3743 fn on_buffer_event(
3744 &mut self,
3745 buffer: Entity<Buffer>,
3746 event: &language::BufferEvent,
3747 cx: &mut Context<Self>,
3748 ) {
3749 match event {
3750 language::BufferEvent::Edited { .. } => {
3751 self.on_buffer_edited(buffer, cx);
3752 }
3753
3754 language::BufferEvent::Saved => {
3755 self.on_buffer_saved(buffer, cx);
3756 }
3757
3758 _ => {}
3759 }
3760 }
3761
3762 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3763 buffer.update(cx, |buffer, _| {
3764 buffer.set_language_registry(self.languages.clone())
3765 });
3766
3767 cx.subscribe(buffer, |this, buffer, event, cx| {
3768 this.on_buffer_event(buffer, event, cx);
3769 })
3770 .detach();
3771
3772 self.detect_language_for_buffer(buffer, cx);
3773 if let Some(local) = self.as_local_mut() {
3774 local.initialize_buffer(buffer, cx);
3775 }
3776
3777 Ok(())
3778 }
3779
3780 pub fn reload_zed_json_schemas_on_extensions_changed(
3781 &mut self,
3782 _: Entity<extension::ExtensionEvents>,
3783 evt: &extension::Event,
3784 cx: &mut Context<Self>,
3785 ) {
3786 #[expect(
3787 irrefutable_let_patterns,
3788 reason = "Make sure to handle new event types in extension properly"
3789 )]
3790 let extension::Event::ExtensionsInstalledChanged = evt else {
3791 return;
3792 };
3793 if self.as_local().is_none() {
3794 return;
3795 }
3796 cx.spawn(async move |this, cx| {
3797 let weak_ref = this.clone();
3798
3799 let servers = this
3800 .update(cx, |this, cx| {
3801 let local = this.as_local()?;
3802
3803 let mut servers = Vec::new();
3804 for ((worktree_id, _), server_ids) in &local.language_server_ids {
3805 for server_id in server_ids {
3806 let Some(states) = local.language_servers.get(server_id) else {
3807 continue;
3808 };
3809 let (json_adapter, json_server) = match states {
3810 LanguageServerState::Running {
3811 adapter, server, ..
3812 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
3813 (adapter.adapter.clone(), server.clone())
3814 }
3815 _ => continue,
3816 };
3817
3818 let Some(worktree) = this
3819 .worktree_store
3820 .read(cx)
3821 .worktree_for_id(*worktree_id, cx)
3822 else {
3823 continue;
3824 };
3825 let json_delegate: Arc<dyn LspAdapterDelegate> =
3826 LocalLspAdapterDelegate::new(
3827 local.languages.clone(),
3828 &local.environment,
3829 weak_ref.clone(),
3830 &worktree,
3831 local.http_client.clone(),
3832 local.fs.clone(),
3833 cx,
3834 );
3835
3836 servers.push((json_adapter, json_server, json_delegate));
3837 }
3838 }
3839 return Some(servers);
3840 })
3841 .ok()
3842 .flatten();
3843
3844 let Some(servers) = servers else {
3845 return;
3846 };
3847
3848 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
3849 let local = this.as_local()?;
3850 let toolchain_store = this.toolchain_store(cx);
3851 return Some((local.fs.clone(), toolchain_store));
3852 }) else {
3853 return;
3854 };
3855 for (adapter, server, delegate) in servers {
3856 adapter.clear_zed_json_schema_cache().await;
3857
3858 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
3859 adapter,
3860 fs.as_ref(),
3861 &delegate,
3862 toolchain_store.clone(),
3863 cx,
3864 )
3865 .await
3866 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
3867 .ok()
3868 else {
3869 continue;
3870 };
3871 server
3872 .notify::<lsp::notification::DidChangeConfiguration>(
3873 &lsp::DidChangeConfigurationParams {
3874 settings: json_workspace_config,
3875 },
3876 )
3877 .ok();
3878 }
3879 })
3880 .detach();
3881 }
3882
3883 pub(crate) fn register_buffer_with_language_servers(
3884 &mut self,
3885 buffer: &Entity<Buffer>,
3886 ignore_refcounts: bool,
3887 cx: &mut Context<Self>,
3888 ) -> OpenLspBufferHandle {
3889 let buffer_id = buffer.read(cx).remote_id();
3890 let handle = cx.new(|_| buffer.clone());
3891 if let Some(local) = self.as_local_mut() {
3892 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
3893 return handle;
3894 };
3895 if !file.is_local() {
3896 return handle;
3897 }
3898
3899 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
3900 if !ignore_refcounts {
3901 *refcount += 1;
3902 }
3903
3904 if ignore_refcounts || *refcount == 1 {
3905 local.register_buffer_with_language_servers(buffer, cx);
3906 }
3907 if !ignore_refcounts {
3908 cx.observe_release(&handle, move |this, buffer, cx| {
3909 let local = this.as_local_mut().unwrap();
3910 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
3911 debug_panic!("bad refcounting");
3912 return;
3913 };
3914
3915 *refcount -= 1;
3916 if *refcount == 0 {
3917 local.registered_buffers.remove(&buffer_id);
3918 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
3919 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
3920 }
3921 }
3922 })
3923 .detach();
3924 }
3925 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
3926 let buffer_id = buffer.read(cx).remote_id().to_proto();
3927 cx.background_spawn(async move {
3928 upstream_client
3929 .request(proto::RegisterBufferWithLanguageServers {
3930 project_id: upstream_project_id,
3931 buffer_id,
3932 })
3933 .await
3934 })
3935 .detach();
3936 } else {
3937 panic!("oops!");
3938 }
3939 handle
3940 }
3941
3942 fn maintain_buffer_languages(
3943 languages: Arc<LanguageRegistry>,
3944 cx: &mut Context<Self>,
3945 ) -> Task<()> {
3946 let mut subscription = languages.subscribe();
3947 let mut prev_reload_count = languages.reload_count();
3948 cx.spawn(async move |this, cx| {
3949 while let Some(()) = subscription.next().await {
3950 if let Some(this) = this.upgrade() {
3951 // If the language registry has been reloaded, then remove and
3952 // re-assign the languages on all open buffers.
3953 let reload_count = languages.reload_count();
3954 if reload_count > prev_reload_count {
3955 prev_reload_count = reload_count;
3956 this.update(cx, |this, cx| {
3957 this.buffer_store.clone().update(cx, |buffer_store, cx| {
3958 for buffer in buffer_store.buffers() {
3959 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
3960 {
3961 buffer
3962 .update(cx, |buffer, cx| buffer.set_language(None, cx));
3963 if let Some(local) = this.as_local_mut() {
3964 local.reset_buffer(&buffer, &f, cx);
3965
3966 if local
3967 .registered_buffers
3968 .contains_key(&buffer.read(cx).remote_id())
3969 {
3970 if let Some(file_url) =
3971 lsp::Url::from_file_path(&f.abs_path(cx))
3972 .log_err()
3973 {
3974 local.unregister_buffer_from_language_servers(
3975 &buffer, &file_url, cx,
3976 );
3977 }
3978 }
3979 }
3980 }
3981 }
3982 });
3983 })
3984 .ok();
3985 }
3986
3987 this.update(cx, |this, cx| {
3988 let mut plain_text_buffers = Vec::new();
3989 let mut buffers_with_unknown_injections = Vec::new();
3990 for handle in this.buffer_store.read(cx).buffers() {
3991 let buffer = handle.read(cx);
3992 if buffer.language().is_none()
3993 || buffer.language() == Some(&*language::PLAIN_TEXT)
3994 {
3995 plain_text_buffers.push(handle);
3996 } else if buffer.contains_unknown_injections() {
3997 buffers_with_unknown_injections.push(handle);
3998 }
3999 }
4000 for buffer in plain_text_buffers {
4001 this.detect_language_for_buffer(&buffer, cx);
4002 if let Some(local) = this.as_local_mut() {
4003 local.initialize_buffer(&buffer, cx);
4004 if local
4005 .registered_buffers
4006 .contains_key(&buffer.read(cx).remote_id())
4007 {
4008 local.register_buffer_with_language_servers(&buffer, cx);
4009 }
4010 }
4011 }
4012
4013 for buffer in buffers_with_unknown_injections {
4014 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4015 }
4016 })
4017 .ok();
4018 }
4019 }
4020 })
4021 }
4022
4023 fn detect_language_for_buffer(
4024 &mut self,
4025 buffer_handle: &Entity<Buffer>,
4026 cx: &mut Context<Self>,
4027 ) -> Option<language::AvailableLanguage> {
4028 // If the buffer has a language, set it and start the language server if we haven't already.
4029 let buffer = buffer_handle.read(cx);
4030 let file = buffer.file()?;
4031
4032 let content = buffer.as_rope();
4033 let available_language = self.languages.language_for_file(file, Some(content), cx);
4034 if let Some(available_language) = &available_language {
4035 if let Some(Ok(Ok(new_language))) = self
4036 .languages
4037 .load_language(available_language)
4038 .now_or_never()
4039 {
4040 self.set_language_for_buffer(buffer_handle, new_language, cx);
4041 }
4042 } else {
4043 cx.emit(LspStoreEvent::LanguageDetected {
4044 buffer: buffer_handle.clone(),
4045 new_language: None,
4046 });
4047 }
4048
4049 available_language
4050 }
4051
4052 pub(crate) fn set_language_for_buffer(
4053 &mut self,
4054 buffer_entity: &Entity<Buffer>,
4055 new_language: Arc<Language>,
4056 cx: &mut Context<Self>,
4057 ) {
4058 let buffer = buffer_entity.read(cx);
4059 let buffer_file = buffer.file().cloned();
4060 let buffer_id = buffer.remote_id();
4061 if let Some(local_store) = self.as_local_mut() {
4062 if local_store.registered_buffers.contains_key(&buffer_id) {
4063 if let Some(abs_path) =
4064 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4065 {
4066 if let Some(file_url) = lsp::Url::from_file_path(&abs_path).log_err() {
4067 local_store.unregister_buffer_from_language_servers(
4068 buffer_entity,
4069 &file_url,
4070 cx,
4071 );
4072 }
4073 }
4074 }
4075 }
4076 buffer_entity.update(cx, |buffer, cx| {
4077 if buffer.language().map_or(true, |old_language| {
4078 !Arc::ptr_eq(old_language, &new_language)
4079 }) {
4080 buffer.set_language(Some(new_language.clone()), cx);
4081 }
4082 });
4083
4084 let settings =
4085 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4086 let buffer_file = File::from_dyn(buffer_file.as_ref());
4087
4088 let worktree_id = if let Some(file) = buffer_file {
4089 let worktree = file.worktree.clone();
4090
4091 if let Some(local) = self.as_local_mut() {
4092 if local.registered_buffers.contains_key(&buffer_id) {
4093 local.register_buffer_with_language_servers(buffer_entity, cx);
4094 }
4095 }
4096 Some(worktree.read(cx).id())
4097 } else {
4098 None
4099 };
4100
4101 if settings.prettier.allowed {
4102 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4103 {
4104 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4105 if let Some(prettier_store) = prettier_store {
4106 prettier_store.update(cx, |prettier_store, cx| {
4107 prettier_store.install_default_prettier(
4108 worktree_id,
4109 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4110 cx,
4111 )
4112 })
4113 }
4114 }
4115 }
4116
4117 cx.emit(LspStoreEvent::LanguageDetected {
4118 buffer: buffer_entity.clone(),
4119 new_language: Some(new_language),
4120 })
4121 }
4122
4123 pub fn buffer_store(&self) -> Entity<BufferStore> {
4124 self.buffer_store.clone()
4125 }
4126
4127 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4128 self.active_entry = active_entry;
4129 }
4130
4131 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4132 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4133 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4134 for (path, summaries) in summaries {
4135 for (&server_id, summary) in summaries {
4136 client
4137 .send(proto::UpdateDiagnosticSummary {
4138 project_id: downstream_project_id,
4139 worktree_id: worktree.id().to_proto(),
4140 summary: Some(summary.to_proto(server_id, path)),
4141 })
4142 .log_err();
4143 }
4144 }
4145 }
4146 }
4147 }
4148
4149 pub fn request_lsp<R: LspCommand>(
4150 &mut self,
4151 buffer_handle: Entity<Buffer>,
4152 server: LanguageServerToQuery,
4153 request: R,
4154 cx: &mut Context<Self>,
4155 ) -> Task<Result<R::Response>>
4156 where
4157 <R::LspRequest as lsp::request::Request>::Result: Send,
4158 <R::LspRequest as lsp::request::Request>::Params: Send,
4159 {
4160 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4161 return self.send_lsp_proto_request(
4162 buffer_handle,
4163 upstream_client,
4164 upstream_project_id,
4165 request,
4166 cx,
4167 );
4168 }
4169
4170 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4171 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4172 local
4173 .language_servers_for_buffer(buffer, cx)
4174 .find(|(_, server)| {
4175 request.check_capabilities(server.adapter_server_capabilities())
4176 })
4177 .map(|(_, server)| server.clone())
4178 }),
4179 LanguageServerToQuery::Other(id) => self
4180 .language_server_for_local_buffer(buffer, id, cx)
4181 .and_then(|(_, server)| {
4182 request
4183 .check_capabilities(server.adapter_server_capabilities())
4184 .then(|| Arc::clone(server))
4185 }),
4186 }) else {
4187 return Task::ready(Ok(Default::default()));
4188 };
4189
4190 let buffer = buffer_handle.read(cx);
4191 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4192
4193 let Some(file) = file else {
4194 return Task::ready(Ok(Default::default()));
4195 };
4196
4197 let lsp_params = match request.to_lsp_params_or_response(
4198 &file.abs_path(cx),
4199 buffer,
4200 &language_server,
4201 cx,
4202 ) {
4203 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4204 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4205
4206 Err(err) => {
4207 let message = format!(
4208 "{} via {} failed: {}",
4209 request.display_name(),
4210 language_server.name(),
4211 err
4212 );
4213 log::warn!("{}", message);
4214 return Task::ready(Err(anyhow!(message)));
4215 }
4216 };
4217
4218 let status = request.status();
4219 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4220 return Task::ready(Ok(Default::default()));
4221 }
4222 return cx.spawn(async move |this, cx| {
4223 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4224
4225 let id = lsp_request.id();
4226 let _cleanup = if status.is_some() {
4227 cx.update(|cx| {
4228 this.update(cx, |this, cx| {
4229 this.on_lsp_work_start(
4230 language_server.server_id(),
4231 id.to_string(),
4232 LanguageServerProgress {
4233 is_disk_based_diagnostics_progress: false,
4234 is_cancellable: false,
4235 title: None,
4236 message: status.clone(),
4237 percentage: None,
4238 last_update_at: cx.background_executor().now(),
4239 },
4240 cx,
4241 );
4242 })
4243 })
4244 .log_err();
4245
4246 Some(defer(|| {
4247 cx.update(|cx| {
4248 this.update(cx, |this, cx| {
4249 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4250 })
4251 })
4252 .log_err();
4253 }))
4254 } else {
4255 None
4256 };
4257
4258 let result = lsp_request.await;
4259
4260 let response = result.map_err(|err| {
4261 let message = format!(
4262 "{} via {} failed: {}",
4263 request.display_name(),
4264 language_server.name(),
4265 err
4266 );
4267 log::warn!("{}", message);
4268 anyhow!(message)
4269 })?;
4270
4271 let response = request
4272 .response_from_lsp(
4273 response,
4274 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
4275 buffer_handle,
4276 language_server.server_id(),
4277 cx.clone(),
4278 )
4279 .await;
4280 response
4281 });
4282 }
4283
4284 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4285 let mut language_formatters_to_check = Vec::new();
4286 for buffer in self.buffer_store.read(cx).buffers() {
4287 let buffer = buffer.read(cx);
4288 let buffer_file = File::from_dyn(buffer.file());
4289 let buffer_language = buffer.language();
4290 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4291 if buffer_language.is_some() {
4292 language_formatters_to_check.push((
4293 buffer_file.map(|f| f.worktree_id(cx)),
4294 settings.into_owned(),
4295 ));
4296 }
4297 }
4298
4299 self.refresh_server_tree(cx);
4300
4301 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4302 prettier_store.update(cx, |prettier_store, cx| {
4303 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4304 })
4305 }
4306
4307 cx.notify();
4308 }
4309
4310 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4311 let buffer_store = self.buffer_store.clone();
4312 if let Some(local) = self.as_local_mut() {
4313 let mut adapters = BTreeMap::default();
4314 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4315 let get_adapter = {
4316 let languages = local.languages.clone();
4317 let environment = local.environment.clone();
4318 let weak = local.weak.clone();
4319 let worktree_store = local.worktree_store.clone();
4320 let http_client = local.http_client.clone();
4321 let fs = local.fs.clone();
4322 move |worktree_id, cx: &mut App| {
4323 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4324 Some(LocalLspAdapterDelegate::new(
4325 languages.clone(),
4326 &environment,
4327 weak.clone(),
4328 &worktree,
4329 http_client.clone(),
4330 fs.clone(),
4331 cx,
4332 ))
4333 }
4334 };
4335
4336 let mut rebase = lsp_tree.rebase();
4337 for buffer in buffer_store.read(cx).buffers().collect::<Vec<_>>() {
4338 let buffer = buffer.read(cx);
4339 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4340 continue;
4341 }
4342 if let Some((file, language)) = File::from_dyn(buffer.file())
4343 .cloned()
4344 .zip(buffer.language().map(|l| l.name()))
4345 {
4346 let worktree_id = file.worktree_id(cx);
4347 let Some(worktree) = local
4348 .worktree_store
4349 .read(cx)
4350 .worktree_for_id(worktree_id, cx)
4351 else {
4352 continue;
4353 };
4354 let path: Arc<Path> = file
4355 .path()
4356 .parent()
4357 .map(Arc::from)
4358 .unwrap_or_else(|| file.path().clone());
4359 let worktree_path = ProjectPath { worktree_id, path };
4360
4361 let Some(delegate) = adapters
4362 .entry(worktree_id)
4363 .or_insert_with(|| get_adapter(worktree_id, cx))
4364 .clone()
4365 else {
4366 continue;
4367 };
4368 let nodes = rebase.get(
4369 worktree_path,
4370 AdapterQuery::Language(&language),
4371 delegate.clone(),
4372 cx,
4373 );
4374 for node in nodes {
4375 node.server_id_or_init(
4376 |LaunchDisposition {
4377 server_name,
4378 attach,
4379 path,
4380 settings,
4381 }| match attach {
4382 language::Attach::InstancePerRoot => {
4383 // todo: handle instance per root proper.
4384 if let Some(server_ids) = local
4385 .language_server_ids
4386 .get(&(worktree_id, server_name.clone()))
4387 {
4388 server_ids.iter().cloned().next().unwrap()
4389 } else {
4390 local.start_language_server(
4391 &worktree,
4392 delegate.clone(),
4393 local
4394 .languages
4395 .lsp_adapters(&language)
4396 .into_iter()
4397 .find(|adapter| &adapter.name() == server_name)
4398 .expect("To find LSP adapter"),
4399 settings,
4400 cx,
4401 )
4402 }
4403 }
4404 language::Attach::Shared => {
4405 let uri = Url::from_file_path(
4406 worktree.read(cx).abs_path().join(&path.path),
4407 );
4408 let key = (worktree_id, server_name.clone());
4409 local.language_server_ids.remove(&key);
4410
4411 let server_id = local.start_language_server(
4412 &worktree,
4413 delegate.clone(),
4414 local
4415 .languages
4416 .lsp_adapters(&language)
4417 .into_iter()
4418 .find(|adapter| &adapter.name() == server_name)
4419 .expect("To find LSP adapter"),
4420 settings,
4421 cx,
4422 );
4423 if let Some(state) = local.language_servers.get(&server_id)
4424 {
4425 if let Ok(uri) = uri {
4426 state.add_workspace_folder(uri);
4427 };
4428 }
4429 server_id
4430 }
4431 },
4432 );
4433 }
4434 }
4435 }
4436 rebase.finish()
4437 });
4438 for (id, name) in to_stop {
4439 self.stop_local_language_server(id, name, cx).detach();
4440 }
4441 }
4442 }
4443
4444 pub fn apply_code_action(
4445 &self,
4446 buffer_handle: Entity<Buffer>,
4447 mut action: CodeAction,
4448 push_to_history: bool,
4449 cx: &mut Context<Self>,
4450 ) -> Task<Result<ProjectTransaction>> {
4451 if let Some((upstream_client, project_id)) = self.upstream_client() {
4452 let request = proto::ApplyCodeAction {
4453 project_id,
4454 buffer_id: buffer_handle.read(cx).remote_id().into(),
4455 action: Some(Self::serialize_code_action(&action)),
4456 };
4457 let buffer_store = self.buffer_store();
4458 cx.spawn(async move |_, cx| {
4459 let response = upstream_client
4460 .request(request)
4461 .await?
4462 .transaction
4463 .ok_or_else(|| anyhow!("missing transaction"))?;
4464
4465 buffer_store
4466 .update(cx, |buffer_store, cx| {
4467 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4468 })?
4469 .await
4470 })
4471 } else if self.mode.is_local() {
4472 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4473 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4474 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4475 }) else {
4476 return Task::ready(Ok(ProjectTransaction::default()));
4477 };
4478 cx.spawn(async move |this, cx| {
4479 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4480 .await
4481 .context("resolving a code action")?;
4482 if let Some(edit) = action.lsp_action.edit() {
4483 if edit.changes.is_some() || edit.document_changes.is_some() {
4484 return LocalLspStore::deserialize_workspace_edit(
4485 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
4486 edit.clone(),
4487 push_to_history,
4488 lsp_adapter.clone(),
4489 lang_server.clone(),
4490 cx,
4491 )
4492 .await;
4493 }
4494 }
4495
4496 if let Some(command) = action.lsp_action.command() {
4497 let server_capabilities = lang_server.capabilities();
4498 let available_commands = server_capabilities
4499 .execute_command_provider
4500 .as_ref()
4501 .map(|options| options.commands.as_slice())
4502 .unwrap_or_default();
4503 if available_commands.contains(&command.command) {
4504 this.update(cx, |this, _| {
4505 this.as_local_mut()
4506 .unwrap()
4507 .last_workspace_edits_by_language_server
4508 .remove(&lang_server.server_id());
4509 })?;
4510
4511 let result = lang_server
4512 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4513 command: command.command.clone(),
4514 arguments: command.arguments.clone().unwrap_or_default(),
4515 ..Default::default()
4516 })
4517 .await;
4518
4519 result?;
4520
4521 return this.update(cx, |this, _| {
4522 this.as_local_mut()
4523 .unwrap()
4524 .last_workspace_edits_by_language_server
4525 .remove(&lang_server.server_id())
4526 .unwrap_or_default()
4527 });
4528 } else {
4529 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4530 }
4531 }
4532
4533 Ok(ProjectTransaction::default())
4534 })
4535 } else {
4536 Task::ready(Err(anyhow!("no upstream client and not local")))
4537 }
4538 }
4539
4540 pub fn apply_code_action_kind(
4541 &mut self,
4542 buffers: HashSet<Entity<Buffer>>,
4543 kind: CodeActionKind,
4544 push_to_history: bool,
4545 cx: &mut Context<Self>,
4546 ) -> Task<anyhow::Result<ProjectTransaction>> {
4547 if let Some(_) = self.as_local() {
4548 cx.spawn(async move |lsp_store, cx| {
4549 let buffers = buffers.into_iter().collect::<Vec<_>>();
4550 let result = LocalLspStore::execute_code_action_kind_locally(
4551 lsp_store.clone(),
4552 buffers,
4553 kind,
4554 push_to_history,
4555 cx,
4556 )
4557 .await;
4558 lsp_store.update(cx, |lsp_store, _| {
4559 lsp_store.update_last_formatting_failure(&result);
4560 })?;
4561 result
4562 })
4563 } else if let Some((client, project_id)) = self.upstream_client() {
4564 let buffer_store = self.buffer_store();
4565 cx.spawn(async move |lsp_store, cx| {
4566 let result = client
4567 .request(proto::ApplyCodeActionKind {
4568 project_id,
4569 kind: kind.as_str().to_owned(),
4570 buffer_ids: buffers
4571 .iter()
4572 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
4573 .collect::<Result<_>>()?,
4574 })
4575 .await
4576 .and_then(|result| result.transaction.context("missing transaction"));
4577 lsp_store.update(cx, |lsp_store, _| {
4578 lsp_store.update_last_formatting_failure(&result);
4579 })?;
4580
4581 let transaction_response = result?;
4582 buffer_store
4583 .update(cx, |buffer_store, cx| {
4584 buffer_store.deserialize_project_transaction(
4585 transaction_response,
4586 push_to_history,
4587 cx,
4588 )
4589 })?
4590 .await
4591 })
4592 } else {
4593 Task::ready(Ok(ProjectTransaction::default()))
4594 }
4595 }
4596
4597 pub fn resolve_inlay_hint(
4598 &self,
4599 hint: InlayHint,
4600 buffer_handle: Entity<Buffer>,
4601 server_id: LanguageServerId,
4602 cx: &mut Context<Self>,
4603 ) -> Task<anyhow::Result<InlayHint>> {
4604 if let Some((upstream_client, project_id)) = self.upstream_client() {
4605 let request = proto::ResolveInlayHint {
4606 project_id,
4607 buffer_id: buffer_handle.read(cx).remote_id().into(),
4608 language_server_id: server_id.0 as u64,
4609 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4610 };
4611 cx.spawn(async move |_, _| {
4612 let response = upstream_client
4613 .request(request)
4614 .await
4615 .context("inlay hints proto request")?;
4616 match response.hint {
4617 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4618 .context("inlay hints proto resolve response conversion"),
4619 None => Ok(hint),
4620 }
4621 })
4622 } else {
4623 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4624 self.language_server_for_local_buffer(buffer, server_id, cx)
4625 .map(|(_, server)| server.clone())
4626 }) else {
4627 return Task::ready(Ok(hint));
4628 };
4629 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4630 return Task::ready(Ok(hint));
4631 }
4632 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4633 cx.spawn(async move |_, cx| {
4634 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4635 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4636 );
4637 let resolved_hint = resolve_task
4638 .await
4639 .context("inlay hint resolve LSP request")?;
4640 let resolved_hint = InlayHints::lsp_to_project_hint(
4641 resolved_hint,
4642 &buffer_handle,
4643 server_id,
4644 ResolveState::Resolved,
4645 false,
4646 cx,
4647 )
4648 .await?;
4649 Ok(resolved_hint)
4650 })
4651 }
4652 }
4653
4654 pub(crate) fn linked_edit(
4655 &mut self,
4656 buffer: &Entity<Buffer>,
4657 position: Anchor,
4658 cx: &mut Context<Self>,
4659 ) -> Task<Result<Vec<Range<Anchor>>>> {
4660 let snapshot = buffer.read(cx).snapshot();
4661 let scope = snapshot.language_scope_at(position);
4662 let Some(server_id) = self
4663 .as_local()
4664 .and_then(|local| {
4665 buffer.update(cx, |buffer, cx| {
4666 local
4667 .language_servers_for_buffer(buffer, cx)
4668 .filter(|(_, server)| {
4669 server
4670 .capabilities()
4671 .linked_editing_range_provider
4672 .is_some()
4673 })
4674 .filter(|(adapter, _)| {
4675 scope
4676 .as_ref()
4677 .map(|scope| scope.language_allowed(&adapter.name))
4678 .unwrap_or(true)
4679 })
4680 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
4681 .next()
4682 })
4683 })
4684 .or_else(|| {
4685 self.upstream_client()
4686 .is_some()
4687 .then_some(LanguageServerToQuery::FirstCapable)
4688 })
4689 .filter(|_| {
4690 maybe!({
4691 let language = buffer.read(cx).language_at(position)?;
4692 Some(
4693 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
4694 .linked_edits,
4695 )
4696 }) == Some(true)
4697 })
4698 else {
4699 return Task::ready(Ok(vec![]));
4700 };
4701
4702 self.request_lsp(
4703 buffer.clone(),
4704 server_id,
4705 LinkedEditingRange { position },
4706 cx,
4707 )
4708 }
4709
4710 fn apply_on_type_formatting(
4711 &mut self,
4712 buffer: Entity<Buffer>,
4713 position: Anchor,
4714 trigger: String,
4715 cx: &mut Context<Self>,
4716 ) -> Task<Result<Option<Transaction>>> {
4717 if let Some((client, project_id)) = self.upstream_client() {
4718 let request = proto::OnTypeFormatting {
4719 project_id,
4720 buffer_id: buffer.read(cx).remote_id().into(),
4721 position: Some(serialize_anchor(&position)),
4722 trigger,
4723 version: serialize_version(&buffer.read(cx).version()),
4724 };
4725 cx.spawn(async move |_, _| {
4726 client
4727 .request(request)
4728 .await?
4729 .transaction
4730 .map(language::proto::deserialize_transaction)
4731 .transpose()
4732 })
4733 } else if let Some(local) = self.as_local_mut() {
4734 let buffer_id = buffer.read(cx).remote_id();
4735 local.buffers_being_formatted.insert(buffer_id);
4736 cx.spawn(async move |this, cx| {
4737 let _cleanup = defer({
4738 let this = this.clone();
4739 let mut cx = cx.clone();
4740 move || {
4741 this.update(&mut cx, |this, _| {
4742 if let Some(local) = this.as_local_mut() {
4743 local.buffers_being_formatted.remove(&buffer_id);
4744 }
4745 })
4746 .ok();
4747 }
4748 });
4749
4750 buffer
4751 .update(cx, |buffer, _| {
4752 buffer.wait_for_edits(Some(position.timestamp))
4753 })?
4754 .await?;
4755 this.update(cx, |this, cx| {
4756 let position = position.to_point_utf16(buffer.read(cx));
4757 this.on_type_format(buffer, position, trigger, false, cx)
4758 })?
4759 .await
4760 })
4761 } else {
4762 Task::ready(Err(anyhow!("No upstream client or local language server")))
4763 }
4764 }
4765
4766 pub fn on_type_format<T: ToPointUtf16>(
4767 &mut self,
4768 buffer: Entity<Buffer>,
4769 position: T,
4770 trigger: String,
4771 push_to_history: bool,
4772 cx: &mut Context<Self>,
4773 ) -> Task<Result<Option<Transaction>>> {
4774 let position = position.to_point_utf16(buffer.read(cx));
4775 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
4776 }
4777
4778 fn on_type_format_impl(
4779 &mut self,
4780 buffer: Entity<Buffer>,
4781 position: PointUtf16,
4782 trigger: String,
4783 push_to_history: bool,
4784 cx: &mut Context<Self>,
4785 ) -> Task<Result<Option<Transaction>>> {
4786 let options = buffer.update(cx, |buffer, cx| {
4787 lsp_command::lsp_formatting_options(
4788 language_settings(
4789 buffer.language_at(position).map(|l| l.name()),
4790 buffer.file(),
4791 cx,
4792 )
4793 .as_ref(),
4794 )
4795 });
4796 self.request_lsp(
4797 buffer.clone(),
4798 LanguageServerToQuery::FirstCapable,
4799 OnTypeFormatting {
4800 position,
4801 trigger,
4802 options,
4803 push_to_history,
4804 },
4805 cx,
4806 )
4807 }
4808
4809 pub fn code_actions(
4810 &mut self,
4811 buffer_handle: &Entity<Buffer>,
4812 range: Range<Anchor>,
4813 kinds: Option<Vec<CodeActionKind>>,
4814 cx: &mut Context<Self>,
4815 ) -> Task<Result<Vec<CodeAction>>> {
4816 if let Some((upstream_client, project_id)) = self.upstream_client() {
4817 let request_task = upstream_client.request(proto::MultiLspQuery {
4818 buffer_id: buffer_handle.read(cx).remote_id().into(),
4819 version: serialize_version(&buffer_handle.read(cx).version()),
4820 project_id,
4821 strategy: Some(proto::multi_lsp_query::Strategy::All(
4822 proto::AllLanguageServers {},
4823 )),
4824 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
4825 GetCodeActions {
4826 range: range.clone(),
4827 kinds: kinds.clone(),
4828 }
4829 .to_proto(project_id, buffer_handle.read(cx)),
4830 )),
4831 });
4832 let buffer = buffer_handle.clone();
4833 cx.spawn(async move |weak_project, cx| {
4834 let Some(project) = weak_project.upgrade() else {
4835 return Ok(Vec::new());
4836 };
4837 let responses = request_task.await?.responses;
4838 let actions = join_all(
4839 responses
4840 .into_iter()
4841 .filter_map(|lsp_response| match lsp_response.response? {
4842 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
4843 Some(response)
4844 }
4845 unexpected => {
4846 debug_panic!("Unexpected response: {unexpected:?}");
4847 None
4848 }
4849 })
4850 .map(|code_actions_response| {
4851 GetCodeActions {
4852 range: range.clone(),
4853 kinds: kinds.clone(),
4854 }
4855 .response_from_proto(
4856 code_actions_response,
4857 project.clone(),
4858 buffer.clone(),
4859 cx.clone(),
4860 )
4861 }),
4862 )
4863 .await;
4864
4865 Ok(actions
4866 .into_iter()
4867 .collect::<Result<Vec<Vec<_>>>>()?
4868 .into_iter()
4869 .flatten()
4870 .collect())
4871 })
4872 } else {
4873 let all_actions_task = self.request_multiple_lsp_locally(
4874 buffer_handle,
4875 Some(range.start),
4876 GetCodeActions {
4877 range: range.clone(),
4878 kinds: kinds.clone(),
4879 },
4880 cx,
4881 );
4882 cx.spawn(async move |_, _| Ok(all_actions_task.await.into_iter().flatten().collect()))
4883 }
4884 }
4885
4886 pub fn code_lens(
4887 &mut self,
4888 buffer_handle: &Entity<Buffer>,
4889 cx: &mut Context<Self>,
4890 ) -> Task<Result<Vec<CodeAction>>> {
4891 if let Some((upstream_client, project_id)) = self.upstream_client() {
4892 let request_task = upstream_client.request(proto::MultiLspQuery {
4893 buffer_id: buffer_handle.read(cx).remote_id().into(),
4894 version: serialize_version(&buffer_handle.read(cx).version()),
4895 project_id,
4896 strategy: Some(proto::multi_lsp_query::Strategy::All(
4897 proto::AllLanguageServers {},
4898 )),
4899 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
4900 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
4901 )),
4902 });
4903 let buffer = buffer_handle.clone();
4904 cx.spawn(async move |weak_project, cx| {
4905 let Some(project) = weak_project.upgrade() else {
4906 return Ok(Vec::new());
4907 };
4908 let responses = request_task.await?.responses;
4909 let code_lens = join_all(
4910 responses
4911 .into_iter()
4912 .filter_map(|lsp_response| match lsp_response.response? {
4913 proto::lsp_response::Response::GetCodeLensResponse(response) => {
4914 Some(response)
4915 }
4916 unexpected => {
4917 debug_panic!("Unexpected response: {unexpected:?}");
4918 None
4919 }
4920 })
4921 .map(|code_lens_response| {
4922 GetCodeLens.response_from_proto(
4923 code_lens_response,
4924 project.clone(),
4925 buffer.clone(),
4926 cx.clone(),
4927 )
4928 }),
4929 )
4930 .await;
4931
4932 Ok(code_lens
4933 .into_iter()
4934 .collect::<Result<Vec<Vec<_>>>>()?
4935 .into_iter()
4936 .flatten()
4937 .collect())
4938 })
4939 } else {
4940 let code_lens_task =
4941 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
4942 cx.spawn(async move |_, _| Ok(code_lens_task.await.into_iter().flatten().collect()))
4943 }
4944 }
4945
4946 #[inline(never)]
4947 pub fn completions(
4948 &self,
4949 buffer: &Entity<Buffer>,
4950 position: PointUtf16,
4951 context: CompletionContext,
4952 cx: &mut Context<Self>,
4953 ) -> Task<Result<Option<Vec<Completion>>>> {
4954 let language_registry = self.languages.clone();
4955
4956 if let Some((upstream_client, project_id)) = self.upstream_client() {
4957 let task = self.send_lsp_proto_request(
4958 buffer.clone(),
4959 upstream_client,
4960 project_id,
4961 GetCompletions { position, context },
4962 cx,
4963 );
4964 let language = buffer.read(cx).language().cloned();
4965
4966 // In the future, we should provide project guests with the names of LSP adapters,
4967 // so that they can use the correct LSP adapter when computing labels. For now,
4968 // guests just use the first LSP adapter associated with the buffer's language.
4969 let lsp_adapter = language.as_ref().and_then(|language| {
4970 language_registry
4971 .lsp_adapters(&language.name())
4972 .first()
4973 .cloned()
4974 });
4975
4976 cx.foreground_executor().spawn(async move {
4977 let completions = task.await?;
4978 let mut result = Vec::new();
4979 populate_labels_for_completions(completions, language, lsp_adapter, &mut result)
4980 .await;
4981 Ok(Some(result))
4982 })
4983 } else if let Some(local) = self.as_local() {
4984 let snapshot = buffer.read(cx).snapshot();
4985 let offset = position.to_offset(&snapshot);
4986 let scope = snapshot.language_scope_at(offset);
4987 let language = snapshot.language().cloned();
4988 let completion_settings = language_settings(
4989 language.as_ref().map(|language| language.name()),
4990 buffer.read(cx).file(),
4991 cx,
4992 )
4993 .completions;
4994 if !completion_settings.lsp {
4995 return Task::ready(Ok(None));
4996 }
4997
4998 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
4999 local
5000 .language_servers_for_buffer(buffer, cx)
5001 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5002 .filter(|(adapter, _)| {
5003 scope
5004 .as_ref()
5005 .map(|scope| scope.language_allowed(&adapter.name))
5006 .unwrap_or(true)
5007 })
5008 .map(|(_, server)| server.server_id())
5009 .collect()
5010 });
5011
5012 let buffer = buffer.clone();
5013 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5014 let lsp_timeout = if lsp_timeout > 0 {
5015 Some(Duration::from_millis(lsp_timeout))
5016 } else {
5017 None
5018 };
5019 cx.spawn(async move |this, cx| {
5020 let mut tasks = Vec::with_capacity(server_ids.len());
5021 this.update(cx, |lsp_store, cx| {
5022 for server_id in server_ids {
5023 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5024 let lsp_timeout = lsp_timeout
5025 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5026 let mut timeout = cx.background_spawn(async move {
5027 match lsp_timeout {
5028 Some(lsp_timeout) => {
5029 lsp_timeout.await;
5030 true
5031 },
5032 None => false,
5033 }
5034 }).fuse();
5035 let mut lsp_request = lsp_store.request_lsp(
5036 buffer.clone(),
5037 LanguageServerToQuery::Other(server_id),
5038 GetCompletions {
5039 position,
5040 context: context.clone(),
5041 },
5042 cx,
5043 ).fuse();
5044 let new_task = cx.background_spawn(async move {
5045 select_biased! {
5046 response = lsp_request => anyhow::Ok(Some(response?)),
5047 timeout_happened = timeout => {
5048 if timeout_happened {
5049 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5050 Ok(None)
5051 } else {
5052 let completions = lsp_request.await?;
5053 Ok(Some(completions))
5054 }
5055 },
5056 }
5057 });
5058 tasks.push((lsp_adapter, new_task));
5059 }
5060 })?;
5061
5062 let mut has_completions_returned = false;
5063 let mut completions = Vec::new();
5064 for (lsp_adapter, task) in tasks {
5065 if let Ok(Some(new_completions)) = task.await {
5066 has_completions_returned = true;
5067 populate_labels_for_completions(
5068 new_completions,
5069 language.clone(),
5070 lsp_adapter,
5071 &mut completions,
5072 )
5073 .await;
5074 }
5075 }
5076 if has_completions_returned {
5077 Ok(Some(completions))
5078 } else {
5079 Ok(None)
5080 }
5081 })
5082 } else {
5083 Task::ready(Err(anyhow!("No upstream client or local language server")))
5084 }
5085 }
5086
5087 pub fn resolve_completions(
5088 &self,
5089 buffer: Entity<Buffer>,
5090 completion_indices: Vec<usize>,
5091 completions: Rc<RefCell<Box<[Completion]>>>,
5092 cx: &mut Context<Self>,
5093 ) -> Task<Result<bool>> {
5094 let client = self.upstream_client();
5095
5096 let buffer_id = buffer.read(cx).remote_id();
5097 let buffer_snapshot = buffer.read(cx).snapshot();
5098
5099 cx.spawn(async move |this, cx| {
5100 let mut did_resolve = false;
5101 if let Some((client, project_id)) = client {
5102 for completion_index in completion_indices {
5103 let server_id = {
5104 let completion = &completions.borrow()[completion_index];
5105 completion.source.server_id()
5106 };
5107 if let Some(server_id) = server_id {
5108 if Self::resolve_completion_remote(
5109 project_id,
5110 server_id,
5111 buffer_id,
5112 completions.clone(),
5113 completion_index,
5114 client.clone(),
5115 )
5116 .await
5117 .log_err()
5118 .is_some()
5119 {
5120 did_resolve = true;
5121 }
5122 } else {
5123 resolve_word_completion(
5124 &buffer_snapshot,
5125 &mut completions.borrow_mut()[completion_index],
5126 );
5127 }
5128 }
5129 } else {
5130 for completion_index in completion_indices {
5131 let server_id = {
5132 let completion = &completions.borrow()[completion_index];
5133 completion.source.server_id()
5134 };
5135 if let Some(server_id) = server_id {
5136 let server_and_adapter = this
5137 .read_with(cx, |lsp_store, _| {
5138 let server = lsp_store.language_server_for_id(server_id)?;
5139 let adapter =
5140 lsp_store.language_server_adapter_for_id(server.server_id())?;
5141 Some((server, adapter))
5142 })
5143 .ok()
5144 .flatten();
5145 let Some((server, adapter)) = server_and_adapter else {
5146 continue;
5147 };
5148
5149 let resolved = Self::resolve_completion_local(
5150 server,
5151 &buffer_snapshot,
5152 completions.clone(),
5153 completion_index,
5154 )
5155 .await
5156 .log_err()
5157 .is_some();
5158 if resolved {
5159 Self::regenerate_completion_labels(
5160 adapter,
5161 &buffer_snapshot,
5162 completions.clone(),
5163 completion_index,
5164 )
5165 .await
5166 .log_err();
5167 did_resolve = true;
5168 }
5169 } else {
5170 resolve_word_completion(
5171 &buffer_snapshot,
5172 &mut completions.borrow_mut()[completion_index],
5173 );
5174 }
5175 }
5176 }
5177
5178 Ok(did_resolve)
5179 })
5180 }
5181
5182 async fn resolve_completion_local(
5183 server: Arc<lsp::LanguageServer>,
5184 snapshot: &BufferSnapshot,
5185 completions: Rc<RefCell<Box<[Completion]>>>,
5186 completion_index: usize,
5187 ) -> Result<()> {
5188 let server_id = server.server_id();
5189 let can_resolve = server
5190 .capabilities()
5191 .completion_provider
5192 .as_ref()
5193 .and_then(|options| options.resolve_provider)
5194 .unwrap_or(false);
5195 if !can_resolve {
5196 return Ok(());
5197 }
5198
5199 let request = {
5200 let completion = &completions.borrow()[completion_index];
5201 match &completion.source {
5202 CompletionSource::Lsp {
5203 lsp_completion,
5204 resolved,
5205 server_id: completion_server_id,
5206 ..
5207 } => {
5208 if *resolved {
5209 return Ok(());
5210 }
5211 anyhow::ensure!(
5212 server_id == *completion_server_id,
5213 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5214 );
5215 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5216 }
5217 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5218 return Ok(());
5219 }
5220 }
5221 };
5222 let resolved_completion = request.await?;
5223
5224 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5225 // Technically we don't have to parse the whole `text_edit`, since the only
5226 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5227 // is `typescript-language-server` and they only update `text_edit.new_text`.
5228 // But we should not rely on that.
5229 let edit = parse_completion_text_edit(text_edit, snapshot);
5230
5231 if let Some((old_range, mut new_text)) = edit {
5232 LineEnding::normalize(&mut new_text);
5233
5234 let mut completions = completions.borrow_mut();
5235 let completion = &mut completions[completion_index];
5236
5237 completion.new_text = new_text;
5238 completion.old_range = old_range;
5239 }
5240 }
5241
5242 let mut completions = completions.borrow_mut();
5243 let completion = &mut completions[completion_index];
5244 if let CompletionSource::Lsp {
5245 lsp_completion,
5246 resolved,
5247 server_id: completion_server_id,
5248 ..
5249 } = &mut completion.source
5250 {
5251 if *resolved {
5252 return Ok(());
5253 }
5254 anyhow::ensure!(
5255 server_id == *completion_server_id,
5256 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5257 );
5258 *lsp_completion = Box::new(resolved_completion);
5259 *resolved = true;
5260 }
5261 Ok(())
5262 }
5263
5264 async fn regenerate_completion_labels(
5265 adapter: Arc<CachedLspAdapter>,
5266 snapshot: &BufferSnapshot,
5267 completions: Rc<RefCell<Box<[Completion]>>>,
5268 completion_index: usize,
5269 ) -> Result<()> {
5270 let completion_item = completions.borrow()[completion_index]
5271 .source
5272 .lsp_completion(true)
5273 .map(Cow::into_owned);
5274 if let Some(lsp_documentation) = completion_item
5275 .as_ref()
5276 .and_then(|completion_item| completion_item.documentation.clone())
5277 {
5278 let mut completions = completions.borrow_mut();
5279 let completion = &mut completions[completion_index];
5280 completion.documentation = Some(lsp_documentation.into());
5281 } else {
5282 let mut completions = completions.borrow_mut();
5283 let completion = &mut completions[completion_index];
5284 completion.documentation = Some(CompletionDocumentation::Undocumented);
5285 }
5286
5287 let mut new_label = match completion_item {
5288 Some(completion_item) => {
5289 // 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
5290 // So we have to update the label here anyway...
5291 let language = snapshot.language();
5292 match language {
5293 Some(language) => {
5294 adapter
5295 .labels_for_completions(&[completion_item.clone()], language)
5296 .await?
5297 }
5298 None => Vec::new(),
5299 }
5300 .pop()
5301 .flatten()
5302 .unwrap_or_else(|| {
5303 CodeLabel::fallback_for_completion(
5304 &completion_item,
5305 language.map(|language| language.as_ref()),
5306 )
5307 })
5308 }
5309 None => CodeLabel::plain(
5310 completions.borrow()[completion_index].new_text.clone(),
5311 None,
5312 ),
5313 };
5314 ensure_uniform_list_compatible_label(&mut new_label);
5315
5316 let mut completions = completions.borrow_mut();
5317 let completion = &mut completions[completion_index];
5318 if completion.label.filter_text() == new_label.filter_text() {
5319 completion.label = new_label;
5320 } else {
5321 log::error!(
5322 "Resolved completion changed display label from {} to {}. \
5323 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5324 completion.label.text(),
5325 new_label.text(),
5326 completion.label.filter_text(),
5327 new_label.filter_text()
5328 );
5329 }
5330
5331 Ok(())
5332 }
5333
5334 async fn resolve_completion_remote(
5335 project_id: u64,
5336 server_id: LanguageServerId,
5337 buffer_id: BufferId,
5338 completions: Rc<RefCell<Box<[Completion]>>>,
5339 completion_index: usize,
5340 client: AnyProtoClient,
5341 ) -> Result<()> {
5342 let lsp_completion = {
5343 let completion = &completions.borrow()[completion_index];
5344 match &completion.source {
5345 CompletionSource::Lsp {
5346 lsp_completion,
5347 resolved,
5348 server_id: completion_server_id,
5349 ..
5350 } => {
5351 anyhow::ensure!(
5352 server_id == *completion_server_id,
5353 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5354 );
5355 if *resolved {
5356 return Ok(());
5357 }
5358 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5359 }
5360 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5361 return Ok(());
5362 }
5363 }
5364 };
5365 let request = proto::ResolveCompletionDocumentation {
5366 project_id,
5367 language_server_id: server_id.0 as u64,
5368 lsp_completion,
5369 buffer_id: buffer_id.into(),
5370 };
5371
5372 let response = client
5373 .request(request)
5374 .await
5375 .context("completion documentation resolve proto request")?;
5376 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5377
5378 let documentation = if response.documentation.is_empty() {
5379 CompletionDocumentation::Undocumented
5380 } else if response.documentation_is_markdown {
5381 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5382 } else if response.documentation.lines().count() <= 1 {
5383 CompletionDocumentation::SingleLine(response.documentation.into())
5384 } else {
5385 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5386 };
5387
5388 let mut completions = completions.borrow_mut();
5389 let completion = &mut completions[completion_index];
5390 completion.documentation = Some(documentation);
5391 if let CompletionSource::Lsp {
5392 lsp_completion,
5393 resolved,
5394 server_id: completion_server_id,
5395 lsp_defaults: _,
5396 } = &mut completion.source
5397 {
5398 if *resolved {
5399 return Ok(());
5400 }
5401 anyhow::ensure!(
5402 server_id == *completion_server_id,
5403 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5404 );
5405 *lsp_completion = Box::new(resolved_lsp_completion);
5406 *resolved = true;
5407 }
5408
5409 let old_range = response
5410 .old_start
5411 .and_then(deserialize_anchor)
5412 .zip(response.old_end.and_then(deserialize_anchor));
5413 if let Some((old_start, old_end)) = old_range {
5414 if !response.new_text.is_empty() {
5415 completion.new_text = response.new_text;
5416 completion.old_range = old_start..old_end;
5417 }
5418 }
5419
5420 Ok(())
5421 }
5422
5423 pub fn apply_additional_edits_for_completion(
5424 &self,
5425 buffer_handle: Entity<Buffer>,
5426 completions: Rc<RefCell<Box<[Completion]>>>,
5427 completion_index: usize,
5428 push_to_history: bool,
5429 cx: &mut Context<Self>,
5430 ) -> Task<Result<Option<Transaction>>> {
5431 if let Some((client, project_id)) = self.upstream_client() {
5432 let buffer = buffer_handle.read(cx);
5433 let buffer_id = buffer.remote_id();
5434 cx.spawn(async move |_, cx| {
5435 let request = {
5436 let completion = completions.borrow()[completion_index].clone();
5437 proto::ApplyCompletionAdditionalEdits {
5438 project_id,
5439 buffer_id: buffer_id.into(),
5440 completion: Some(Self::serialize_completion(&CoreCompletion {
5441 old_range: completion.old_range,
5442 new_text: completion.new_text,
5443 source: completion.source,
5444 })),
5445 }
5446 };
5447
5448 if let Some(transaction) = client.request(request).await?.transaction {
5449 let transaction = language::proto::deserialize_transaction(transaction)?;
5450 buffer_handle
5451 .update(cx, |buffer, _| {
5452 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5453 })?
5454 .await?;
5455 if push_to_history {
5456 buffer_handle.update(cx, |buffer, _| {
5457 buffer.push_transaction(transaction.clone(), Instant::now());
5458 })?;
5459 }
5460 Ok(Some(transaction))
5461 } else {
5462 Ok(None)
5463 }
5464 })
5465 } else {
5466 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5467 let completion = &completions.borrow()[completion_index];
5468 let server_id = completion.source.server_id()?;
5469 Some(
5470 self.language_server_for_local_buffer(buffer, server_id, cx)?
5471 .1
5472 .clone(),
5473 )
5474 }) else {
5475 return Task::ready(Ok(None));
5476 };
5477 let snapshot = buffer_handle.read(&cx).snapshot();
5478
5479 cx.spawn(async move |this, cx| {
5480 Self::resolve_completion_local(
5481 server.clone(),
5482 &snapshot,
5483 completions.clone(),
5484 completion_index,
5485 )
5486 .await
5487 .context("resolving completion")?;
5488 let completion = completions.borrow()[completion_index].clone();
5489 let additional_text_edits = completion
5490 .source
5491 .lsp_completion(true)
5492 .as_ref()
5493 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5494 if let Some(edits) = additional_text_edits {
5495 let edits = this
5496 .update(cx, |this, cx| {
5497 this.as_local_mut().unwrap().edits_from_lsp(
5498 &buffer_handle,
5499 edits,
5500 server.server_id(),
5501 None,
5502 cx,
5503 )
5504 })?
5505 .await?;
5506
5507 buffer_handle.update(cx, |buffer, cx| {
5508 buffer.finalize_last_transaction();
5509 buffer.start_transaction();
5510
5511 for (range, text) in edits {
5512 let primary = &completion.old_range;
5513 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5514 && primary.end.cmp(&range.start, buffer).is_ge();
5515 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5516 && range.end.cmp(&primary.end, buffer).is_ge();
5517
5518 //Skip additional edits which overlap with the primary completion edit
5519 //https://github.com/zed-industries/zed/pull/1871
5520 if !start_within && !end_within {
5521 buffer.edit([(range, text)], None, cx);
5522 }
5523 }
5524
5525 let transaction = if buffer.end_transaction(cx).is_some() {
5526 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5527 if !push_to_history {
5528 buffer.forget_transaction(transaction.id);
5529 }
5530 Some(transaction)
5531 } else {
5532 None
5533 };
5534 Ok(transaction)
5535 })?
5536 } else {
5537 Ok(None)
5538 }
5539 })
5540 }
5541 }
5542
5543 pub fn inlay_hints(
5544 &mut self,
5545 buffer_handle: Entity<Buffer>,
5546 range: Range<Anchor>,
5547 cx: &mut Context<Self>,
5548 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5549 let buffer = buffer_handle.read(cx);
5550 let range_start = range.start;
5551 let range_end = range.end;
5552 let buffer_id = buffer.remote_id().into();
5553 let lsp_request = InlayHints { range };
5554
5555 if let Some((client, project_id)) = self.upstream_client() {
5556 let request = proto::InlayHints {
5557 project_id,
5558 buffer_id,
5559 start: Some(serialize_anchor(&range_start)),
5560 end: Some(serialize_anchor(&range_end)),
5561 version: serialize_version(&buffer_handle.read(cx).version()),
5562 };
5563 cx.spawn(async move |project, cx| {
5564 let response = client
5565 .request(request)
5566 .await
5567 .context("inlay hints proto request")?;
5568 LspCommand::response_from_proto(
5569 lsp_request,
5570 response,
5571 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5572 buffer_handle.clone(),
5573 cx.clone(),
5574 )
5575 .await
5576 .context("inlay hints proto response conversion")
5577 })
5578 } else {
5579 let lsp_request_task = self.request_lsp(
5580 buffer_handle.clone(),
5581 LanguageServerToQuery::FirstCapable,
5582 lsp_request,
5583 cx,
5584 );
5585 cx.spawn(async move |_, cx| {
5586 buffer_handle
5587 .update(cx, |buffer, _| {
5588 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5589 })?
5590 .await
5591 .context("waiting for inlay hint request range edits")?;
5592 lsp_request_task.await.context("inlay hints LSP request")
5593 })
5594 }
5595 }
5596
5597 pub fn signature_help<T: ToPointUtf16>(
5598 &mut self,
5599 buffer: &Entity<Buffer>,
5600 position: T,
5601 cx: &mut Context<Self>,
5602 ) -> Task<Vec<SignatureHelp>> {
5603 let position = position.to_point_utf16(buffer.read(cx));
5604
5605 if let Some((client, upstream_project_id)) = self.upstream_client() {
5606 let request_task = client.request(proto::MultiLspQuery {
5607 buffer_id: buffer.read(cx).remote_id().into(),
5608 version: serialize_version(&buffer.read(cx).version()),
5609 project_id: upstream_project_id,
5610 strategy: Some(proto::multi_lsp_query::Strategy::All(
5611 proto::AllLanguageServers {},
5612 )),
5613 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
5614 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
5615 )),
5616 });
5617 let buffer = buffer.clone();
5618 cx.spawn(async move |weak_project, cx| {
5619 let Some(project) = weak_project.upgrade() else {
5620 return Vec::new();
5621 };
5622 join_all(
5623 request_task
5624 .await
5625 .log_err()
5626 .map(|response| response.responses)
5627 .unwrap_or_default()
5628 .into_iter()
5629 .filter_map(|lsp_response| match lsp_response.response? {
5630 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
5631 Some(response)
5632 }
5633 unexpected => {
5634 debug_panic!("Unexpected response: {unexpected:?}");
5635 None
5636 }
5637 })
5638 .map(|signature_response| {
5639 let response = GetSignatureHelp { position }.response_from_proto(
5640 signature_response,
5641 project.clone(),
5642 buffer.clone(),
5643 cx.clone(),
5644 );
5645 async move { response.await.log_err().flatten() }
5646 }),
5647 )
5648 .await
5649 .into_iter()
5650 .flatten()
5651 .collect()
5652 })
5653 } else {
5654 let all_actions_task = self.request_multiple_lsp_locally(
5655 buffer,
5656 Some(position),
5657 GetSignatureHelp { position },
5658 cx,
5659 );
5660 cx.spawn(async move |_, _| {
5661 all_actions_task
5662 .await
5663 .into_iter()
5664 .flatten()
5665 .filter(|help| !help.label.is_empty())
5666 .collect::<Vec<_>>()
5667 })
5668 }
5669 }
5670
5671 pub fn hover(
5672 &mut self,
5673 buffer: &Entity<Buffer>,
5674 position: PointUtf16,
5675 cx: &mut Context<Self>,
5676 ) -> Task<Vec<Hover>> {
5677 if let Some((client, upstream_project_id)) = self.upstream_client() {
5678 let request_task = client.request(proto::MultiLspQuery {
5679 buffer_id: buffer.read(cx).remote_id().into(),
5680 version: serialize_version(&buffer.read(cx).version()),
5681 project_id: upstream_project_id,
5682 strategy: Some(proto::multi_lsp_query::Strategy::All(
5683 proto::AllLanguageServers {},
5684 )),
5685 request: Some(proto::multi_lsp_query::Request::GetHover(
5686 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
5687 )),
5688 });
5689 let buffer = buffer.clone();
5690 cx.spawn(async move |weak_project, cx| {
5691 let Some(project) = weak_project.upgrade() else {
5692 return Vec::new();
5693 };
5694 join_all(
5695 request_task
5696 .await
5697 .log_err()
5698 .map(|response| response.responses)
5699 .unwrap_or_default()
5700 .into_iter()
5701 .filter_map(|lsp_response| match lsp_response.response? {
5702 proto::lsp_response::Response::GetHoverResponse(response) => {
5703 Some(response)
5704 }
5705 unexpected => {
5706 debug_panic!("Unexpected response: {unexpected:?}");
5707 None
5708 }
5709 })
5710 .map(|hover_response| {
5711 let response = GetHover { position }.response_from_proto(
5712 hover_response,
5713 project.clone(),
5714 buffer.clone(),
5715 cx.clone(),
5716 );
5717 async move {
5718 response
5719 .await
5720 .log_err()
5721 .flatten()
5722 .and_then(remove_empty_hover_blocks)
5723 }
5724 }),
5725 )
5726 .await
5727 .into_iter()
5728 .flatten()
5729 .collect()
5730 })
5731 } else {
5732 let all_actions_task = self.request_multiple_lsp_locally(
5733 buffer,
5734 Some(position),
5735 GetHover { position },
5736 cx,
5737 );
5738 cx.spawn(async move |_, _| {
5739 all_actions_task
5740 .await
5741 .into_iter()
5742 .filter_map(|hover| remove_empty_hover_blocks(hover?))
5743 .collect::<Vec<Hover>>()
5744 })
5745 }
5746 }
5747
5748 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
5749 let language_registry = self.languages.clone();
5750
5751 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
5752 let request = upstream_client.request(proto::GetProjectSymbols {
5753 project_id: *project_id,
5754 query: query.to_string(),
5755 });
5756 cx.foreground_executor().spawn(async move {
5757 let response = request.await?;
5758 let mut symbols = Vec::new();
5759 let core_symbols = response
5760 .symbols
5761 .into_iter()
5762 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
5763 .collect::<Vec<_>>();
5764 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
5765 .await;
5766 Ok(symbols)
5767 })
5768 } else if let Some(local) = self.as_local() {
5769 struct WorkspaceSymbolsResult {
5770 server_id: LanguageServerId,
5771 lsp_adapter: Arc<CachedLspAdapter>,
5772 worktree: WeakEntity<Worktree>,
5773 worktree_abs_path: Arc<Path>,
5774 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
5775 }
5776
5777 let mut requests = Vec::new();
5778 let mut requested_servers = BTreeSet::new();
5779 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
5780 let Some(worktree_handle) = self
5781 .worktree_store
5782 .read(cx)
5783 .worktree_for_id(*worktree_id, cx)
5784 else {
5785 continue;
5786 };
5787 let worktree = worktree_handle.read(cx);
5788 if !worktree.is_visible() {
5789 continue;
5790 }
5791
5792 let mut servers_to_query = server_ids
5793 .difference(&requested_servers)
5794 .cloned()
5795 .collect::<BTreeSet<_>>();
5796 for server_id in &servers_to_query {
5797 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
5798 Some(LanguageServerState::Running {
5799 adapter, server, ..
5800 }) => (adapter.clone(), server),
5801
5802 _ => continue 'next_server,
5803 };
5804 let supports_workspace_symbol_request =
5805 match server.capabilities().workspace_symbol_provider {
5806 Some(OneOf::Left(supported)) => supported,
5807 Some(OneOf::Right(_)) => true,
5808 None => false,
5809 };
5810 if !supports_workspace_symbol_request {
5811 continue 'next_server;
5812 }
5813 let worktree_abs_path = worktree.abs_path().clone();
5814 let worktree_handle = worktree_handle.clone();
5815 let server_id = server.server_id();
5816 requests.push(
5817 server
5818 .request::<lsp::request::WorkspaceSymbolRequest>(
5819 lsp::WorkspaceSymbolParams {
5820 query: query.to_string(),
5821 ..Default::default()
5822 },
5823 )
5824 .log_err()
5825 .map(move |response| {
5826 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
5827 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
5828 flat_responses.into_iter().map(|lsp_symbol| {
5829 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
5830 }).collect::<Vec<_>>()
5831 }
5832 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
5833 nested_responses.into_iter().filter_map(|lsp_symbol| {
5834 let location = match lsp_symbol.location {
5835 OneOf::Left(location) => location,
5836 OneOf::Right(_) => {
5837 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
5838 return None
5839 }
5840 };
5841 Some((lsp_symbol.name, lsp_symbol.kind, location))
5842 }).collect::<Vec<_>>()
5843 }
5844 }).unwrap_or_default();
5845
5846 WorkspaceSymbolsResult {
5847 server_id,
5848 lsp_adapter,
5849 worktree: worktree_handle.downgrade(),
5850 worktree_abs_path,
5851 lsp_symbols,
5852 }
5853 }),
5854 );
5855 }
5856 requested_servers.append(&mut servers_to_query);
5857 }
5858
5859 cx.spawn(async move |this, cx| {
5860 let responses = futures::future::join_all(requests).await;
5861 let this = match this.upgrade() {
5862 Some(this) => this,
5863 None => return Ok(Vec::new()),
5864 };
5865
5866 let mut symbols = Vec::new();
5867 for result in responses {
5868 let core_symbols = this.update(cx, |this, cx| {
5869 result
5870 .lsp_symbols
5871 .into_iter()
5872 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
5873 let abs_path = symbol_location.uri.to_file_path().ok()?;
5874 let source_worktree = result.worktree.upgrade()?;
5875 let source_worktree_id = source_worktree.read(cx).id();
5876
5877 let path;
5878 let worktree;
5879 if let Some((tree, rel_path)) =
5880 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
5881 {
5882 worktree = tree;
5883 path = rel_path;
5884 } else {
5885 worktree = source_worktree.clone();
5886 path = relativize_path(&result.worktree_abs_path, &abs_path);
5887 }
5888
5889 let worktree_id = worktree.read(cx).id();
5890 let project_path = ProjectPath {
5891 worktree_id,
5892 path: path.into(),
5893 };
5894 let signature = this.symbol_signature(&project_path);
5895 Some(CoreSymbol {
5896 source_language_server_id: result.server_id,
5897 language_server_name: result.lsp_adapter.name.clone(),
5898 source_worktree_id,
5899 path: project_path,
5900 kind: symbol_kind,
5901 name: symbol_name,
5902 range: range_from_lsp(symbol_location.range),
5903 signature,
5904 })
5905 })
5906 .collect()
5907 })?;
5908
5909 populate_labels_for_symbols(
5910 core_symbols,
5911 &language_registry,
5912 Some(result.lsp_adapter),
5913 &mut symbols,
5914 )
5915 .await;
5916 }
5917
5918 Ok(symbols)
5919 })
5920 } else {
5921 Task::ready(Err(anyhow!("No upstream client or local language server")))
5922 }
5923 }
5924
5925 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
5926 let mut summary = DiagnosticSummary::default();
5927 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
5928 summary.error_count += path_summary.error_count;
5929 summary.warning_count += path_summary.warning_count;
5930 }
5931 summary
5932 }
5933
5934 pub fn diagnostic_summaries<'a>(
5935 &'a self,
5936 include_ignored: bool,
5937 cx: &'a App,
5938 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5939 self.worktree_store
5940 .read(cx)
5941 .visible_worktrees(cx)
5942 .filter_map(|worktree| {
5943 let worktree = worktree.read(cx);
5944 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
5945 })
5946 .flat_map(move |(worktree, summaries)| {
5947 let worktree_id = worktree.id();
5948 summaries
5949 .iter()
5950 .filter(move |(path, _)| {
5951 include_ignored
5952 || worktree
5953 .entry_for_path(path.as_ref())
5954 .map_or(false, |entry| !entry.is_ignored)
5955 })
5956 .flat_map(move |(path, summaries)| {
5957 summaries.iter().map(move |(server_id, summary)| {
5958 (
5959 ProjectPath {
5960 worktree_id,
5961 path: path.clone(),
5962 },
5963 *server_id,
5964 *summary,
5965 )
5966 })
5967 })
5968 })
5969 }
5970
5971 pub fn on_buffer_edited(
5972 &mut self,
5973 buffer: Entity<Buffer>,
5974 cx: &mut Context<Self>,
5975 ) -> Option<()> {
5976 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
5977 Some(
5978 self.as_local()?
5979 .language_servers_for_buffer(buffer, cx)
5980 .map(|i| i.1.clone())
5981 .collect(),
5982 )
5983 })?;
5984
5985 let buffer = buffer.read(cx);
5986 let file = File::from_dyn(buffer.file())?;
5987 let abs_path = file.as_local()?.abs_path(cx);
5988 let uri = lsp::Url::from_file_path(abs_path).unwrap();
5989 let next_snapshot = buffer.text_snapshot();
5990 for language_server in language_servers {
5991 let language_server = language_server.clone();
5992
5993 let buffer_snapshots = self
5994 .as_local_mut()
5995 .unwrap()
5996 .buffer_snapshots
5997 .get_mut(&buffer.remote_id())
5998 .and_then(|m| m.get_mut(&language_server.server_id()))?;
5999 let previous_snapshot = buffer_snapshots.last()?;
6000
6001 let build_incremental_change = || {
6002 buffer
6003 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6004 .map(|edit| {
6005 let edit_start = edit.new.start.0;
6006 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6007 let new_text = next_snapshot
6008 .text_for_range(edit.new.start.1..edit.new.end.1)
6009 .collect();
6010 lsp::TextDocumentContentChangeEvent {
6011 range: Some(lsp::Range::new(
6012 point_to_lsp(edit_start),
6013 point_to_lsp(edit_end),
6014 )),
6015 range_length: None,
6016 text: new_text,
6017 }
6018 })
6019 .collect()
6020 };
6021
6022 let document_sync_kind = language_server
6023 .capabilities()
6024 .text_document_sync
6025 .as_ref()
6026 .and_then(|sync| match sync {
6027 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6028 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6029 });
6030
6031 let content_changes: Vec<_> = match document_sync_kind {
6032 Some(lsp::TextDocumentSyncKind::FULL) => {
6033 vec![lsp::TextDocumentContentChangeEvent {
6034 range: None,
6035 range_length: None,
6036 text: next_snapshot.text(),
6037 }]
6038 }
6039 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6040 _ => {
6041 #[cfg(any(test, feature = "test-support"))]
6042 {
6043 build_incremental_change()
6044 }
6045
6046 #[cfg(not(any(test, feature = "test-support")))]
6047 {
6048 continue;
6049 }
6050 }
6051 };
6052
6053 let next_version = previous_snapshot.version + 1;
6054 buffer_snapshots.push(LspBufferSnapshot {
6055 version: next_version,
6056 snapshot: next_snapshot.clone(),
6057 });
6058
6059 language_server
6060 .notify::<lsp::notification::DidChangeTextDocument>(
6061 &lsp::DidChangeTextDocumentParams {
6062 text_document: lsp::VersionedTextDocumentIdentifier::new(
6063 uri.clone(),
6064 next_version,
6065 ),
6066 content_changes,
6067 },
6068 )
6069 .log_err();
6070 }
6071
6072 None
6073 }
6074
6075 pub fn on_buffer_saved(
6076 &mut self,
6077 buffer: Entity<Buffer>,
6078 cx: &mut Context<Self>,
6079 ) -> Option<()> {
6080 let file = File::from_dyn(buffer.read(cx).file())?;
6081 let worktree_id = file.worktree_id(cx);
6082 let abs_path = file.as_local()?.abs_path(cx);
6083 let text_document = lsp::TextDocumentIdentifier {
6084 uri: lsp::Url::from_file_path(abs_path).log_err()?,
6085 };
6086 let local = self.as_local()?;
6087
6088 for server in local.language_servers_for_worktree(worktree_id) {
6089 if let Some(include_text) = include_text(server.as_ref()) {
6090 let text = if include_text {
6091 Some(buffer.read(cx).text())
6092 } else {
6093 None
6094 };
6095 server
6096 .notify::<lsp::notification::DidSaveTextDocument>(
6097 &lsp::DidSaveTextDocumentParams {
6098 text_document: text_document.clone(),
6099 text,
6100 },
6101 )
6102 .log_err();
6103 }
6104 }
6105
6106 let language_servers = buffer.update(cx, |buffer, cx| {
6107 local.language_server_ids_for_buffer(buffer, cx)
6108 });
6109 for language_server_id in language_servers {
6110 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6111 }
6112
6113 None
6114 }
6115
6116 pub(crate) async fn refresh_workspace_configurations(
6117 this: &WeakEntity<Self>,
6118 fs: Arc<dyn Fs>,
6119 cx: &mut AsyncApp,
6120 ) {
6121 maybe!(async move {
6122 let servers = this
6123 .update(cx, |this, cx| {
6124 let Some(local) = this.as_local() else {
6125 return Vec::default();
6126 };
6127 local
6128 .language_server_ids
6129 .iter()
6130 .flat_map(|((worktree_id, _), server_ids)| {
6131 let worktree = this
6132 .worktree_store
6133 .read(cx)
6134 .worktree_for_id(*worktree_id, cx);
6135 let delegate = worktree.map(|worktree| {
6136 LocalLspAdapterDelegate::new(
6137 local.languages.clone(),
6138 &local.environment,
6139 cx.weak_entity(),
6140 &worktree,
6141 local.http_client.clone(),
6142 local.fs.clone(),
6143 cx,
6144 )
6145 });
6146
6147 server_ids.iter().filter_map(move |server_id| {
6148 let states = local.language_servers.get(server_id)?;
6149
6150 match states {
6151 LanguageServerState::Starting { .. } => None,
6152 LanguageServerState::Running {
6153 adapter, server, ..
6154 } => Some((
6155 adapter.adapter.clone(),
6156 server.clone(),
6157 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
6158 )),
6159 }
6160 })
6161 })
6162 .collect::<Vec<_>>()
6163 })
6164 .ok()?;
6165
6166 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
6167 for (adapter, server, delegate) in servers {
6168 let settings = LocalLspStore::workspace_configuration_for_adapter(
6169 adapter,
6170 fs.as_ref(),
6171 &delegate,
6172 toolchain_store.clone(),
6173 cx,
6174 )
6175 .await
6176 .ok()?;
6177
6178 server
6179 .notify::<lsp::notification::DidChangeConfiguration>(
6180 &lsp::DidChangeConfigurationParams { settings },
6181 )
6182 .ok();
6183 }
6184 Some(())
6185 })
6186 .await;
6187 }
6188
6189 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
6190 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
6191 toolchain_store.read(cx).as_language_toolchain_store()
6192 } else {
6193 Arc::new(EmptyToolchainStore)
6194 }
6195 }
6196 fn maintain_workspace_config(
6197 fs: Arc<dyn Fs>,
6198 external_refresh_requests: watch::Receiver<()>,
6199 cx: &mut Context<Self>,
6200 ) -> Task<Result<()>> {
6201 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
6202 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
6203
6204 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
6205 *settings_changed_tx.borrow_mut() = ();
6206 });
6207
6208 let mut joint_future =
6209 futures::stream::select(settings_changed_rx, external_refresh_requests);
6210 cx.spawn(async move |this, cx| {
6211 while let Some(()) = joint_future.next().await {
6212 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
6213 }
6214
6215 drop(settings_observation);
6216 anyhow::Ok(())
6217 })
6218 }
6219
6220 pub fn language_servers_for_local_buffer<'a>(
6221 &'a self,
6222 buffer: &Buffer,
6223 cx: &mut App,
6224 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6225 let local = self.as_local();
6226 let language_server_ids = local
6227 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
6228 .unwrap_or_default();
6229
6230 language_server_ids
6231 .into_iter()
6232 .filter_map(
6233 move |server_id| match local?.language_servers.get(&server_id)? {
6234 LanguageServerState::Running {
6235 adapter, server, ..
6236 } => Some((adapter, server)),
6237 _ => None,
6238 },
6239 )
6240 }
6241
6242 pub fn language_server_for_local_buffer<'a>(
6243 &'a self,
6244 buffer: &'a Buffer,
6245 server_id: LanguageServerId,
6246 cx: &'a mut App,
6247 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6248 self.as_local()?
6249 .language_servers_for_buffer(buffer, cx)
6250 .find(|(_, s)| s.server_id() == server_id)
6251 }
6252
6253 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
6254 self.diagnostic_summaries.remove(&id_to_remove);
6255 if let Some(local) = self.as_local_mut() {
6256 let to_remove = local.remove_worktree(id_to_remove, cx);
6257 for server in to_remove {
6258 self.language_server_statuses.remove(&server);
6259 }
6260 }
6261 }
6262
6263 pub fn shared(
6264 &mut self,
6265 project_id: u64,
6266 downstream_client: AnyProtoClient,
6267 _: &mut Context<Self>,
6268 ) {
6269 self.downstream_client = Some((downstream_client.clone(), project_id));
6270
6271 for (server_id, status) in &self.language_server_statuses {
6272 downstream_client
6273 .send(proto::StartLanguageServer {
6274 project_id,
6275 server: Some(proto::LanguageServer {
6276 id: server_id.0 as u64,
6277 name: status.name.clone(),
6278 worktree_id: None,
6279 }),
6280 })
6281 .log_err();
6282 }
6283 }
6284
6285 pub fn disconnected_from_host(&mut self) {
6286 self.downstream_client.take();
6287 }
6288
6289 pub fn disconnected_from_ssh_remote(&mut self) {
6290 if let LspStoreMode::Remote(RemoteLspStore {
6291 upstream_client, ..
6292 }) = &mut self.mode
6293 {
6294 upstream_client.take();
6295 }
6296 }
6297
6298 pub(crate) fn set_language_server_statuses_from_proto(
6299 &mut self,
6300 language_servers: Vec<proto::LanguageServer>,
6301 ) {
6302 self.language_server_statuses = language_servers
6303 .into_iter()
6304 .map(|server| {
6305 (
6306 LanguageServerId(server.id as usize),
6307 LanguageServerStatus {
6308 name: server.name,
6309 pending_work: Default::default(),
6310 has_pending_diagnostic_updates: false,
6311 progress_tokens: Default::default(),
6312 },
6313 )
6314 })
6315 .collect();
6316 }
6317
6318 fn register_local_language_server(
6319 &mut self,
6320 worktree: Entity<Worktree>,
6321 language_server_name: LanguageServerName,
6322 language_server_id: LanguageServerId,
6323 cx: &mut App,
6324 ) {
6325 let Some(local) = self.as_local_mut() else {
6326 return;
6327 };
6328 let worktree_id = worktree.read(cx).id();
6329 let path = ProjectPath {
6330 worktree_id,
6331 path: Arc::from("".as_ref()),
6332 };
6333 let delegate = LocalLspAdapterDelegate::from_local_lsp(local, &worktree, cx);
6334 local.lsp_tree.update(cx, |this, cx| {
6335 for node in this.get(
6336 path,
6337 AdapterQuery::Adapter(&language_server_name),
6338 delegate,
6339 cx,
6340 ) {
6341 node.server_id_or_init(|disposition| {
6342 assert_eq!(disposition.server_name, &language_server_name);
6343
6344 language_server_id
6345 });
6346 }
6347 });
6348 local
6349 .language_server_ids
6350 .entry((worktree_id, language_server_name))
6351 .or_default()
6352 .insert(language_server_id);
6353 }
6354
6355 pub fn update_diagnostic_entries(
6356 &mut self,
6357 server_id: LanguageServerId,
6358 abs_path: PathBuf,
6359 version: Option<i32>,
6360 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6361 cx: &mut Context<Self>,
6362 ) -> anyhow::Result<()> {
6363 self.merge_diagnostic_entries(server_id, abs_path, version, diagnostics, |_| false, cx)
6364 }
6365
6366 pub fn merge_diagnostic_entries<F: Fn(&Diagnostic) -> bool + Clone>(
6367 &mut self,
6368 server_id: LanguageServerId,
6369 abs_path: PathBuf,
6370 version: Option<i32>,
6371 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6372 filter: F,
6373 cx: &mut Context<Self>,
6374 ) -> Result<(), anyhow::Error> {
6375 let Some((worktree, relative_path)) =
6376 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
6377 else {
6378 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
6379 return Ok(());
6380 };
6381
6382 let project_path = ProjectPath {
6383 worktree_id: worktree.read(cx).id(),
6384 path: relative_path.into(),
6385 };
6386
6387 if let Some(buffer) = self.buffer_store.read(cx).get_by_path(&project_path, cx) {
6388 let snapshot = self
6389 .as_local_mut()
6390 .unwrap()
6391 .buffer_snapshot_for_lsp_version(&buffer, server_id, version, cx)?;
6392
6393 diagnostics.extend(
6394 buffer
6395 .read(cx)
6396 .get_diagnostics(server_id)
6397 .into_iter()
6398 .flat_map(|diag| {
6399 diag.iter().filter(|v| filter(&v.diagnostic)).map(|v| {
6400 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
6401 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
6402 DiagnosticEntry {
6403 range: start..end,
6404 diagnostic: v.diagnostic.clone(),
6405 }
6406 })
6407 }),
6408 );
6409
6410 self.as_local_mut().unwrap().update_buffer_diagnostics(
6411 &buffer,
6412 server_id,
6413 version,
6414 diagnostics.clone(),
6415 cx,
6416 )?;
6417 }
6418
6419 let updated = worktree.update(cx, |worktree, cx| {
6420 self.update_worktree_diagnostics(
6421 worktree.id(),
6422 server_id,
6423 project_path.path.clone(),
6424 diagnostics,
6425 cx,
6426 )
6427 })?;
6428 if updated {
6429 cx.emit(LspStoreEvent::DiagnosticsUpdated {
6430 language_server_id: server_id,
6431 path: project_path,
6432 })
6433 }
6434 Ok(())
6435 }
6436
6437 fn update_worktree_diagnostics(
6438 &mut self,
6439 worktree_id: WorktreeId,
6440 server_id: LanguageServerId,
6441 worktree_path: Arc<Path>,
6442 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6443 _: &mut Context<Worktree>,
6444 ) -> Result<bool> {
6445 let local = match &mut self.mode {
6446 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
6447 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
6448 };
6449
6450 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
6451 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
6452 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
6453
6454 let old_summary = summaries_by_server_id
6455 .remove(&server_id)
6456 .unwrap_or_default();
6457
6458 let new_summary = DiagnosticSummary::new(&diagnostics);
6459 if new_summary.is_empty() {
6460 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
6461 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6462 diagnostics_by_server_id.remove(ix);
6463 }
6464 if diagnostics_by_server_id.is_empty() {
6465 diagnostics_for_tree.remove(&worktree_path);
6466 }
6467 }
6468 } else {
6469 summaries_by_server_id.insert(server_id, new_summary);
6470 let diagnostics_by_server_id = diagnostics_for_tree
6471 .entry(worktree_path.clone())
6472 .or_default();
6473 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6474 Ok(ix) => {
6475 diagnostics_by_server_id[ix] = (server_id, diagnostics);
6476 }
6477 Err(ix) => {
6478 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
6479 }
6480 }
6481 }
6482
6483 if !old_summary.is_empty() || !new_summary.is_empty() {
6484 if let Some((downstream_client, project_id)) = &self.downstream_client {
6485 downstream_client
6486 .send(proto::UpdateDiagnosticSummary {
6487 project_id: *project_id,
6488 worktree_id: worktree_id.to_proto(),
6489 summary: Some(proto::DiagnosticSummary {
6490 path: worktree_path.to_proto(),
6491 language_server_id: server_id.0 as u64,
6492 error_count: new_summary.error_count as u32,
6493 warning_count: new_summary.warning_count as u32,
6494 }),
6495 })
6496 .log_err();
6497 }
6498 }
6499
6500 Ok(!old_summary.is_empty() || !new_summary.is_empty())
6501 }
6502
6503 pub fn open_buffer_for_symbol(
6504 &mut self,
6505 symbol: &Symbol,
6506 cx: &mut Context<Self>,
6507 ) -> Task<Result<Entity<Buffer>>> {
6508 if let Some((client, project_id)) = self.upstream_client() {
6509 let request = client.request(proto::OpenBufferForSymbol {
6510 project_id,
6511 symbol: Some(Self::serialize_symbol(symbol)),
6512 });
6513 cx.spawn(async move |this, cx| {
6514 let response = request.await?;
6515 let buffer_id = BufferId::new(response.buffer_id)?;
6516 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
6517 .await
6518 })
6519 } else if let Some(local) = self.as_local() {
6520 let Some(language_server_id) = local
6521 .language_server_ids
6522 .get(&(
6523 symbol.source_worktree_id,
6524 symbol.language_server_name.clone(),
6525 ))
6526 .and_then(|ids| {
6527 ids.contains(&symbol.source_language_server_id)
6528 .then_some(symbol.source_language_server_id)
6529 })
6530 else {
6531 return Task::ready(Err(anyhow!(
6532 "language server for worktree and language not found"
6533 )));
6534 };
6535
6536 let worktree_abs_path = if let Some(worktree_abs_path) = self
6537 .worktree_store
6538 .read(cx)
6539 .worktree_for_id(symbol.path.worktree_id, cx)
6540 .map(|worktree| worktree.read(cx).abs_path())
6541 {
6542 worktree_abs_path
6543 } else {
6544 return Task::ready(Err(anyhow!("worktree not found for symbol")));
6545 };
6546
6547 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
6548 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
6549 uri
6550 } else {
6551 return Task::ready(Err(anyhow!("invalid symbol path")));
6552 };
6553
6554 self.open_local_buffer_via_lsp(
6555 symbol_uri,
6556 language_server_id,
6557 symbol.language_server_name.clone(),
6558 cx,
6559 )
6560 } else {
6561 Task::ready(Err(anyhow!("no upstream client or local store")))
6562 }
6563 }
6564
6565 pub fn open_local_buffer_via_lsp(
6566 &mut self,
6567 mut abs_path: lsp::Url,
6568 language_server_id: LanguageServerId,
6569 language_server_name: LanguageServerName,
6570 cx: &mut Context<Self>,
6571 ) -> Task<Result<Entity<Buffer>>> {
6572 cx.spawn(async move |lsp_store, cx| {
6573 // Escape percent-encoded string.
6574 let current_scheme = abs_path.scheme().to_owned();
6575 let _ = abs_path.set_scheme("file");
6576
6577 let abs_path = abs_path
6578 .to_file_path()
6579 .map_err(|_| anyhow!("can't convert URI to path"))?;
6580 let p = abs_path.clone();
6581 let yarn_worktree = lsp_store
6582 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
6583 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
6584 cx.spawn(async move |this, cx| {
6585 let t = this
6586 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
6587 .ok()?;
6588 t.await
6589 })
6590 }),
6591 None => Task::ready(None),
6592 })?
6593 .await;
6594 let (worktree_root_target, known_relative_path) =
6595 if let Some((zip_root, relative_path)) = yarn_worktree {
6596 (zip_root, Some(relative_path))
6597 } else {
6598 (Arc::<Path>::from(abs_path.as_path()), None)
6599 };
6600 let (worktree, relative_path) = if let Some(result) =
6601 lsp_store.update(cx, |lsp_store, cx| {
6602 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6603 worktree_store.find_worktree(&worktree_root_target, cx)
6604 })
6605 })? {
6606 let relative_path =
6607 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
6608 (result.0, relative_path)
6609 } else {
6610 let worktree = lsp_store
6611 .update(cx, |lsp_store, cx| {
6612 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6613 worktree_store.create_worktree(&worktree_root_target, false, cx)
6614 })
6615 })?
6616 .await?;
6617 if worktree.update(cx, |worktree, _| worktree.is_local())? {
6618 lsp_store
6619 .update(cx, |lsp_store, cx| {
6620 lsp_store.register_local_language_server(
6621 worktree.clone(),
6622 language_server_name,
6623 language_server_id,
6624 cx,
6625 )
6626 })
6627 .ok();
6628 }
6629 let worktree_root = worktree.update(cx, |worktree, _| worktree.abs_path())?;
6630 let relative_path = if let Some(known_path) = known_relative_path {
6631 known_path
6632 } else {
6633 abs_path.strip_prefix(worktree_root)?.into()
6634 };
6635 (worktree, relative_path)
6636 };
6637 let project_path = ProjectPath {
6638 worktree_id: worktree.update(cx, |worktree, _| worktree.id())?,
6639 path: relative_path,
6640 };
6641 lsp_store
6642 .update(cx, |lsp_store, cx| {
6643 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
6644 buffer_store.open_buffer(project_path, cx)
6645 })
6646 })?
6647 .await
6648 })
6649 }
6650
6651 fn request_multiple_lsp_locally<P, R>(
6652 &mut self,
6653 buffer: &Entity<Buffer>,
6654 position: Option<P>,
6655 request: R,
6656 cx: &mut Context<Self>,
6657 ) -> Task<Vec<R::Response>>
6658 where
6659 P: ToOffset,
6660 R: LspCommand + Clone,
6661 <R::LspRequest as lsp::request::Request>::Result: Send,
6662 <R::LspRequest as lsp::request::Request>::Params: Send,
6663 {
6664 let Some(local) = self.as_local() else {
6665 return Task::ready(Vec::new());
6666 };
6667
6668 let snapshot = buffer.read(cx).snapshot();
6669 let scope = position.and_then(|position| snapshot.language_scope_at(position));
6670
6671 let server_ids = buffer.update(cx, |buffer, cx| {
6672 local
6673 .language_servers_for_buffer(buffer, cx)
6674 .filter(|(adapter, _)| {
6675 scope
6676 .as_ref()
6677 .map(|scope| scope.language_allowed(&adapter.name))
6678 .unwrap_or(true)
6679 })
6680 .map(|(_, server)| server.server_id())
6681 .collect::<Vec<_>>()
6682 });
6683
6684 let mut response_results = server_ids
6685 .into_iter()
6686 .map(|server_id| {
6687 self.request_lsp(
6688 buffer.clone(),
6689 LanguageServerToQuery::Other(server_id),
6690 request.clone(),
6691 cx,
6692 )
6693 })
6694 .collect::<FuturesUnordered<_>>();
6695
6696 cx.spawn(async move |_, _| {
6697 let mut responses = Vec::with_capacity(response_results.len());
6698 while let Some(response_result) = response_results.next().await {
6699 if let Some(response) = response_result.log_err() {
6700 responses.push(response);
6701 }
6702 }
6703 responses
6704 })
6705 }
6706
6707 async fn handle_lsp_command<T: LspCommand>(
6708 this: Entity<Self>,
6709 envelope: TypedEnvelope<T::ProtoRequest>,
6710 mut cx: AsyncApp,
6711 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6712 where
6713 <T::LspRequest as lsp::request::Request>::Params: Send,
6714 <T::LspRequest as lsp::request::Request>::Result: Send,
6715 {
6716 let sender_id = envelope.original_sender_id().unwrap_or_default();
6717 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
6718 let buffer_handle = this.update(&mut cx, |this, cx| {
6719 this.buffer_store.read(cx).get_existing(buffer_id)
6720 })??;
6721 let request = T::from_proto(
6722 envelope.payload,
6723 this.clone(),
6724 buffer_handle.clone(),
6725 cx.clone(),
6726 )
6727 .await?;
6728 let response = this
6729 .update(&mut cx, |this, cx| {
6730 this.request_lsp(
6731 buffer_handle.clone(),
6732 LanguageServerToQuery::FirstCapable,
6733 request,
6734 cx,
6735 )
6736 })?
6737 .await?;
6738 this.update(&mut cx, |this, cx| {
6739 Ok(T::response_to_proto(
6740 response,
6741 this,
6742 sender_id,
6743 &buffer_handle.read(cx).version(),
6744 cx,
6745 ))
6746 })?
6747 }
6748
6749 async fn handle_multi_lsp_query(
6750 this: Entity<Self>,
6751 envelope: TypedEnvelope<proto::MultiLspQuery>,
6752 mut cx: AsyncApp,
6753 ) -> Result<proto::MultiLspQueryResponse> {
6754 let response_from_ssh = this.update(&mut cx, |this, _| {
6755 let (upstream_client, project_id) = this.upstream_client()?;
6756 let mut payload = envelope.payload.clone();
6757 payload.project_id = project_id;
6758
6759 Some(upstream_client.request(payload))
6760 })?;
6761 if let Some(response_from_ssh) = response_from_ssh {
6762 return response_from_ssh.await;
6763 }
6764
6765 let sender_id = envelope.original_sender_id().unwrap_or_default();
6766 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6767 let version = deserialize_version(&envelope.payload.version);
6768 let buffer = this.update(&mut cx, |this, cx| {
6769 this.buffer_store.read(cx).get_existing(buffer_id)
6770 })??;
6771 buffer
6772 .update(&mut cx, |buffer, _| {
6773 buffer.wait_for_version(version.clone())
6774 })?
6775 .await?;
6776 let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
6777 match envelope
6778 .payload
6779 .strategy
6780 .context("invalid request without the strategy")?
6781 {
6782 proto::multi_lsp_query::Strategy::All(_) => {
6783 // currently, there's only one multiple language servers query strategy,
6784 // so just ensure it's specified correctly
6785 }
6786 }
6787 match envelope.payload.request {
6788 Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
6789 let get_hover =
6790 GetHover::from_proto(get_hover, this.clone(), buffer.clone(), cx.clone())
6791 .await?;
6792 let all_hovers = this
6793 .update(&mut cx, |this, cx| {
6794 this.request_multiple_lsp_locally(
6795 &buffer,
6796 Some(get_hover.position),
6797 get_hover,
6798 cx,
6799 )
6800 })?
6801 .await
6802 .into_iter()
6803 .filter_map(|hover| remove_empty_hover_blocks(hover?));
6804 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6805 responses: all_hovers
6806 .map(|hover| proto::LspResponse {
6807 response: Some(proto::lsp_response::Response::GetHoverResponse(
6808 GetHover::response_to_proto(
6809 Some(hover),
6810 project,
6811 sender_id,
6812 &buffer_version,
6813 cx,
6814 ),
6815 )),
6816 })
6817 .collect(),
6818 })
6819 }
6820 Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
6821 let get_code_actions = GetCodeActions::from_proto(
6822 get_code_actions,
6823 this.clone(),
6824 buffer.clone(),
6825 cx.clone(),
6826 )
6827 .await?;
6828
6829 let all_actions = this
6830 .update(&mut cx, |project, cx| {
6831 project.request_multiple_lsp_locally(
6832 &buffer,
6833 Some(get_code_actions.range.start),
6834 get_code_actions,
6835 cx,
6836 )
6837 })?
6838 .await
6839 .into_iter();
6840
6841 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6842 responses: all_actions
6843 .map(|code_actions| proto::LspResponse {
6844 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
6845 GetCodeActions::response_to_proto(
6846 code_actions,
6847 project,
6848 sender_id,
6849 &buffer_version,
6850 cx,
6851 ),
6852 )),
6853 })
6854 .collect(),
6855 })
6856 }
6857 Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
6858 let get_signature_help = GetSignatureHelp::from_proto(
6859 get_signature_help,
6860 this.clone(),
6861 buffer.clone(),
6862 cx.clone(),
6863 )
6864 .await?;
6865
6866 let all_signatures = this
6867 .update(&mut cx, |project, cx| {
6868 project.request_multiple_lsp_locally(
6869 &buffer,
6870 Some(get_signature_help.position),
6871 get_signature_help,
6872 cx,
6873 )
6874 })?
6875 .await
6876 .into_iter();
6877
6878 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6879 responses: all_signatures
6880 .map(|signature_help| proto::LspResponse {
6881 response: Some(
6882 proto::lsp_response::Response::GetSignatureHelpResponse(
6883 GetSignatureHelp::response_to_proto(
6884 signature_help,
6885 project,
6886 sender_id,
6887 &buffer_version,
6888 cx,
6889 ),
6890 ),
6891 ),
6892 })
6893 .collect(),
6894 })
6895 }
6896 Some(proto::multi_lsp_query::Request::GetCodeLens(get_code_lens)) => {
6897 let get_code_lens = GetCodeLens::from_proto(
6898 get_code_lens,
6899 this.clone(),
6900 buffer.clone(),
6901 cx.clone(),
6902 )
6903 .await?;
6904
6905 let code_lens_actions = this
6906 .update(&mut cx, |project, cx| {
6907 project.request_multiple_lsp_locally(
6908 &buffer,
6909 None::<usize>,
6910 get_code_lens,
6911 cx,
6912 )
6913 })?
6914 .await
6915 .into_iter();
6916
6917 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6918 responses: code_lens_actions
6919 .map(|actions| proto::LspResponse {
6920 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
6921 GetCodeLens::response_to_proto(
6922 actions,
6923 project,
6924 sender_id,
6925 &buffer_version,
6926 cx,
6927 ),
6928 )),
6929 })
6930 .collect(),
6931 })
6932 }
6933 None => anyhow::bail!("empty multi lsp query request"),
6934 }
6935 }
6936
6937 async fn handle_apply_code_action(
6938 this: Entity<Self>,
6939 envelope: TypedEnvelope<proto::ApplyCodeAction>,
6940 mut cx: AsyncApp,
6941 ) -> Result<proto::ApplyCodeActionResponse> {
6942 let sender_id = envelope.original_sender_id().unwrap_or_default();
6943 let action = Self::deserialize_code_action(
6944 envelope
6945 .payload
6946 .action
6947 .ok_or_else(|| anyhow!("invalid action"))?,
6948 )?;
6949 let apply_code_action = this.update(&mut cx, |this, cx| {
6950 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6951 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
6952 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
6953 })??;
6954
6955 let project_transaction = apply_code_action.await?;
6956 let project_transaction = this.update(&mut cx, |this, cx| {
6957 this.buffer_store.update(cx, |buffer_store, cx| {
6958 buffer_store.serialize_project_transaction_for_peer(
6959 project_transaction,
6960 sender_id,
6961 cx,
6962 )
6963 })
6964 })?;
6965 Ok(proto::ApplyCodeActionResponse {
6966 transaction: Some(project_transaction),
6967 })
6968 }
6969
6970 async fn handle_register_buffer_with_language_servers(
6971 this: Entity<Self>,
6972 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
6973 mut cx: AsyncApp,
6974 ) -> Result<proto::Ack> {
6975 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6976 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
6977 this.update(&mut cx, |this, cx| {
6978 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
6979 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
6980 project_id: upstream_project_id,
6981 buffer_id: buffer_id.to_proto(),
6982 });
6983 }
6984
6985 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
6986 anyhow::bail!("buffer is not open");
6987 };
6988
6989 let handle = this.register_buffer_with_language_servers(&buffer, false, cx);
6990 this.buffer_store().update(cx, |buffer_store, _| {
6991 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
6992 });
6993
6994 Ok(())
6995 })??;
6996 Ok(proto::Ack {})
6997 }
6998
6999 async fn handle_language_server_id_for_name(
7000 lsp_store: Entity<Self>,
7001 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7002 mut cx: AsyncApp,
7003 ) -> Result<proto::LanguageServerIdForNameResponse> {
7004 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7005 let name = &envelope.payload.name;
7006 lsp_store
7007 .update(&mut cx, |lsp_store, cx| {
7008 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7009 let server_id = buffer.update(cx, |buffer, cx| {
7010 lsp_store
7011 .language_servers_for_local_buffer(buffer, cx)
7012 .find_map(|(adapter, server)| {
7013 if adapter.name.0.as_ref() == name {
7014 Some(server.server_id())
7015 } else {
7016 None
7017 }
7018 })
7019 });
7020 Ok(server_id)
7021 })?
7022 .map(|server_id| proto::LanguageServerIdForNameResponse {
7023 server_id: server_id.map(|id| id.to_proto()),
7024 })
7025 }
7026
7027 async fn handle_rename_project_entry(
7028 this: Entity<Self>,
7029 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7030 mut cx: AsyncApp,
7031 ) -> Result<proto::ProjectEntryResponse> {
7032 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7033 let (worktree_id, worktree, old_path, is_dir) = this
7034 .update(&mut cx, |this, cx| {
7035 this.worktree_store
7036 .read(cx)
7037 .worktree_and_entry_for_id(entry_id, cx)
7038 .map(|(worktree, entry)| {
7039 (
7040 worktree.read(cx).id(),
7041 worktree,
7042 entry.path.clone(),
7043 entry.is_dir(),
7044 )
7045 })
7046 })?
7047 .ok_or_else(|| anyhow!("worktree not found"))?;
7048 let (old_abs_path, new_abs_path) = {
7049 let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
7050 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
7051 (root_path.join(&old_path), root_path.join(&new_path))
7052 };
7053
7054 Self::will_rename_entry(
7055 this.downgrade(),
7056 worktree_id,
7057 &old_abs_path,
7058 &new_abs_path,
7059 is_dir,
7060 cx.clone(),
7061 )
7062 .await;
7063 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
7064 this.update(&mut cx, |this, _| {
7065 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
7066 })
7067 .ok();
7068 response
7069 }
7070
7071 async fn handle_update_diagnostic_summary(
7072 this: Entity<Self>,
7073 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7074 mut cx: AsyncApp,
7075 ) -> Result<()> {
7076 this.update(&mut cx, |this, cx| {
7077 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7078 if let Some(message) = envelope.payload.summary {
7079 let project_path = ProjectPath {
7080 worktree_id,
7081 path: Arc::<Path>::from_proto(message.path),
7082 };
7083 let path = project_path.path.clone();
7084 let server_id = LanguageServerId(message.language_server_id as usize);
7085 let summary = DiagnosticSummary {
7086 error_count: message.error_count as usize,
7087 warning_count: message.warning_count as usize,
7088 };
7089
7090 if summary.is_empty() {
7091 if let Some(worktree_summaries) =
7092 this.diagnostic_summaries.get_mut(&worktree_id)
7093 {
7094 if let Some(summaries) = worktree_summaries.get_mut(&path) {
7095 summaries.remove(&server_id);
7096 if summaries.is_empty() {
7097 worktree_summaries.remove(&path);
7098 }
7099 }
7100 }
7101 } else {
7102 this.diagnostic_summaries
7103 .entry(worktree_id)
7104 .or_default()
7105 .entry(path)
7106 .or_default()
7107 .insert(server_id, summary);
7108 }
7109 if let Some((downstream_client, project_id)) = &this.downstream_client {
7110 downstream_client
7111 .send(proto::UpdateDiagnosticSummary {
7112 project_id: *project_id,
7113 worktree_id: worktree_id.to_proto(),
7114 summary: Some(proto::DiagnosticSummary {
7115 path: project_path.path.as_ref().to_proto(),
7116 language_server_id: server_id.0 as u64,
7117 error_count: summary.error_count as u32,
7118 warning_count: summary.warning_count as u32,
7119 }),
7120 })
7121 .log_err();
7122 }
7123 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7124 language_server_id: LanguageServerId(message.language_server_id as usize),
7125 path: project_path,
7126 });
7127 }
7128 Ok(())
7129 })?
7130 }
7131
7132 async fn handle_start_language_server(
7133 this: Entity<Self>,
7134 envelope: TypedEnvelope<proto::StartLanguageServer>,
7135 mut cx: AsyncApp,
7136 ) -> Result<()> {
7137 let server = envelope
7138 .payload
7139 .server
7140 .ok_or_else(|| anyhow!("invalid server"))?;
7141
7142 this.update(&mut cx, |this, cx| {
7143 let server_id = LanguageServerId(server.id as usize);
7144 this.language_server_statuses.insert(
7145 server_id,
7146 LanguageServerStatus {
7147 name: server.name.clone(),
7148 pending_work: Default::default(),
7149 has_pending_diagnostic_updates: false,
7150 progress_tokens: Default::default(),
7151 },
7152 );
7153 cx.emit(LspStoreEvent::LanguageServerAdded(
7154 server_id,
7155 LanguageServerName(server.name.into()),
7156 server.worktree_id.map(WorktreeId::from_proto),
7157 ));
7158 cx.notify();
7159 })?;
7160 Ok(())
7161 }
7162
7163 async fn handle_update_language_server(
7164 this: Entity<Self>,
7165 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7166 mut cx: AsyncApp,
7167 ) -> Result<()> {
7168 this.update(&mut cx, |this, cx| {
7169 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7170
7171 match envelope
7172 .payload
7173 .variant
7174 .ok_or_else(|| anyhow!("invalid variant"))?
7175 {
7176 proto::update_language_server::Variant::WorkStart(payload) => {
7177 this.on_lsp_work_start(
7178 language_server_id,
7179 payload.token,
7180 LanguageServerProgress {
7181 title: payload.title,
7182 is_disk_based_diagnostics_progress: false,
7183 is_cancellable: payload.is_cancellable.unwrap_or(false),
7184 message: payload.message,
7185 percentage: payload.percentage.map(|p| p as usize),
7186 last_update_at: cx.background_executor().now(),
7187 },
7188 cx,
7189 );
7190 }
7191
7192 proto::update_language_server::Variant::WorkProgress(payload) => {
7193 this.on_lsp_work_progress(
7194 language_server_id,
7195 payload.token,
7196 LanguageServerProgress {
7197 title: None,
7198 is_disk_based_diagnostics_progress: false,
7199 is_cancellable: payload.is_cancellable.unwrap_or(false),
7200 message: payload.message,
7201 percentage: payload.percentage.map(|p| p as usize),
7202 last_update_at: cx.background_executor().now(),
7203 },
7204 cx,
7205 );
7206 }
7207
7208 proto::update_language_server::Variant::WorkEnd(payload) => {
7209 this.on_lsp_work_end(language_server_id, payload.token, cx);
7210 }
7211
7212 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7213 this.disk_based_diagnostics_started(language_server_id, cx);
7214 }
7215
7216 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7217 this.disk_based_diagnostics_finished(language_server_id, cx)
7218 }
7219 }
7220
7221 Ok(())
7222 })?
7223 }
7224
7225 async fn handle_language_server_log(
7226 this: Entity<Self>,
7227 envelope: TypedEnvelope<proto::LanguageServerLog>,
7228 mut cx: AsyncApp,
7229 ) -> Result<()> {
7230 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7231 let log_type = envelope
7232 .payload
7233 .log_type
7234 .map(LanguageServerLogType::from_proto)
7235 .context("invalid language server log type")?;
7236
7237 let message = envelope.payload.message;
7238
7239 this.update(&mut cx, |_, cx| {
7240 cx.emit(LspStoreEvent::LanguageServerLog(
7241 language_server_id,
7242 log_type,
7243 message,
7244 ));
7245 })
7246 }
7247
7248 pub fn disk_based_diagnostics_started(
7249 &mut self,
7250 language_server_id: LanguageServerId,
7251 cx: &mut Context<Self>,
7252 ) {
7253 if let Some(language_server_status) =
7254 self.language_server_statuses.get_mut(&language_server_id)
7255 {
7256 language_server_status.has_pending_diagnostic_updates = true;
7257 }
7258
7259 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
7260 cx.emit(LspStoreEvent::LanguageServerUpdate {
7261 language_server_id,
7262 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
7263 Default::default(),
7264 ),
7265 })
7266 }
7267
7268 pub fn disk_based_diagnostics_finished(
7269 &mut self,
7270 language_server_id: LanguageServerId,
7271 cx: &mut Context<Self>,
7272 ) {
7273 if let Some(language_server_status) =
7274 self.language_server_statuses.get_mut(&language_server_id)
7275 {
7276 language_server_status.has_pending_diagnostic_updates = false;
7277 }
7278
7279 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
7280 cx.emit(LspStoreEvent::LanguageServerUpdate {
7281 language_server_id,
7282 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
7283 Default::default(),
7284 ),
7285 })
7286 }
7287
7288 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
7289 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
7290 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
7291 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
7292 // the language server might take some time to publish diagnostics.
7293 fn simulate_disk_based_diagnostics_events_if_needed(
7294 &mut self,
7295 language_server_id: LanguageServerId,
7296 cx: &mut Context<Self>,
7297 ) {
7298 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
7299
7300 let Some(LanguageServerState::Running {
7301 simulate_disk_based_diagnostics_completion,
7302 adapter,
7303 ..
7304 }) = self
7305 .as_local_mut()
7306 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
7307 else {
7308 return;
7309 };
7310
7311 if adapter.disk_based_diagnostics_progress_token.is_some() {
7312 return;
7313 }
7314
7315 let prev_task =
7316 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
7317 cx.background_executor()
7318 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
7319 .await;
7320
7321 this.update(cx, |this, cx| {
7322 this.disk_based_diagnostics_finished(language_server_id, cx);
7323
7324 if let Some(LanguageServerState::Running {
7325 simulate_disk_based_diagnostics_completion,
7326 ..
7327 }) = this.as_local_mut().and_then(|local_store| {
7328 local_store.language_servers.get_mut(&language_server_id)
7329 }) {
7330 *simulate_disk_based_diagnostics_completion = None;
7331 }
7332 })
7333 .ok();
7334 }));
7335
7336 if prev_task.is_none() {
7337 self.disk_based_diagnostics_started(language_server_id, cx);
7338 }
7339 }
7340
7341 pub fn language_server_statuses(
7342 &self,
7343 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
7344 self.language_server_statuses
7345 .iter()
7346 .map(|(key, value)| (*key, value))
7347 }
7348
7349 pub(super) fn did_rename_entry(
7350 &self,
7351 worktree_id: WorktreeId,
7352 old_path: &Path,
7353 new_path: &Path,
7354 is_dir: bool,
7355 ) {
7356 maybe!({
7357 let local_store = self.as_local()?;
7358
7359 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
7360 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
7361
7362 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7363 let Some(filter) = local_store
7364 .language_server_paths_watched_for_rename
7365 .get(&language_server.server_id())
7366 else {
7367 continue;
7368 };
7369
7370 if filter.should_send_did_rename(&old_uri, is_dir) {
7371 language_server
7372 .notify::<DidRenameFiles>(&RenameFilesParams {
7373 files: vec![FileRename {
7374 old_uri: old_uri.clone(),
7375 new_uri: new_uri.clone(),
7376 }],
7377 })
7378 .log_err();
7379 }
7380 }
7381 Some(())
7382 });
7383 }
7384
7385 pub(super) fn will_rename_entry(
7386 this: WeakEntity<Self>,
7387 worktree_id: WorktreeId,
7388 old_path: &Path,
7389 new_path: &Path,
7390 is_dir: bool,
7391 cx: AsyncApp,
7392 ) -> Task<()> {
7393 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
7394 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
7395 cx.spawn(async move |cx| {
7396 let mut tasks = vec![];
7397 this.update(cx, |this, cx| {
7398 let local_store = this.as_local()?;
7399 let old_uri = old_uri?;
7400 let new_uri = new_uri?;
7401 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7402 let Some(filter) = local_store
7403 .language_server_paths_watched_for_rename
7404 .get(&language_server.server_id())
7405 else {
7406 continue;
7407 };
7408 let Some(adapter) =
7409 this.language_server_adapter_for_id(language_server.server_id())
7410 else {
7411 continue;
7412 };
7413 if filter.should_send_will_rename(&old_uri, is_dir) {
7414 let apply_edit = cx.spawn({
7415 let old_uri = old_uri.clone();
7416 let new_uri = new_uri.clone();
7417 let language_server = language_server.clone();
7418 async move |this, cx| {
7419 let edit = language_server
7420 .request::<WillRenameFiles>(RenameFilesParams {
7421 files: vec![FileRename { old_uri, new_uri }],
7422 })
7423 .log_err()
7424 .await
7425 .flatten()?;
7426
7427 LocalLspStore::deserialize_workspace_edit(
7428 this.upgrade()?,
7429 edit,
7430 false,
7431 adapter.clone(),
7432 language_server.clone(),
7433 cx,
7434 )
7435 .await
7436 .ok();
7437 Some(())
7438 }
7439 });
7440 tasks.push(apply_edit);
7441 }
7442 }
7443 Some(())
7444 })
7445 .ok()
7446 .flatten();
7447 for task in tasks {
7448 // Await on tasks sequentially so that the order of application of edits is deterministic
7449 // (at least with regards to the order of registration of language servers)
7450 task.await;
7451 }
7452 })
7453 }
7454
7455 fn lsp_notify_abs_paths_changed(
7456 &mut self,
7457 server_id: LanguageServerId,
7458 changes: Vec<PathEvent>,
7459 ) {
7460 maybe!({
7461 let server = self.language_server_for_id(server_id)?;
7462 let changes = changes
7463 .into_iter()
7464 .filter_map(|event| {
7465 let typ = match event.kind? {
7466 PathEventKind::Created => lsp::FileChangeType::CREATED,
7467 PathEventKind::Removed => lsp::FileChangeType::DELETED,
7468 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
7469 };
7470 Some(lsp::FileEvent {
7471 uri: lsp::Url::from_file_path(&event.path).ok()?,
7472 typ,
7473 })
7474 })
7475 .collect::<Vec<_>>();
7476 if !changes.is_empty() {
7477 server
7478 .notify::<lsp::notification::DidChangeWatchedFiles>(
7479 &lsp::DidChangeWatchedFilesParams { changes },
7480 )
7481 .log_err();
7482 }
7483 Some(())
7484 });
7485 }
7486
7487 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7488 let local_lsp_store = self.as_local()?;
7489 if let Some(LanguageServerState::Running { server, .. }) =
7490 local_lsp_store.language_servers.get(&id)
7491 {
7492 Some(server.clone())
7493 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
7494 Some(Arc::clone(server))
7495 } else {
7496 None
7497 }
7498 }
7499
7500 fn on_lsp_progress(
7501 &mut self,
7502 progress: lsp::ProgressParams,
7503 language_server_id: LanguageServerId,
7504 disk_based_diagnostics_progress_token: Option<String>,
7505 cx: &mut Context<Self>,
7506 ) {
7507 let token = match progress.token {
7508 lsp::NumberOrString::String(token) => token,
7509 lsp::NumberOrString::Number(token) => {
7510 log::info!("skipping numeric progress token {}", token);
7511 return;
7512 }
7513 };
7514
7515 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
7516 let language_server_status =
7517 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7518 status
7519 } else {
7520 return;
7521 };
7522
7523 if !language_server_status.progress_tokens.contains(&token) {
7524 return;
7525 }
7526
7527 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
7528 .as_ref()
7529 .map_or(false, |disk_based_token| {
7530 token.starts_with(disk_based_token)
7531 });
7532
7533 match progress {
7534 lsp::WorkDoneProgress::Begin(report) => {
7535 if is_disk_based_diagnostics_progress {
7536 self.disk_based_diagnostics_started(language_server_id, cx);
7537 }
7538 self.on_lsp_work_start(
7539 language_server_id,
7540 token.clone(),
7541 LanguageServerProgress {
7542 title: Some(report.title),
7543 is_disk_based_diagnostics_progress,
7544 is_cancellable: report.cancellable.unwrap_or(false),
7545 message: report.message.clone(),
7546 percentage: report.percentage.map(|p| p as usize),
7547 last_update_at: cx.background_executor().now(),
7548 },
7549 cx,
7550 );
7551 }
7552 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
7553 language_server_id,
7554 token,
7555 LanguageServerProgress {
7556 title: None,
7557 is_disk_based_diagnostics_progress,
7558 is_cancellable: report.cancellable.unwrap_or(false),
7559 message: report.message,
7560 percentage: report.percentage.map(|p| p as usize),
7561 last_update_at: cx.background_executor().now(),
7562 },
7563 cx,
7564 ),
7565 lsp::WorkDoneProgress::End(_) => {
7566 language_server_status.progress_tokens.remove(&token);
7567 self.on_lsp_work_end(language_server_id, token.clone(), cx);
7568 if is_disk_based_diagnostics_progress {
7569 self.disk_based_diagnostics_finished(language_server_id, cx);
7570 }
7571 }
7572 }
7573 }
7574
7575 fn on_lsp_work_start(
7576 &mut self,
7577 language_server_id: LanguageServerId,
7578 token: String,
7579 progress: LanguageServerProgress,
7580 cx: &mut Context<Self>,
7581 ) {
7582 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7583 status.pending_work.insert(token.clone(), progress.clone());
7584 cx.notify();
7585 }
7586 cx.emit(LspStoreEvent::LanguageServerUpdate {
7587 language_server_id,
7588 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
7589 token,
7590 title: progress.title,
7591 message: progress.message,
7592 percentage: progress.percentage.map(|p| p as u32),
7593 is_cancellable: Some(progress.is_cancellable),
7594 }),
7595 })
7596 }
7597
7598 fn on_lsp_work_progress(
7599 &mut self,
7600 language_server_id: LanguageServerId,
7601 token: String,
7602 progress: LanguageServerProgress,
7603 cx: &mut Context<Self>,
7604 ) {
7605 let mut did_update = false;
7606 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7607 match status.pending_work.entry(token.clone()) {
7608 btree_map::Entry::Vacant(entry) => {
7609 entry.insert(progress.clone());
7610 did_update = true;
7611 }
7612 btree_map::Entry::Occupied(mut entry) => {
7613 let entry = entry.get_mut();
7614 if (progress.last_update_at - entry.last_update_at)
7615 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
7616 {
7617 entry.last_update_at = progress.last_update_at;
7618 if progress.message.is_some() {
7619 entry.message = progress.message.clone();
7620 }
7621 if progress.percentage.is_some() {
7622 entry.percentage = progress.percentage;
7623 }
7624 if progress.is_cancellable != entry.is_cancellable {
7625 entry.is_cancellable = progress.is_cancellable;
7626 }
7627 did_update = true;
7628 }
7629 }
7630 }
7631 }
7632
7633 if did_update {
7634 cx.emit(LspStoreEvent::LanguageServerUpdate {
7635 language_server_id,
7636 message: proto::update_language_server::Variant::WorkProgress(
7637 proto::LspWorkProgress {
7638 token,
7639 message: progress.message,
7640 percentage: progress.percentage.map(|p| p as u32),
7641 is_cancellable: Some(progress.is_cancellable),
7642 },
7643 ),
7644 })
7645 }
7646 }
7647
7648 fn on_lsp_work_end(
7649 &mut self,
7650 language_server_id: LanguageServerId,
7651 token: String,
7652 cx: &mut Context<Self>,
7653 ) {
7654 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7655 if let Some(work) = status.pending_work.remove(&token) {
7656 if !work.is_disk_based_diagnostics_progress {
7657 cx.emit(LspStoreEvent::RefreshInlayHints);
7658 }
7659 }
7660 cx.notify();
7661 }
7662
7663 cx.emit(LspStoreEvent::LanguageServerUpdate {
7664 language_server_id,
7665 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
7666 })
7667 }
7668
7669 pub async fn handle_resolve_completion_documentation(
7670 this: Entity<Self>,
7671 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7672 mut cx: AsyncApp,
7673 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7674 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7675
7676 let completion = this
7677 .read_with(&cx, |this, cx| {
7678 let id = LanguageServerId(envelope.payload.language_server_id as usize);
7679 let Some(server) = this.language_server_for_id(id) else {
7680 return Err(anyhow!("No language server {id}"));
7681 };
7682
7683 Ok(cx.background_spawn(async move {
7684 let can_resolve = server
7685 .capabilities()
7686 .completion_provider
7687 .as_ref()
7688 .and_then(|options| options.resolve_provider)
7689 .unwrap_or(false);
7690 if can_resolve {
7691 server
7692 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
7693 .await
7694 } else {
7695 anyhow::Ok(lsp_completion)
7696 }
7697 }))
7698 })??
7699 .await?;
7700
7701 let mut documentation_is_markdown = false;
7702 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
7703 let documentation = match completion.documentation {
7704 Some(lsp::Documentation::String(text)) => text,
7705
7706 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7707 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
7708 value
7709 }
7710
7711 _ => String::new(),
7712 };
7713
7714 // If we have a new buffer_id, that means we're talking to a new client
7715 // and want to check for new text_edits in the completion too.
7716 let mut old_start = None;
7717 let mut old_end = None;
7718 let mut new_text = String::default();
7719 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
7720 let buffer_snapshot = this.update(&mut cx, |this, cx| {
7721 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7722 anyhow::Ok(buffer.read(cx).snapshot())
7723 })??;
7724
7725 if let Some(text_edit) = completion.text_edit.as_ref() {
7726 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
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}