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
2638 lsp_edits.sort_by_key(|(range, _)| (range.start, range.end));
2639
2640 let mut lsp_edits = lsp_edits.into_iter().peekable();
2641 let mut edits = Vec::new();
2642 while let Some((range, mut new_text)) = lsp_edits.next() {
2643 // Clip invalid ranges provided by the language server.
2644 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
2645 ..snapshot.clip_point_utf16(range.end, Bias::Left);
2646
2647 // Combine any LSP edits that are adjacent.
2648 //
2649 // Also, combine LSP edits that are separated from each other by only
2650 // a newline. This is important because for some code actions,
2651 // Rust-analyzer rewrites the entire buffer via a series of edits that
2652 // are separated by unchanged newline characters.
2653 //
2654 // In order for the diffing logic below to work properly, any edits that
2655 // cancel each other out must be combined into one.
2656 while let Some((next_range, next_text)) = lsp_edits.peek() {
2657 if next_range.start.0 > range.end {
2658 if next_range.start.0.row > range.end.row + 1
2659 || next_range.start.0.column > 0
2660 || snapshot.clip_point_utf16(
2661 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
2662 Bias::Left,
2663 ) > range.end
2664 {
2665 break;
2666 }
2667 new_text.push('\n');
2668 }
2669 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
2670 new_text.push_str(next_text);
2671 lsp_edits.next();
2672 }
2673
2674 // For multiline edits, perform a diff of the old and new text so that
2675 // we can identify the changes more precisely, preserving the locations
2676 // of any anchors positioned in the unchanged regions.
2677 if range.end.row > range.start.row {
2678 let offset = range.start.to_offset(&snapshot);
2679 let old_text = snapshot.text_for_range(range).collect::<String>();
2680 let range_edits = language::text_diff(old_text.as_str(), &new_text);
2681 edits.extend(range_edits.into_iter().map(|(range, replacement)| {
2682 (
2683 snapshot.anchor_after(offset + range.start)
2684 ..snapshot.anchor_before(offset + range.end),
2685 replacement,
2686 )
2687 }));
2688 } else if range.end == range.start {
2689 let anchor = snapshot.anchor_after(range.start);
2690 edits.push((anchor..anchor, new_text.into()));
2691 } else {
2692 let edit_start = snapshot.anchor_after(range.start);
2693 let edit_end = snapshot.anchor_before(range.end);
2694 edits.push((edit_start..edit_end, new_text.into()));
2695 }
2696 }
2697
2698 Ok(edits)
2699 })
2700 }
2701
2702 pub(crate) async fn deserialize_workspace_edit(
2703 this: Entity<LspStore>,
2704 edit: lsp::WorkspaceEdit,
2705 push_to_history: bool,
2706 lsp_adapter: Arc<CachedLspAdapter>,
2707 language_server: Arc<LanguageServer>,
2708 cx: &mut AsyncApp,
2709 ) -> Result<ProjectTransaction> {
2710 let fs = this.read_with(cx, |this, _| this.as_local().unwrap().fs.clone())?;
2711
2712 let mut operations = Vec::new();
2713 if let Some(document_changes) = edit.document_changes {
2714 match document_changes {
2715 lsp::DocumentChanges::Edits(edits) => {
2716 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2717 }
2718 lsp::DocumentChanges::Operations(ops) => operations = ops,
2719 }
2720 } else if let Some(changes) = edit.changes {
2721 operations.extend(changes.into_iter().map(|(uri, edits)| {
2722 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2723 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2724 uri,
2725 version: None,
2726 },
2727 edits: edits.into_iter().map(Edit::Plain).collect(),
2728 })
2729 }));
2730 }
2731
2732 let mut project_transaction = ProjectTransaction::default();
2733 for operation in operations {
2734 match operation {
2735 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2736 let abs_path = op
2737 .uri
2738 .to_file_path()
2739 .map_err(|_| anyhow!("can't convert URI to path"))?;
2740
2741 if let Some(parent_path) = abs_path.parent() {
2742 fs.create_dir(parent_path).await?;
2743 }
2744 if abs_path.ends_with("/") {
2745 fs.create_dir(&abs_path).await?;
2746 } else {
2747 fs.create_file(
2748 &abs_path,
2749 op.options
2750 .map(|options| fs::CreateOptions {
2751 overwrite: options.overwrite.unwrap_or(false),
2752 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2753 })
2754 .unwrap_or_default(),
2755 )
2756 .await?;
2757 }
2758 }
2759
2760 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2761 let source_abs_path = op
2762 .old_uri
2763 .to_file_path()
2764 .map_err(|_| anyhow!("can't convert URI to path"))?;
2765 let target_abs_path = op
2766 .new_uri
2767 .to_file_path()
2768 .map_err(|_| anyhow!("can't convert URI to path"))?;
2769 fs.rename(
2770 &source_abs_path,
2771 &target_abs_path,
2772 op.options
2773 .map(|options| fs::RenameOptions {
2774 overwrite: options.overwrite.unwrap_or(false),
2775 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2776 })
2777 .unwrap_or_default(),
2778 )
2779 .await?;
2780 }
2781
2782 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2783 let abs_path = op
2784 .uri
2785 .to_file_path()
2786 .map_err(|_| anyhow!("can't convert URI to path"))?;
2787 let options = op
2788 .options
2789 .map(|options| fs::RemoveOptions {
2790 recursive: options.recursive.unwrap_or(false),
2791 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2792 })
2793 .unwrap_or_default();
2794 if abs_path.ends_with("/") {
2795 fs.remove_dir(&abs_path, options).await?;
2796 } else {
2797 fs.remove_file(&abs_path, options).await?;
2798 }
2799 }
2800
2801 lsp::DocumentChangeOperation::Edit(op) => {
2802 let buffer_to_edit = this
2803 .update(cx, |this, cx| {
2804 this.open_local_buffer_via_lsp(
2805 op.text_document.uri.clone(),
2806 language_server.server_id(),
2807 lsp_adapter.name.clone(),
2808 cx,
2809 )
2810 })?
2811 .await?;
2812
2813 let edits = this
2814 .update(cx, |this, cx| {
2815 let path = buffer_to_edit.read(cx).project_path(cx);
2816 let active_entry = this.active_entry;
2817 let is_active_entry = path.clone().map_or(false, |project_path| {
2818 this.worktree_store
2819 .read(cx)
2820 .entry_for_path(&project_path, cx)
2821 .map_or(false, |entry| Some(entry.id) == active_entry)
2822 });
2823 let local = this.as_local_mut().unwrap();
2824
2825 let (mut edits, mut snippet_edits) = (vec![], vec![]);
2826 for edit in op.edits {
2827 match edit {
2828 Edit::Plain(edit) => {
2829 if !edits.contains(&edit) {
2830 edits.push(edit)
2831 }
2832 }
2833 Edit::Annotated(edit) => {
2834 if !edits.contains(&edit.text_edit) {
2835 edits.push(edit.text_edit)
2836 }
2837 }
2838 Edit::Snippet(edit) => {
2839 let Ok(snippet) = Snippet::parse(&edit.snippet.value)
2840 else {
2841 continue;
2842 };
2843
2844 if is_active_entry {
2845 snippet_edits.push((edit.range, snippet));
2846 } else {
2847 // Since this buffer is not focused, apply a normal edit.
2848 let new_edit = TextEdit {
2849 range: edit.range,
2850 new_text: snippet.text,
2851 };
2852 if !edits.contains(&new_edit) {
2853 edits.push(new_edit);
2854 }
2855 }
2856 }
2857 }
2858 }
2859 if !snippet_edits.is_empty() {
2860 let buffer_id = buffer_to_edit.read(cx).remote_id();
2861 let version = if let Some(buffer_version) = op.text_document.version
2862 {
2863 local
2864 .buffer_snapshot_for_lsp_version(
2865 &buffer_to_edit,
2866 language_server.server_id(),
2867 Some(buffer_version),
2868 cx,
2869 )
2870 .ok()
2871 .map(|snapshot| snapshot.version)
2872 } else {
2873 Some(buffer_to_edit.read(cx).saved_version().clone())
2874 };
2875
2876 let most_recent_edit = version.and_then(|version| {
2877 version.iter().max_by_key(|timestamp| timestamp.value)
2878 });
2879 // Check if the edit that triggered that edit has been made by this participant.
2880
2881 if let Some(most_recent_edit) = most_recent_edit {
2882 cx.emit(LspStoreEvent::SnippetEdit {
2883 buffer_id,
2884 edits: snippet_edits,
2885 most_recent_edit,
2886 });
2887 }
2888 }
2889
2890 local.edits_from_lsp(
2891 &buffer_to_edit,
2892 edits,
2893 language_server.server_id(),
2894 op.text_document.version,
2895 cx,
2896 )
2897 })?
2898 .await?;
2899
2900 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2901 buffer.finalize_last_transaction();
2902 buffer.start_transaction();
2903 for (range, text) in edits {
2904 buffer.edit([(range, text)], None, cx);
2905 }
2906 let transaction = if buffer.end_transaction(cx).is_some() {
2907 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2908 if !push_to_history {
2909 buffer.forget_transaction(transaction.id);
2910 }
2911 Some(transaction)
2912 } else {
2913 None
2914 };
2915
2916 transaction
2917 })?;
2918 if let Some(transaction) = transaction {
2919 project_transaction.0.insert(buffer_to_edit, transaction);
2920 }
2921 }
2922 }
2923 }
2924
2925 Ok(project_transaction)
2926 }
2927
2928 async fn on_lsp_workspace_edit(
2929 this: WeakEntity<LspStore>,
2930 params: lsp::ApplyWorkspaceEditParams,
2931 server_id: LanguageServerId,
2932 adapter: Arc<CachedLspAdapter>,
2933 cx: &mut AsyncApp,
2934 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2935 let this = this
2936 .upgrade()
2937 .ok_or_else(|| anyhow!("project project closed"))?;
2938 let language_server = this
2939 .update(cx, |this, _| this.language_server_for_id(server_id))?
2940 .ok_or_else(|| anyhow!("language server not found"))?;
2941 let transaction = Self::deserialize_workspace_edit(
2942 this.clone(),
2943 params.edit,
2944 true,
2945 adapter.clone(),
2946 language_server.clone(),
2947 cx,
2948 )
2949 .await
2950 .log_err();
2951 this.update(cx, |this, _| {
2952 if let Some(transaction) = transaction {
2953 this.as_local_mut()
2954 .unwrap()
2955 .last_workspace_edits_by_language_server
2956 .insert(server_id, transaction);
2957 }
2958 })?;
2959 Ok(lsp::ApplyWorkspaceEditResponse {
2960 applied: true,
2961 failed_change: None,
2962 failure_reason: None,
2963 })
2964 }
2965
2966 fn remove_worktree(
2967 &mut self,
2968 id_to_remove: WorktreeId,
2969 cx: &mut Context<LspStore>,
2970 ) -> Vec<LanguageServerId> {
2971 self.diagnostics.remove(&id_to_remove);
2972 self.prettier_store.update(cx, |prettier_store, cx| {
2973 prettier_store.remove_worktree(id_to_remove, cx);
2974 });
2975
2976 let mut servers_to_remove = BTreeMap::default();
2977 let mut servers_to_preserve = HashSet::default();
2978 for ((path, server_name), ref server_ids) in &self.language_server_ids {
2979 if *path == id_to_remove {
2980 servers_to_remove.extend(server_ids.iter().map(|id| (*id, server_name.clone())));
2981 } else {
2982 servers_to_preserve.extend(server_ids.iter().cloned());
2983 }
2984 }
2985 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
2986
2987 for (server_id_to_remove, _) in &servers_to_remove {
2988 self.language_server_ids
2989 .values_mut()
2990 .for_each(|server_ids| {
2991 server_ids.remove(server_id_to_remove);
2992 });
2993 self.language_server_watched_paths
2994 .remove(&server_id_to_remove);
2995 self.language_server_paths_watched_for_rename
2996 .remove(&server_id_to_remove);
2997 self.last_workspace_edits_by_language_server
2998 .remove(&server_id_to_remove);
2999 self.language_servers.remove(&server_id_to_remove);
3000 cx.emit(LspStoreEvent::LanguageServerRemoved(*server_id_to_remove));
3001 }
3002 servers_to_remove.into_keys().collect()
3003 }
3004
3005 fn rebuild_watched_paths_inner<'a>(
3006 &'a self,
3007 language_server_id: LanguageServerId,
3008 watchers: impl Iterator<Item = &'a FileSystemWatcher>,
3009 cx: &mut Context<LspStore>,
3010 ) -> LanguageServerWatchedPathsBuilder {
3011 let worktrees = self
3012 .worktree_store
3013 .read(cx)
3014 .worktrees()
3015 .filter_map(|worktree| {
3016 self.language_servers_for_worktree(worktree.read(cx).id())
3017 .find(|server| server.server_id() == language_server_id)
3018 .map(|_| worktree)
3019 })
3020 .collect::<Vec<_>>();
3021
3022 let mut worktree_globs = HashMap::default();
3023 let mut abs_globs = HashMap::default();
3024 log::trace!(
3025 "Processing new watcher paths for language server with id {}",
3026 language_server_id
3027 );
3028
3029 enum PathToWatch {
3030 Worktree {
3031 literal_prefix: Arc<Path>,
3032 pattern: String,
3033 },
3034 Absolute {
3035 path: Arc<Path>,
3036 pattern: String,
3037 },
3038 }
3039 for watcher in watchers {
3040 let mut found_host = false;
3041 for worktree in &worktrees {
3042 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3043 let worktree_root_path = tree.abs_path();
3044 let path_to_watch = match &watcher.glob_pattern {
3045 lsp::GlobPattern::String(s) => {
3046 let watcher_path = SanitizedPath::from(s);
3047 match watcher_path.as_path().strip_prefix(&worktree_root_path) {
3048 Ok(relative) => {
3049 let pattern = relative.to_string_lossy().to_string();
3050 let literal_prefix = glob_literal_prefix(relative).into();
3051
3052 PathToWatch::Worktree {
3053 literal_prefix,
3054 pattern,
3055 }
3056 }
3057 Err(_) => {
3058 let path = glob_literal_prefix(watcher_path.as_path());
3059 let pattern = watcher_path
3060 .as_path()
3061 .strip_prefix(&path)
3062 .map(|p| p.to_string_lossy().to_string())
3063 .unwrap_or_else(|e| {
3064 debug_panic!(
3065 "Failed to strip prefix for string pattern: {}, with prefix: {}, with error: {}",
3066 s,
3067 path.display(),
3068 e
3069 );
3070 watcher_path.as_path().to_string_lossy().to_string()
3071 });
3072 let path = if path.components().next().is_none() {
3073 worktree_root_path.clone()
3074 } else {
3075 path.into()
3076 };
3077
3078 PathToWatch::Absolute { path, pattern }
3079 }
3080 }
3081 }
3082 lsp::GlobPattern::Relative(rp) => {
3083 let Ok(mut base_uri) = match &rp.base_uri {
3084 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3085 lsp::OneOf::Right(base_uri) => base_uri,
3086 }
3087 .to_file_path() else {
3088 return false;
3089 };
3090
3091 match base_uri.strip_prefix(&worktree_root_path) {
3092 Ok(relative) => {
3093 let mut literal_prefix = relative.to_owned();
3094 literal_prefix
3095 .push(glob_literal_prefix(Path::new(&rp.pattern)));
3096
3097 PathToWatch::Worktree {
3098 literal_prefix: literal_prefix.into(),
3099 pattern: rp.pattern.clone(),
3100 }
3101 }
3102 Err(_) => {
3103 let path = glob_literal_prefix(Path::new(&rp.pattern));
3104 let pattern = Path::new(&rp.pattern)
3105 .strip_prefix(&path)
3106 .map(|p| p.to_string_lossy().to_string())
3107 .unwrap_or_else(|e| {
3108 debug_panic!(
3109 "Failed to strip prefix for relative pattern: {}, with prefix: {}, with error: {}",
3110 rp.pattern,
3111 path.display(),
3112 e
3113 );
3114 rp.pattern.clone()
3115 });
3116 base_uri.push(path);
3117
3118 let path = if base_uri.components().next().is_none() {
3119 debug_panic!("base_uri is empty, {}", base_uri.display());
3120 worktree_root_path.clone()
3121 } else {
3122 base_uri.into()
3123 };
3124 PathToWatch::Absolute { path, pattern }
3125 }
3126 }
3127 }
3128 };
3129 match path_to_watch {
3130 PathToWatch::Worktree {
3131 literal_prefix,
3132 pattern,
3133 } => {
3134 if let Some((tree, glob)) =
3135 tree.as_local_mut().zip(Glob::new(&pattern).log_err())
3136 {
3137 tree.add_path_prefix_to_scan(literal_prefix);
3138 worktree_globs
3139 .entry(tree.id())
3140 .or_insert_with(GlobSetBuilder::new)
3141 .add(glob);
3142 } else {
3143 return false;
3144 }
3145 }
3146 PathToWatch::Absolute { path, pattern } => {
3147 if let Some(glob) = Glob::new(&pattern).log_err() {
3148 abs_globs
3149 .entry(path)
3150 .or_insert_with(GlobSetBuilder::new)
3151 .add(glob);
3152 }
3153 }
3154 }
3155 true
3156 });
3157 if glob_is_inside_worktree {
3158 log::trace!(
3159 "Watcher pattern `{}` has been attached to the worktree at `{}`",
3160 serde_json::to_string(&watcher.glob_pattern).unwrap(),
3161 worktree.read(cx).abs_path().display()
3162 );
3163 found_host = true;
3164 }
3165 }
3166 if !found_host {
3167 log::error!(
3168 "Watcher pattern `{}` has not been attached to any worktree or absolute path",
3169 serde_json::to_string(&watcher.glob_pattern).unwrap()
3170 )
3171 }
3172 }
3173
3174 let mut watch_builder = LanguageServerWatchedPathsBuilder::default();
3175 for (worktree_id, builder) in worktree_globs {
3176 if let Ok(globset) = builder.build() {
3177 watch_builder.watch_worktree(worktree_id, globset);
3178 }
3179 }
3180 for (abs_path, builder) in abs_globs {
3181 if let Ok(globset) = builder.build() {
3182 watch_builder.watch_abs_path(abs_path, globset);
3183 }
3184 }
3185 watch_builder
3186 }
3187
3188 fn rebuild_watched_paths(
3189 &mut self,
3190 language_server_id: LanguageServerId,
3191 cx: &mut Context<LspStore>,
3192 ) {
3193 let Some(watchers) = self
3194 .language_server_watcher_registrations
3195 .get(&language_server_id)
3196 else {
3197 return;
3198 };
3199
3200 let watch_builder =
3201 self.rebuild_watched_paths_inner(language_server_id, watchers.values().flatten(), cx);
3202 let watcher = watch_builder.build(self.fs.clone(), language_server_id, cx);
3203 self.language_server_watched_paths
3204 .insert(language_server_id, watcher);
3205
3206 cx.notify();
3207 }
3208
3209 fn on_lsp_did_change_watched_files(
3210 &mut self,
3211 language_server_id: LanguageServerId,
3212 registration_id: &str,
3213 params: DidChangeWatchedFilesRegistrationOptions,
3214 cx: &mut Context<LspStore>,
3215 ) {
3216 let registrations = self
3217 .language_server_watcher_registrations
3218 .entry(language_server_id)
3219 .or_default();
3220
3221 registrations.insert(registration_id.to_string(), params.watchers);
3222
3223 self.rebuild_watched_paths(language_server_id, cx);
3224 }
3225
3226 fn on_lsp_unregister_did_change_watched_files(
3227 &mut self,
3228 language_server_id: LanguageServerId,
3229 registration_id: &str,
3230 cx: &mut Context<LspStore>,
3231 ) {
3232 let registrations = self
3233 .language_server_watcher_registrations
3234 .entry(language_server_id)
3235 .or_default();
3236
3237 if registrations.remove(registration_id).is_some() {
3238 log::info!(
3239 "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
3240 language_server_id,
3241 registration_id
3242 );
3243 } else {
3244 log::warn!(
3245 "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
3246 language_server_id,
3247 registration_id
3248 );
3249 }
3250
3251 self.rebuild_watched_paths(language_server_id, cx);
3252 }
3253
3254 async fn initialization_options_for_adapter(
3255 adapter: Arc<dyn LspAdapter>,
3256 fs: &dyn Fs,
3257 delegate: &Arc<dyn LspAdapterDelegate>,
3258 ) -> Result<Option<serde_json::Value>> {
3259 let Some(mut initialization_config) =
3260 adapter.clone().initialization_options(fs, delegate).await?
3261 else {
3262 return Ok(None);
3263 };
3264
3265 for other_adapter in delegate.registered_lsp_adapters() {
3266 if other_adapter.name() == adapter.name() {
3267 continue;
3268 }
3269 if let Ok(Some(target_config)) = other_adapter
3270 .clone()
3271 .additional_initialization_options(adapter.name(), fs, delegate)
3272 .await
3273 {
3274 merge_json_value_into(target_config.clone(), &mut initialization_config);
3275 }
3276 }
3277
3278 Ok(Some(initialization_config))
3279 }
3280
3281 async fn workspace_configuration_for_adapter(
3282 adapter: Arc<dyn LspAdapter>,
3283 fs: &dyn Fs,
3284 delegate: &Arc<dyn LspAdapterDelegate>,
3285 toolchains: Arc<dyn LanguageToolchainStore>,
3286 cx: &mut AsyncApp,
3287 ) -> Result<serde_json::Value> {
3288 let mut workspace_config = adapter
3289 .clone()
3290 .workspace_configuration(fs, delegate, toolchains.clone(), cx)
3291 .await?;
3292
3293 for other_adapter in delegate.registered_lsp_adapters() {
3294 if other_adapter.name() == adapter.name() {
3295 continue;
3296 }
3297 if let Ok(Some(target_config)) = other_adapter
3298 .clone()
3299 .additional_workspace_configuration(
3300 adapter.name(),
3301 fs,
3302 delegate,
3303 toolchains.clone(),
3304 cx,
3305 )
3306 .await
3307 {
3308 merge_json_value_into(target_config.clone(), &mut workspace_config);
3309 }
3310 }
3311
3312 Ok(workspace_config)
3313 }
3314}
3315
3316#[derive(Debug)]
3317pub struct FormattableBuffer {
3318 handle: Entity<Buffer>,
3319 abs_path: Option<PathBuf>,
3320 env: Option<HashMap<String, String>>,
3321 ranges: Option<Vec<Range<Anchor>>>,
3322}
3323
3324pub struct RemoteLspStore {
3325 upstream_client: Option<AnyProtoClient>,
3326 upstream_project_id: u64,
3327}
3328
3329#[allow(clippy::large_enum_variant)]
3330pub(crate) enum LspStoreMode {
3331 Local(LocalLspStore), // ssh host and collab host
3332 Remote(RemoteLspStore), // collab guest
3333}
3334
3335impl LspStoreMode {
3336 fn is_local(&self) -> bool {
3337 matches!(self, LspStoreMode::Local(_))
3338 }
3339}
3340
3341pub struct LspStore {
3342 mode: LspStoreMode,
3343 last_formatting_failure: Option<String>,
3344 downstream_client: Option<(AnyProtoClient, u64)>,
3345 nonce: u128,
3346 buffer_store: Entity<BufferStore>,
3347 worktree_store: Entity<WorktreeStore>,
3348 toolchain_store: Option<Entity<ToolchainStore>>,
3349 pub languages: Arc<LanguageRegistry>,
3350 pub language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
3351 active_entry: Option<ProjectEntryId>,
3352 _maintain_workspace_config: (Task<Result<()>>, watch::Sender<()>),
3353 _maintain_buffer_languages: Task<()>,
3354 diagnostic_summaries:
3355 HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
3356}
3357
3358pub enum LspStoreEvent {
3359 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3360 LanguageServerRemoved(LanguageServerId),
3361 LanguageServerUpdate {
3362 language_server_id: LanguageServerId,
3363 message: proto::update_language_server::Variant,
3364 },
3365 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3366 LanguageServerPrompt(LanguageServerPromptRequest),
3367 LanguageDetected {
3368 buffer: Entity<Buffer>,
3369 new_language: Option<Arc<Language>>,
3370 },
3371 Notification(String),
3372 RefreshInlayHints,
3373 RefreshCodeLens,
3374 DiagnosticsUpdated {
3375 language_server_id: LanguageServerId,
3376 path: ProjectPath,
3377 },
3378 DiskBasedDiagnosticsStarted {
3379 language_server_id: LanguageServerId,
3380 },
3381 DiskBasedDiagnosticsFinished {
3382 language_server_id: LanguageServerId,
3383 },
3384 SnippetEdit {
3385 buffer_id: BufferId,
3386 edits: Vec<(lsp::Range, Snippet)>,
3387 most_recent_edit: clock::Lamport,
3388 },
3389}
3390
3391#[derive(Clone, Debug, Serialize)]
3392pub struct LanguageServerStatus {
3393 pub name: String,
3394 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3395 pub has_pending_diagnostic_updates: bool,
3396 progress_tokens: HashSet<String>,
3397}
3398
3399#[derive(Clone, Debug)]
3400struct CoreSymbol {
3401 pub language_server_name: LanguageServerName,
3402 pub source_worktree_id: WorktreeId,
3403 pub source_language_server_id: LanguageServerId,
3404 pub path: ProjectPath,
3405 pub name: String,
3406 pub kind: lsp::SymbolKind,
3407 pub range: Range<Unclipped<PointUtf16>>,
3408 pub signature: [u8; 32],
3409}
3410
3411impl LspStore {
3412 pub fn init(client: &AnyProtoClient) {
3413 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3414 client.add_entity_request_handler(Self::handle_restart_language_servers);
3415 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3416 client.add_entity_message_handler(Self::handle_start_language_server);
3417 client.add_entity_message_handler(Self::handle_update_language_server);
3418 client.add_entity_message_handler(Self::handle_language_server_log);
3419 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3420 client.add_entity_request_handler(Self::handle_format_buffers);
3421 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3422 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3423 client.add_entity_request_handler(Self::handle_apply_code_action);
3424 client.add_entity_request_handler(Self::handle_inlay_hints);
3425 client.add_entity_request_handler(Self::handle_get_project_symbols);
3426 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3427 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3428 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3429 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3430 client.add_entity_request_handler(Self::handle_on_type_formatting);
3431 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3432 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3433 client.add_entity_request_handler(Self::handle_rename_project_entry);
3434 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3435 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3436 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3437 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3438 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3439 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3440 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3441 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3442 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3443 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3444 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3445 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3446 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3447
3448 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3449 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3450 client.add_entity_request_handler(
3451 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3452 );
3453 }
3454
3455 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3456 match &self.mode {
3457 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3458 _ => None,
3459 }
3460 }
3461
3462 pub fn as_local(&self) -> Option<&LocalLspStore> {
3463 match &self.mode {
3464 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3465 _ => None,
3466 }
3467 }
3468
3469 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3470 match &mut self.mode {
3471 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3472 _ => None,
3473 }
3474 }
3475
3476 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3477 match &self.mode {
3478 LspStoreMode::Remote(RemoteLspStore {
3479 upstream_client: Some(upstream_client),
3480 upstream_project_id,
3481 ..
3482 }) => Some((upstream_client.clone(), *upstream_project_id)),
3483
3484 LspStoreMode::Remote(RemoteLspStore {
3485 upstream_client: None,
3486 ..
3487 }) => None,
3488 LspStoreMode::Local(_) => None,
3489 }
3490 }
3491
3492 pub fn new_local(
3493 buffer_store: Entity<BufferStore>,
3494 worktree_store: Entity<WorktreeStore>,
3495 prettier_store: Entity<PrettierStore>,
3496 toolchain_store: Entity<ToolchainStore>,
3497 environment: Entity<ProjectEnvironment>,
3498 languages: Arc<LanguageRegistry>,
3499 http_client: Arc<dyn HttpClient>,
3500 fs: Arc<dyn Fs>,
3501 cx: &mut Context<Self>,
3502 ) -> Self {
3503 let yarn = YarnPathStore::new(fs.clone(), cx);
3504 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3505 .detach();
3506 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3507 .detach();
3508 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3509 .detach();
3510 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3511 .detach();
3512 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3513 cx.subscribe(
3514 extension_events,
3515 Self::reload_zed_json_schemas_on_extensions_changed,
3516 )
3517 .detach();
3518 } else {
3519 log::info!("No extension events global found. Skipping JSON schema auto-reload setup");
3520 }
3521 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3522 .detach();
3523
3524 let _maintain_workspace_config = {
3525 let (sender, receiver) = watch::channel();
3526 (
3527 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3528 sender,
3529 )
3530 };
3531 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
3532 Self {
3533 mode: LspStoreMode::Local(LocalLspStore {
3534 weak: cx.weak_entity(),
3535 worktree_store: worktree_store.clone(),
3536 toolchain_store: toolchain_store.clone(),
3537 supplementary_language_servers: Default::default(),
3538 languages: languages.clone(),
3539 language_server_ids: Default::default(),
3540 language_servers: Default::default(),
3541 last_workspace_edits_by_language_server: Default::default(),
3542 language_server_watched_paths: Default::default(),
3543 language_server_paths_watched_for_rename: Default::default(),
3544 language_server_watcher_registrations: Default::default(),
3545 buffers_being_formatted: Default::default(),
3546 buffer_snapshots: Default::default(),
3547 prettier_store,
3548 environment,
3549 http_client,
3550 fs,
3551 yarn,
3552 next_diagnostic_group_id: Default::default(),
3553 diagnostics: Default::default(),
3554 _subscription: cx.on_app_quit(|this, cx| {
3555 this.as_local_mut().unwrap().shutdown_language_servers(cx)
3556 }),
3557 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3558 registered_buffers: Default::default(),
3559 }),
3560 last_formatting_failure: None,
3561 downstream_client: None,
3562 buffer_store,
3563 worktree_store,
3564 toolchain_store: Some(toolchain_store),
3565 languages: languages.clone(),
3566 language_server_statuses: Default::default(),
3567 nonce: StdRng::from_entropy().r#gen(),
3568 diagnostic_summaries: Default::default(),
3569 active_entry: None,
3570
3571 _maintain_workspace_config,
3572 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3573 }
3574 }
3575
3576 fn send_lsp_proto_request<R: LspCommand>(
3577 &self,
3578 buffer: Entity<Buffer>,
3579 client: AnyProtoClient,
3580 upstream_project_id: u64,
3581 request: R,
3582 cx: &mut Context<LspStore>,
3583 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3584 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3585 cx.spawn(async move |this, cx| {
3586 let response = client.request(message).await?;
3587 let this = this.upgrade().context("project dropped")?;
3588 request
3589 .response_from_proto(response, this, buffer, cx.clone())
3590 .await
3591 })
3592 }
3593
3594 pub(super) fn new_remote(
3595 buffer_store: Entity<BufferStore>,
3596 worktree_store: Entity<WorktreeStore>,
3597 toolchain_store: Option<Entity<ToolchainStore>>,
3598 languages: Arc<LanguageRegistry>,
3599 upstream_client: AnyProtoClient,
3600 project_id: u64,
3601 fs: Arc<dyn Fs>,
3602 cx: &mut Context<Self>,
3603 ) -> Self {
3604 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3605 .detach();
3606 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3607 .detach();
3608 let _maintain_workspace_config = {
3609 let (sender, receiver) = watch::channel();
3610 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3611 };
3612 Self {
3613 mode: LspStoreMode::Remote(RemoteLspStore {
3614 upstream_client: Some(upstream_client),
3615 upstream_project_id: project_id,
3616 }),
3617 downstream_client: None,
3618 last_formatting_failure: None,
3619 buffer_store,
3620 worktree_store,
3621 languages: languages.clone(),
3622 language_server_statuses: Default::default(),
3623 nonce: StdRng::from_entropy().r#gen(),
3624 diagnostic_summaries: Default::default(),
3625 active_entry: None,
3626 toolchain_store,
3627 _maintain_workspace_config,
3628 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3629 }
3630 }
3631
3632 fn on_buffer_store_event(
3633 &mut self,
3634 _: Entity<BufferStore>,
3635 event: &BufferStoreEvent,
3636 cx: &mut Context<Self>,
3637 ) {
3638 match event {
3639 BufferStoreEvent::BufferAdded(buffer) => {
3640 self.on_buffer_added(buffer, cx).log_err();
3641 }
3642 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3643 let buffer_id = buffer.read(cx).remote_id();
3644 if let Some(local) = self.as_local_mut() {
3645 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3646 local.reset_buffer(buffer, old_file, cx);
3647
3648 if local.registered_buffers.contains_key(&buffer_id) {
3649 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3650 }
3651 }
3652 }
3653
3654 self.detect_language_for_buffer(buffer, cx);
3655 if let Some(local) = self.as_local_mut() {
3656 local.initialize_buffer(buffer, cx);
3657 if local.registered_buffers.contains_key(&buffer_id) {
3658 local.register_buffer_with_language_servers(buffer, cx);
3659 }
3660 }
3661 }
3662 _ => {}
3663 }
3664 }
3665
3666 fn on_worktree_store_event(
3667 &mut self,
3668 _: Entity<WorktreeStore>,
3669 event: &WorktreeStoreEvent,
3670 cx: &mut Context<Self>,
3671 ) {
3672 match event {
3673 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3674 if !worktree.read(cx).is_local() {
3675 return;
3676 }
3677 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3678 worktree::Event::UpdatedEntries(changes) => {
3679 this.update_local_worktree_language_servers(&worktree, changes, cx);
3680 }
3681 worktree::Event::UpdatedGitRepositories(_)
3682 | worktree::Event::DeletedEntry(_) => {}
3683 })
3684 .detach()
3685 }
3686 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3687 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3688 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3689 }
3690 WorktreeStoreEvent::WorktreeReleased(..)
3691 | WorktreeStoreEvent::WorktreeOrderChanged
3692 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3693 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3694 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3695 }
3696 }
3697
3698 fn on_prettier_store_event(
3699 &mut self,
3700 _: Entity<PrettierStore>,
3701 event: &PrettierStoreEvent,
3702 cx: &mut Context<Self>,
3703 ) {
3704 match event {
3705 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3706 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3707 }
3708 PrettierStoreEvent::LanguageServerAdded {
3709 new_server_id,
3710 name,
3711 prettier_server,
3712 } => {
3713 self.register_supplementary_language_server(
3714 *new_server_id,
3715 name.clone(),
3716 prettier_server.clone(),
3717 cx,
3718 );
3719 }
3720 }
3721 }
3722
3723 fn on_toolchain_store_event(
3724 &mut self,
3725 _: Entity<ToolchainStore>,
3726 event: &ToolchainStoreEvent,
3727 _: &mut Context<Self>,
3728 ) {
3729 match event {
3730 ToolchainStoreEvent::ToolchainActivated { .. } => {
3731 self.request_workspace_config_refresh()
3732 }
3733 }
3734 }
3735
3736 fn request_workspace_config_refresh(&mut self) {
3737 *self._maintain_workspace_config.1.borrow_mut() = ();
3738 }
3739
3740 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3741 self.as_local().map(|local| local.prettier_store.clone())
3742 }
3743
3744 fn on_buffer_event(
3745 &mut self,
3746 buffer: Entity<Buffer>,
3747 event: &language::BufferEvent,
3748 cx: &mut Context<Self>,
3749 ) {
3750 match event {
3751 language::BufferEvent::Edited { .. } => {
3752 self.on_buffer_edited(buffer, cx);
3753 }
3754
3755 language::BufferEvent::Saved => {
3756 self.on_buffer_saved(buffer, cx);
3757 }
3758
3759 _ => {}
3760 }
3761 }
3762
3763 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3764 buffer.update(cx, |buffer, _| {
3765 buffer.set_language_registry(self.languages.clone())
3766 });
3767
3768 cx.subscribe(buffer, |this, buffer, event, cx| {
3769 this.on_buffer_event(buffer, event, cx);
3770 })
3771 .detach();
3772
3773 self.detect_language_for_buffer(buffer, cx);
3774 if let Some(local) = self.as_local_mut() {
3775 local.initialize_buffer(buffer, cx);
3776 }
3777
3778 Ok(())
3779 }
3780
3781 pub fn reload_zed_json_schemas_on_extensions_changed(
3782 &mut self,
3783 _: Entity<extension::ExtensionEvents>,
3784 evt: &extension::Event,
3785 cx: &mut Context<Self>,
3786 ) {
3787 #[expect(
3788 irrefutable_let_patterns,
3789 reason = "Make sure to handle new event types in extension properly"
3790 )]
3791 let extension::Event::ExtensionsInstalledChanged = evt else {
3792 return;
3793 };
3794 if self.as_local().is_none() {
3795 return;
3796 }
3797 cx.spawn(async move |this, cx| {
3798 let weak_ref = this.clone();
3799
3800 let servers = this
3801 .update(cx, |this, cx| {
3802 let local = this.as_local()?;
3803
3804 let mut servers = Vec::new();
3805 for ((worktree_id, _), server_ids) in &local.language_server_ids {
3806 for server_id in server_ids {
3807 let Some(states) = local.language_servers.get(server_id) else {
3808 continue;
3809 };
3810 let (json_adapter, json_server) = match states {
3811 LanguageServerState::Running {
3812 adapter, server, ..
3813 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
3814 (adapter.adapter.clone(), server.clone())
3815 }
3816 _ => continue,
3817 };
3818
3819 let Some(worktree) = this
3820 .worktree_store
3821 .read(cx)
3822 .worktree_for_id(*worktree_id, cx)
3823 else {
3824 continue;
3825 };
3826 let json_delegate: Arc<dyn LspAdapterDelegate> =
3827 LocalLspAdapterDelegate::new(
3828 local.languages.clone(),
3829 &local.environment,
3830 weak_ref.clone(),
3831 &worktree,
3832 local.http_client.clone(),
3833 local.fs.clone(),
3834 cx,
3835 );
3836
3837 servers.push((json_adapter, json_server, json_delegate));
3838 }
3839 }
3840 return Some(servers);
3841 })
3842 .ok()
3843 .flatten();
3844
3845 let Some(servers) = servers else {
3846 return;
3847 };
3848
3849 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
3850 let local = this.as_local()?;
3851 let toolchain_store = this.toolchain_store(cx);
3852 return Some((local.fs.clone(), toolchain_store));
3853 }) else {
3854 return;
3855 };
3856 for (adapter, server, delegate) in servers {
3857 adapter.clear_zed_json_schema_cache().await;
3858
3859 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
3860 adapter,
3861 fs.as_ref(),
3862 &delegate,
3863 toolchain_store.clone(),
3864 cx,
3865 )
3866 .await
3867 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
3868 .ok()
3869 else {
3870 continue;
3871 };
3872 server
3873 .notify::<lsp::notification::DidChangeConfiguration>(
3874 &lsp::DidChangeConfigurationParams {
3875 settings: json_workspace_config,
3876 },
3877 )
3878 .ok();
3879 }
3880 })
3881 .detach();
3882 }
3883
3884 pub(crate) fn register_buffer_with_language_servers(
3885 &mut self,
3886 buffer: &Entity<Buffer>,
3887 ignore_refcounts: bool,
3888 cx: &mut Context<Self>,
3889 ) -> OpenLspBufferHandle {
3890 let buffer_id = buffer.read(cx).remote_id();
3891 let handle = cx.new(|_| buffer.clone());
3892 if let Some(local) = self.as_local_mut() {
3893 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
3894 return handle;
3895 };
3896 if !file.is_local() {
3897 return handle;
3898 }
3899
3900 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
3901 if !ignore_refcounts {
3902 *refcount += 1;
3903 }
3904
3905 if ignore_refcounts || *refcount == 1 {
3906 local.register_buffer_with_language_servers(buffer, cx);
3907 }
3908 if !ignore_refcounts {
3909 cx.observe_release(&handle, move |this, buffer, cx| {
3910 let local = this.as_local_mut().unwrap();
3911 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
3912 debug_panic!("bad refcounting");
3913 return;
3914 };
3915
3916 *refcount -= 1;
3917 if *refcount == 0 {
3918 local.registered_buffers.remove(&buffer_id);
3919 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
3920 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
3921 }
3922 }
3923 })
3924 .detach();
3925 }
3926 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
3927 let buffer_id = buffer.read(cx).remote_id().to_proto();
3928 cx.background_spawn(async move {
3929 upstream_client
3930 .request(proto::RegisterBufferWithLanguageServers {
3931 project_id: upstream_project_id,
3932 buffer_id,
3933 })
3934 .await
3935 })
3936 .detach();
3937 } else {
3938 panic!("oops!");
3939 }
3940 handle
3941 }
3942
3943 fn maintain_buffer_languages(
3944 languages: Arc<LanguageRegistry>,
3945 cx: &mut Context<Self>,
3946 ) -> Task<()> {
3947 let mut subscription = languages.subscribe();
3948 let mut prev_reload_count = languages.reload_count();
3949 cx.spawn(async move |this, cx| {
3950 while let Some(()) = subscription.next().await {
3951 if let Some(this) = this.upgrade() {
3952 // If the language registry has been reloaded, then remove and
3953 // re-assign the languages on all open buffers.
3954 let reload_count = languages.reload_count();
3955 if reload_count > prev_reload_count {
3956 prev_reload_count = reload_count;
3957 this.update(cx, |this, cx| {
3958 this.buffer_store.clone().update(cx, |buffer_store, cx| {
3959 for buffer in buffer_store.buffers() {
3960 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
3961 {
3962 buffer
3963 .update(cx, |buffer, cx| buffer.set_language(None, cx));
3964 if let Some(local) = this.as_local_mut() {
3965 local.reset_buffer(&buffer, &f, cx);
3966
3967 if local
3968 .registered_buffers
3969 .contains_key(&buffer.read(cx).remote_id())
3970 {
3971 if let Some(file_url) =
3972 lsp::Url::from_file_path(&f.abs_path(cx))
3973 .log_err()
3974 {
3975 local.unregister_buffer_from_language_servers(
3976 &buffer, &file_url, cx,
3977 );
3978 }
3979 }
3980 }
3981 }
3982 }
3983 });
3984 })
3985 .ok();
3986 }
3987
3988 this.update(cx, |this, cx| {
3989 let mut plain_text_buffers = Vec::new();
3990 let mut buffers_with_unknown_injections = Vec::new();
3991 for handle in this.buffer_store.read(cx).buffers() {
3992 let buffer = handle.read(cx);
3993 if buffer.language().is_none()
3994 || buffer.language() == Some(&*language::PLAIN_TEXT)
3995 {
3996 plain_text_buffers.push(handle);
3997 } else if buffer.contains_unknown_injections() {
3998 buffers_with_unknown_injections.push(handle);
3999 }
4000 }
4001 for buffer in plain_text_buffers {
4002 this.detect_language_for_buffer(&buffer, cx);
4003 if let Some(local) = this.as_local_mut() {
4004 local.initialize_buffer(&buffer, cx);
4005 if local
4006 .registered_buffers
4007 .contains_key(&buffer.read(cx).remote_id())
4008 {
4009 local.register_buffer_with_language_servers(&buffer, cx);
4010 }
4011 }
4012 }
4013
4014 for buffer in buffers_with_unknown_injections {
4015 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4016 }
4017 })
4018 .ok();
4019 }
4020 }
4021 })
4022 }
4023
4024 fn detect_language_for_buffer(
4025 &mut self,
4026 buffer_handle: &Entity<Buffer>,
4027 cx: &mut Context<Self>,
4028 ) -> Option<language::AvailableLanguage> {
4029 // If the buffer has a language, set it and start the language server if we haven't already.
4030 let buffer = buffer_handle.read(cx);
4031 let file = buffer.file()?;
4032
4033 let content = buffer.as_rope();
4034 let available_language = self.languages.language_for_file(file, Some(content), cx);
4035 if let Some(available_language) = &available_language {
4036 if let Some(Ok(Ok(new_language))) = self
4037 .languages
4038 .load_language(available_language)
4039 .now_or_never()
4040 {
4041 self.set_language_for_buffer(buffer_handle, new_language, cx);
4042 }
4043 } else {
4044 cx.emit(LspStoreEvent::LanguageDetected {
4045 buffer: buffer_handle.clone(),
4046 new_language: None,
4047 });
4048 }
4049
4050 available_language
4051 }
4052
4053 pub(crate) fn set_language_for_buffer(
4054 &mut self,
4055 buffer_entity: &Entity<Buffer>,
4056 new_language: Arc<Language>,
4057 cx: &mut Context<Self>,
4058 ) {
4059 let buffer = buffer_entity.read(cx);
4060 let buffer_file = buffer.file().cloned();
4061 let buffer_id = buffer.remote_id();
4062 if let Some(local_store) = self.as_local_mut() {
4063 if local_store.registered_buffers.contains_key(&buffer_id) {
4064 if let Some(abs_path) =
4065 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4066 {
4067 if let Some(file_url) = lsp::Url::from_file_path(&abs_path).log_err() {
4068 local_store.unregister_buffer_from_language_servers(
4069 buffer_entity,
4070 &file_url,
4071 cx,
4072 );
4073 }
4074 }
4075 }
4076 }
4077 buffer_entity.update(cx, |buffer, cx| {
4078 if buffer.language().map_or(true, |old_language| {
4079 !Arc::ptr_eq(old_language, &new_language)
4080 }) {
4081 buffer.set_language(Some(new_language.clone()), cx);
4082 }
4083 });
4084
4085 let settings =
4086 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4087 let buffer_file = File::from_dyn(buffer_file.as_ref());
4088
4089 let worktree_id = if let Some(file) = buffer_file {
4090 let worktree = file.worktree.clone();
4091
4092 if let Some(local) = self.as_local_mut() {
4093 if local.registered_buffers.contains_key(&buffer_id) {
4094 local.register_buffer_with_language_servers(buffer_entity, cx);
4095 }
4096 }
4097 Some(worktree.read(cx).id())
4098 } else {
4099 None
4100 };
4101
4102 if settings.prettier.allowed {
4103 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4104 {
4105 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4106 if let Some(prettier_store) = prettier_store {
4107 prettier_store.update(cx, |prettier_store, cx| {
4108 prettier_store.install_default_prettier(
4109 worktree_id,
4110 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4111 cx,
4112 )
4113 })
4114 }
4115 }
4116 }
4117
4118 cx.emit(LspStoreEvent::LanguageDetected {
4119 buffer: buffer_entity.clone(),
4120 new_language: Some(new_language),
4121 })
4122 }
4123
4124 pub fn buffer_store(&self) -> Entity<BufferStore> {
4125 self.buffer_store.clone()
4126 }
4127
4128 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4129 self.active_entry = active_entry;
4130 }
4131
4132 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4133 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4134 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4135 for (path, summaries) in summaries {
4136 for (&server_id, summary) in summaries {
4137 client
4138 .send(proto::UpdateDiagnosticSummary {
4139 project_id: downstream_project_id,
4140 worktree_id: worktree.id().to_proto(),
4141 summary: Some(summary.to_proto(server_id, path)),
4142 })
4143 .log_err();
4144 }
4145 }
4146 }
4147 }
4148 }
4149
4150 pub fn request_lsp<R: LspCommand>(
4151 &mut self,
4152 buffer_handle: Entity<Buffer>,
4153 server: LanguageServerToQuery,
4154 request: R,
4155 cx: &mut Context<Self>,
4156 ) -> Task<Result<R::Response>>
4157 where
4158 <R::LspRequest as lsp::request::Request>::Result: Send,
4159 <R::LspRequest as lsp::request::Request>::Params: Send,
4160 {
4161 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4162 return self.send_lsp_proto_request(
4163 buffer_handle,
4164 upstream_client,
4165 upstream_project_id,
4166 request,
4167 cx,
4168 );
4169 }
4170
4171 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4172 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4173 local
4174 .language_servers_for_buffer(buffer, cx)
4175 .find(|(_, server)| {
4176 request.check_capabilities(server.adapter_server_capabilities())
4177 })
4178 .map(|(_, server)| server.clone())
4179 }),
4180 LanguageServerToQuery::Other(id) => self
4181 .language_server_for_local_buffer(buffer, id, cx)
4182 .and_then(|(_, server)| {
4183 request
4184 .check_capabilities(server.adapter_server_capabilities())
4185 .then(|| Arc::clone(server))
4186 }),
4187 }) else {
4188 return Task::ready(Ok(Default::default()));
4189 };
4190
4191 let buffer = buffer_handle.read(cx);
4192 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4193
4194 let Some(file) = file else {
4195 return Task::ready(Ok(Default::default()));
4196 };
4197
4198 let lsp_params = match request.to_lsp_params_or_response(
4199 &file.abs_path(cx),
4200 buffer,
4201 &language_server,
4202 cx,
4203 ) {
4204 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4205 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4206
4207 Err(err) => {
4208 let message = format!(
4209 "{} via {} failed: {}",
4210 request.display_name(),
4211 language_server.name(),
4212 err
4213 );
4214 log::warn!("{}", message);
4215 return Task::ready(Err(anyhow!(message)));
4216 }
4217 };
4218
4219 let status = request.status();
4220 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4221 return Task::ready(Ok(Default::default()));
4222 }
4223 return cx.spawn(async move |this, cx| {
4224 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4225
4226 let id = lsp_request.id();
4227 let _cleanup = if status.is_some() {
4228 cx.update(|cx| {
4229 this.update(cx, |this, cx| {
4230 this.on_lsp_work_start(
4231 language_server.server_id(),
4232 id.to_string(),
4233 LanguageServerProgress {
4234 is_disk_based_diagnostics_progress: false,
4235 is_cancellable: false,
4236 title: None,
4237 message: status.clone(),
4238 percentage: None,
4239 last_update_at: cx.background_executor().now(),
4240 },
4241 cx,
4242 );
4243 })
4244 })
4245 .log_err();
4246
4247 Some(defer(|| {
4248 cx.update(|cx| {
4249 this.update(cx, |this, cx| {
4250 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4251 })
4252 })
4253 .log_err();
4254 }))
4255 } else {
4256 None
4257 };
4258
4259 let result = lsp_request.await;
4260
4261 let response = result.map_err(|err| {
4262 let message = format!(
4263 "{} via {} failed: {}",
4264 request.display_name(),
4265 language_server.name(),
4266 err
4267 );
4268 log::warn!("{}", message);
4269 anyhow!(message)
4270 })?;
4271
4272 let response = request
4273 .response_from_lsp(
4274 response,
4275 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
4276 buffer_handle,
4277 language_server.server_id(),
4278 cx.clone(),
4279 )
4280 .await;
4281 response
4282 });
4283 }
4284
4285 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4286 let mut language_formatters_to_check = Vec::new();
4287 for buffer in self.buffer_store.read(cx).buffers() {
4288 let buffer = buffer.read(cx);
4289 let buffer_file = File::from_dyn(buffer.file());
4290 let buffer_language = buffer.language();
4291 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4292 if buffer_language.is_some() {
4293 language_formatters_to_check.push((
4294 buffer_file.map(|f| f.worktree_id(cx)),
4295 settings.into_owned(),
4296 ));
4297 }
4298 }
4299
4300 self.refresh_server_tree(cx);
4301
4302 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4303 prettier_store.update(cx, |prettier_store, cx| {
4304 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4305 })
4306 }
4307
4308 cx.notify();
4309 }
4310
4311 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4312 let buffer_store = self.buffer_store.clone();
4313 if let Some(local) = self.as_local_mut() {
4314 let mut adapters = BTreeMap::default();
4315 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4316 let get_adapter = {
4317 let languages = local.languages.clone();
4318 let environment = local.environment.clone();
4319 let weak = local.weak.clone();
4320 let worktree_store = local.worktree_store.clone();
4321 let http_client = local.http_client.clone();
4322 let fs = local.fs.clone();
4323 move |worktree_id, cx: &mut App| {
4324 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4325 Some(LocalLspAdapterDelegate::new(
4326 languages.clone(),
4327 &environment,
4328 weak.clone(),
4329 &worktree,
4330 http_client.clone(),
4331 fs.clone(),
4332 cx,
4333 ))
4334 }
4335 };
4336
4337 let mut rebase = lsp_tree.rebase();
4338 for buffer in buffer_store.read(cx).buffers().collect::<Vec<_>>() {
4339 let buffer = buffer.read(cx);
4340 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4341 continue;
4342 }
4343 if let Some((file, language)) = File::from_dyn(buffer.file())
4344 .cloned()
4345 .zip(buffer.language().map(|l| l.name()))
4346 {
4347 let worktree_id = file.worktree_id(cx);
4348 let Some(worktree) = local
4349 .worktree_store
4350 .read(cx)
4351 .worktree_for_id(worktree_id, cx)
4352 else {
4353 continue;
4354 };
4355 let path: Arc<Path> = file
4356 .path()
4357 .parent()
4358 .map(Arc::from)
4359 .unwrap_or_else(|| file.path().clone());
4360 let worktree_path = ProjectPath { worktree_id, path };
4361
4362 let Some(delegate) = adapters
4363 .entry(worktree_id)
4364 .or_insert_with(|| get_adapter(worktree_id, cx))
4365 .clone()
4366 else {
4367 continue;
4368 };
4369 let nodes = rebase.get(
4370 worktree_path,
4371 AdapterQuery::Language(&language),
4372 delegate.clone(),
4373 cx,
4374 );
4375 for node in nodes {
4376 node.server_id_or_init(
4377 |LaunchDisposition {
4378 server_name,
4379 attach,
4380 path,
4381 settings,
4382 }| match attach {
4383 language::Attach::InstancePerRoot => {
4384 // todo: handle instance per root proper.
4385 if let Some(server_ids) = local
4386 .language_server_ids
4387 .get(&(worktree_id, server_name.clone()))
4388 {
4389 server_ids.iter().cloned().next().unwrap()
4390 } else {
4391 local.start_language_server(
4392 &worktree,
4393 delegate.clone(),
4394 local
4395 .languages
4396 .lsp_adapters(&language)
4397 .into_iter()
4398 .find(|adapter| &adapter.name() == server_name)
4399 .expect("To find LSP adapter"),
4400 settings,
4401 cx,
4402 )
4403 }
4404 }
4405 language::Attach::Shared => {
4406 let uri = Url::from_file_path(
4407 worktree.read(cx).abs_path().join(&path.path),
4408 );
4409 let key = (worktree_id, server_name.clone());
4410 local.language_server_ids.remove(&key);
4411
4412 let server_id = local.start_language_server(
4413 &worktree,
4414 delegate.clone(),
4415 local
4416 .languages
4417 .lsp_adapters(&language)
4418 .into_iter()
4419 .find(|adapter| &adapter.name() == server_name)
4420 .expect("To find LSP adapter"),
4421 settings,
4422 cx,
4423 );
4424 if let Some(state) = local.language_servers.get(&server_id)
4425 {
4426 if let Ok(uri) = uri {
4427 state.add_workspace_folder(uri);
4428 };
4429 }
4430 server_id
4431 }
4432 },
4433 );
4434 }
4435 }
4436 }
4437 rebase.finish()
4438 });
4439 for (id, name) in to_stop {
4440 self.stop_local_language_server(id, name, cx).detach();
4441 }
4442 }
4443 }
4444
4445 pub fn apply_code_action(
4446 &self,
4447 buffer_handle: Entity<Buffer>,
4448 mut action: CodeAction,
4449 push_to_history: bool,
4450 cx: &mut Context<Self>,
4451 ) -> Task<Result<ProjectTransaction>> {
4452 if let Some((upstream_client, project_id)) = self.upstream_client() {
4453 let request = proto::ApplyCodeAction {
4454 project_id,
4455 buffer_id: buffer_handle.read(cx).remote_id().into(),
4456 action: Some(Self::serialize_code_action(&action)),
4457 };
4458 let buffer_store = self.buffer_store();
4459 cx.spawn(async move |_, cx| {
4460 let response = upstream_client
4461 .request(request)
4462 .await?
4463 .transaction
4464 .ok_or_else(|| anyhow!("missing transaction"))?;
4465
4466 buffer_store
4467 .update(cx, |buffer_store, cx| {
4468 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4469 })?
4470 .await
4471 })
4472 } else if self.mode.is_local() {
4473 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4474 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4475 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4476 }) else {
4477 return Task::ready(Ok(ProjectTransaction::default()));
4478 };
4479 cx.spawn(async move |this, cx| {
4480 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4481 .await
4482 .context("resolving a code action")?;
4483 if let Some(edit) = action.lsp_action.edit() {
4484 if edit.changes.is_some() || edit.document_changes.is_some() {
4485 return LocalLspStore::deserialize_workspace_edit(
4486 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
4487 edit.clone(),
4488 push_to_history,
4489 lsp_adapter.clone(),
4490 lang_server.clone(),
4491 cx,
4492 )
4493 .await;
4494 }
4495 }
4496
4497 if let Some(command) = action.lsp_action.command() {
4498 let server_capabilities = lang_server.capabilities();
4499 let available_commands = server_capabilities
4500 .execute_command_provider
4501 .as_ref()
4502 .map(|options| options.commands.as_slice())
4503 .unwrap_or_default();
4504 if available_commands.contains(&command.command) {
4505 this.update(cx, |this, _| {
4506 this.as_local_mut()
4507 .unwrap()
4508 .last_workspace_edits_by_language_server
4509 .remove(&lang_server.server_id());
4510 })?;
4511
4512 let result = lang_server
4513 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4514 command: command.command.clone(),
4515 arguments: command.arguments.clone().unwrap_or_default(),
4516 ..Default::default()
4517 })
4518 .await;
4519
4520 result?;
4521
4522 return this.update(cx, |this, _| {
4523 this.as_local_mut()
4524 .unwrap()
4525 .last_workspace_edits_by_language_server
4526 .remove(&lang_server.server_id())
4527 .unwrap_or_default()
4528 });
4529 } else {
4530 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4531 }
4532 }
4533
4534 Ok(ProjectTransaction::default())
4535 })
4536 } else {
4537 Task::ready(Err(anyhow!("no upstream client and not local")))
4538 }
4539 }
4540
4541 pub fn apply_code_action_kind(
4542 &mut self,
4543 buffers: HashSet<Entity<Buffer>>,
4544 kind: CodeActionKind,
4545 push_to_history: bool,
4546 cx: &mut Context<Self>,
4547 ) -> Task<anyhow::Result<ProjectTransaction>> {
4548 if let Some(_) = self.as_local() {
4549 cx.spawn(async move |lsp_store, cx| {
4550 let buffers = buffers.into_iter().collect::<Vec<_>>();
4551 let result = LocalLspStore::execute_code_action_kind_locally(
4552 lsp_store.clone(),
4553 buffers,
4554 kind,
4555 push_to_history,
4556 cx,
4557 )
4558 .await;
4559 lsp_store.update(cx, |lsp_store, _| {
4560 lsp_store.update_last_formatting_failure(&result);
4561 })?;
4562 result
4563 })
4564 } else if let Some((client, project_id)) = self.upstream_client() {
4565 let buffer_store = self.buffer_store();
4566 cx.spawn(async move |lsp_store, cx| {
4567 let result = client
4568 .request(proto::ApplyCodeActionKind {
4569 project_id,
4570 kind: kind.as_str().to_owned(),
4571 buffer_ids: buffers
4572 .iter()
4573 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
4574 .collect::<Result<_>>()?,
4575 })
4576 .await
4577 .and_then(|result| result.transaction.context("missing transaction"));
4578 lsp_store.update(cx, |lsp_store, _| {
4579 lsp_store.update_last_formatting_failure(&result);
4580 })?;
4581
4582 let transaction_response = result?;
4583 buffer_store
4584 .update(cx, |buffer_store, cx| {
4585 buffer_store.deserialize_project_transaction(
4586 transaction_response,
4587 push_to_history,
4588 cx,
4589 )
4590 })?
4591 .await
4592 })
4593 } else {
4594 Task::ready(Ok(ProjectTransaction::default()))
4595 }
4596 }
4597
4598 pub fn resolve_inlay_hint(
4599 &self,
4600 hint: InlayHint,
4601 buffer_handle: Entity<Buffer>,
4602 server_id: LanguageServerId,
4603 cx: &mut Context<Self>,
4604 ) -> Task<anyhow::Result<InlayHint>> {
4605 if let Some((upstream_client, project_id)) = self.upstream_client() {
4606 let request = proto::ResolveInlayHint {
4607 project_id,
4608 buffer_id: buffer_handle.read(cx).remote_id().into(),
4609 language_server_id: server_id.0 as u64,
4610 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4611 };
4612 cx.spawn(async move |_, _| {
4613 let response = upstream_client
4614 .request(request)
4615 .await
4616 .context("inlay hints proto request")?;
4617 match response.hint {
4618 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4619 .context("inlay hints proto resolve response conversion"),
4620 None => Ok(hint),
4621 }
4622 })
4623 } else {
4624 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4625 self.language_server_for_local_buffer(buffer, server_id, cx)
4626 .map(|(_, server)| server.clone())
4627 }) else {
4628 return Task::ready(Ok(hint));
4629 };
4630 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4631 return Task::ready(Ok(hint));
4632 }
4633 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4634 cx.spawn(async move |_, cx| {
4635 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4636 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4637 );
4638 let resolved_hint = resolve_task
4639 .await
4640 .context("inlay hint resolve LSP request")?;
4641 let resolved_hint = InlayHints::lsp_to_project_hint(
4642 resolved_hint,
4643 &buffer_handle,
4644 server_id,
4645 ResolveState::Resolved,
4646 false,
4647 cx,
4648 )
4649 .await?;
4650 Ok(resolved_hint)
4651 })
4652 }
4653 }
4654
4655 pub(crate) fn linked_edit(
4656 &mut self,
4657 buffer: &Entity<Buffer>,
4658 position: Anchor,
4659 cx: &mut Context<Self>,
4660 ) -> Task<Result<Vec<Range<Anchor>>>> {
4661 let snapshot = buffer.read(cx).snapshot();
4662 let scope = snapshot.language_scope_at(position);
4663 let Some(server_id) = self
4664 .as_local()
4665 .and_then(|local| {
4666 buffer.update(cx, |buffer, cx| {
4667 local
4668 .language_servers_for_buffer(buffer, cx)
4669 .filter(|(_, server)| {
4670 server
4671 .capabilities()
4672 .linked_editing_range_provider
4673 .is_some()
4674 })
4675 .filter(|(adapter, _)| {
4676 scope
4677 .as_ref()
4678 .map(|scope| scope.language_allowed(&adapter.name))
4679 .unwrap_or(true)
4680 })
4681 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
4682 .next()
4683 })
4684 })
4685 .or_else(|| {
4686 self.upstream_client()
4687 .is_some()
4688 .then_some(LanguageServerToQuery::FirstCapable)
4689 })
4690 .filter(|_| {
4691 maybe!({
4692 let language = buffer.read(cx).language_at(position)?;
4693 Some(
4694 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
4695 .linked_edits,
4696 )
4697 }) == Some(true)
4698 })
4699 else {
4700 return Task::ready(Ok(vec![]));
4701 };
4702
4703 self.request_lsp(
4704 buffer.clone(),
4705 server_id,
4706 LinkedEditingRange { position },
4707 cx,
4708 )
4709 }
4710
4711 fn apply_on_type_formatting(
4712 &mut self,
4713 buffer: Entity<Buffer>,
4714 position: Anchor,
4715 trigger: String,
4716 cx: &mut Context<Self>,
4717 ) -> Task<Result<Option<Transaction>>> {
4718 if let Some((client, project_id)) = self.upstream_client() {
4719 let request = proto::OnTypeFormatting {
4720 project_id,
4721 buffer_id: buffer.read(cx).remote_id().into(),
4722 position: Some(serialize_anchor(&position)),
4723 trigger,
4724 version: serialize_version(&buffer.read(cx).version()),
4725 };
4726 cx.spawn(async move |_, _| {
4727 client
4728 .request(request)
4729 .await?
4730 .transaction
4731 .map(language::proto::deserialize_transaction)
4732 .transpose()
4733 })
4734 } else if let Some(local) = self.as_local_mut() {
4735 let buffer_id = buffer.read(cx).remote_id();
4736 local.buffers_being_formatted.insert(buffer_id);
4737 cx.spawn(async move |this, cx| {
4738 let _cleanup = defer({
4739 let this = this.clone();
4740 let mut cx = cx.clone();
4741 move || {
4742 this.update(&mut cx, |this, _| {
4743 if let Some(local) = this.as_local_mut() {
4744 local.buffers_being_formatted.remove(&buffer_id);
4745 }
4746 })
4747 .ok();
4748 }
4749 });
4750
4751 buffer
4752 .update(cx, |buffer, _| {
4753 buffer.wait_for_edits(Some(position.timestamp))
4754 })?
4755 .await?;
4756 this.update(cx, |this, cx| {
4757 let position = position.to_point_utf16(buffer.read(cx));
4758 this.on_type_format(buffer, position, trigger, false, cx)
4759 })?
4760 .await
4761 })
4762 } else {
4763 Task::ready(Err(anyhow!("No upstream client or local language server")))
4764 }
4765 }
4766
4767 pub fn on_type_format<T: ToPointUtf16>(
4768 &mut self,
4769 buffer: Entity<Buffer>,
4770 position: T,
4771 trigger: String,
4772 push_to_history: bool,
4773 cx: &mut Context<Self>,
4774 ) -> Task<Result<Option<Transaction>>> {
4775 let position = position.to_point_utf16(buffer.read(cx));
4776 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
4777 }
4778
4779 fn on_type_format_impl(
4780 &mut self,
4781 buffer: Entity<Buffer>,
4782 position: PointUtf16,
4783 trigger: String,
4784 push_to_history: bool,
4785 cx: &mut Context<Self>,
4786 ) -> Task<Result<Option<Transaction>>> {
4787 let options = buffer.update(cx, |buffer, cx| {
4788 lsp_command::lsp_formatting_options(
4789 language_settings(
4790 buffer.language_at(position).map(|l| l.name()),
4791 buffer.file(),
4792 cx,
4793 )
4794 .as_ref(),
4795 )
4796 });
4797 self.request_lsp(
4798 buffer.clone(),
4799 LanguageServerToQuery::FirstCapable,
4800 OnTypeFormatting {
4801 position,
4802 trigger,
4803 options,
4804 push_to_history,
4805 },
4806 cx,
4807 )
4808 }
4809
4810 pub fn code_actions(
4811 &mut self,
4812 buffer_handle: &Entity<Buffer>,
4813 range: Range<Anchor>,
4814 kinds: Option<Vec<CodeActionKind>>,
4815 cx: &mut Context<Self>,
4816 ) -> Task<Result<Vec<CodeAction>>> {
4817 if let Some((upstream_client, project_id)) = self.upstream_client() {
4818 let request_task = upstream_client.request(proto::MultiLspQuery {
4819 buffer_id: buffer_handle.read(cx).remote_id().into(),
4820 version: serialize_version(&buffer_handle.read(cx).version()),
4821 project_id,
4822 strategy: Some(proto::multi_lsp_query::Strategy::All(
4823 proto::AllLanguageServers {},
4824 )),
4825 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
4826 GetCodeActions {
4827 range: range.clone(),
4828 kinds: kinds.clone(),
4829 }
4830 .to_proto(project_id, buffer_handle.read(cx)),
4831 )),
4832 });
4833 let buffer = buffer_handle.clone();
4834 cx.spawn(async move |weak_project, cx| {
4835 let Some(project) = weak_project.upgrade() else {
4836 return Ok(Vec::new());
4837 };
4838 let responses = request_task.await?.responses;
4839 let actions = join_all(
4840 responses
4841 .into_iter()
4842 .filter_map(|lsp_response| match lsp_response.response? {
4843 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
4844 Some(response)
4845 }
4846 unexpected => {
4847 debug_panic!("Unexpected response: {unexpected:?}");
4848 None
4849 }
4850 })
4851 .map(|code_actions_response| {
4852 GetCodeActions {
4853 range: range.clone(),
4854 kinds: kinds.clone(),
4855 }
4856 .response_from_proto(
4857 code_actions_response,
4858 project.clone(),
4859 buffer.clone(),
4860 cx.clone(),
4861 )
4862 }),
4863 )
4864 .await;
4865
4866 Ok(actions
4867 .into_iter()
4868 .collect::<Result<Vec<Vec<_>>>>()?
4869 .into_iter()
4870 .flatten()
4871 .collect())
4872 })
4873 } else {
4874 let all_actions_task = self.request_multiple_lsp_locally(
4875 buffer_handle,
4876 Some(range.start),
4877 GetCodeActions {
4878 range: range.clone(),
4879 kinds: kinds.clone(),
4880 },
4881 cx,
4882 );
4883 cx.spawn(async move |_, _| Ok(all_actions_task.await.into_iter().flatten().collect()))
4884 }
4885 }
4886
4887 pub fn code_lens(
4888 &mut self,
4889 buffer_handle: &Entity<Buffer>,
4890 cx: &mut Context<Self>,
4891 ) -> Task<Result<Vec<CodeAction>>> {
4892 if let Some((upstream_client, project_id)) = self.upstream_client() {
4893 let request_task = upstream_client.request(proto::MultiLspQuery {
4894 buffer_id: buffer_handle.read(cx).remote_id().into(),
4895 version: serialize_version(&buffer_handle.read(cx).version()),
4896 project_id,
4897 strategy: Some(proto::multi_lsp_query::Strategy::All(
4898 proto::AllLanguageServers {},
4899 )),
4900 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
4901 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
4902 )),
4903 });
4904 let buffer = buffer_handle.clone();
4905 cx.spawn(async move |weak_project, cx| {
4906 let Some(project) = weak_project.upgrade() else {
4907 return Ok(Vec::new());
4908 };
4909 let responses = request_task.await?.responses;
4910 let code_lens = join_all(
4911 responses
4912 .into_iter()
4913 .filter_map(|lsp_response| match lsp_response.response? {
4914 proto::lsp_response::Response::GetCodeLensResponse(response) => {
4915 Some(response)
4916 }
4917 unexpected => {
4918 debug_panic!("Unexpected response: {unexpected:?}");
4919 None
4920 }
4921 })
4922 .map(|code_lens_response| {
4923 GetCodeLens.response_from_proto(
4924 code_lens_response,
4925 project.clone(),
4926 buffer.clone(),
4927 cx.clone(),
4928 )
4929 }),
4930 )
4931 .await;
4932
4933 Ok(code_lens
4934 .into_iter()
4935 .collect::<Result<Vec<Vec<_>>>>()?
4936 .into_iter()
4937 .flatten()
4938 .collect())
4939 })
4940 } else {
4941 let code_lens_task =
4942 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
4943 cx.spawn(async move |_, _| Ok(code_lens_task.await.into_iter().flatten().collect()))
4944 }
4945 }
4946
4947 #[inline(never)]
4948 pub fn completions(
4949 &self,
4950 buffer: &Entity<Buffer>,
4951 position: PointUtf16,
4952 context: CompletionContext,
4953 cx: &mut Context<Self>,
4954 ) -> Task<Result<Option<Vec<Completion>>>> {
4955 let language_registry = self.languages.clone();
4956
4957 if let Some((upstream_client, project_id)) = self.upstream_client() {
4958 let task = self.send_lsp_proto_request(
4959 buffer.clone(),
4960 upstream_client,
4961 project_id,
4962 GetCompletions { position, context },
4963 cx,
4964 );
4965 let language = buffer.read(cx).language().cloned();
4966
4967 // In the future, we should provide project guests with the names of LSP adapters,
4968 // so that they can use the correct LSP adapter when computing labels. For now,
4969 // guests just use the first LSP adapter associated with the buffer's language.
4970 let lsp_adapter = language.as_ref().and_then(|language| {
4971 language_registry
4972 .lsp_adapters(&language.name())
4973 .first()
4974 .cloned()
4975 });
4976
4977 cx.foreground_executor().spawn(async move {
4978 let completions = task.await?;
4979 let mut result = Vec::new();
4980 populate_labels_for_completions(completions, language, lsp_adapter, &mut result)
4981 .await;
4982 Ok(Some(result))
4983 })
4984 } else if let Some(local) = self.as_local() {
4985 let snapshot = buffer.read(cx).snapshot();
4986 let offset = position.to_offset(&snapshot);
4987 let scope = snapshot.language_scope_at(offset);
4988 let language = snapshot.language().cloned();
4989 let completion_settings = language_settings(
4990 language.as_ref().map(|language| language.name()),
4991 buffer.read(cx).file(),
4992 cx,
4993 )
4994 .completions;
4995 if !completion_settings.lsp {
4996 return Task::ready(Ok(None));
4997 }
4998
4999 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5000 local
5001 .language_servers_for_buffer(buffer, cx)
5002 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5003 .filter(|(adapter, _)| {
5004 scope
5005 .as_ref()
5006 .map(|scope| scope.language_allowed(&adapter.name))
5007 .unwrap_or(true)
5008 })
5009 .map(|(_, server)| server.server_id())
5010 .collect()
5011 });
5012
5013 let buffer = buffer.clone();
5014 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5015 let lsp_timeout = if lsp_timeout > 0 {
5016 Some(Duration::from_millis(lsp_timeout))
5017 } else {
5018 None
5019 };
5020 cx.spawn(async move |this, cx| {
5021 let mut tasks = Vec::with_capacity(server_ids.len());
5022 this.update(cx, |lsp_store, cx| {
5023 for server_id in server_ids {
5024 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5025 let lsp_timeout = lsp_timeout
5026 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5027 let mut timeout = cx.background_spawn(async move {
5028 match lsp_timeout {
5029 Some(lsp_timeout) => {
5030 lsp_timeout.await;
5031 true
5032 },
5033 None => false,
5034 }
5035 }).fuse();
5036 let mut lsp_request = lsp_store.request_lsp(
5037 buffer.clone(),
5038 LanguageServerToQuery::Other(server_id),
5039 GetCompletions {
5040 position,
5041 context: context.clone(),
5042 },
5043 cx,
5044 ).fuse();
5045 let new_task = cx.background_spawn(async move {
5046 select_biased! {
5047 response = lsp_request => anyhow::Ok(Some(response?)),
5048 timeout_happened = timeout => {
5049 if timeout_happened {
5050 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5051 Ok(None)
5052 } else {
5053 let completions = lsp_request.await?;
5054 Ok(Some(completions))
5055 }
5056 },
5057 }
5058 });
5059 tasks.push((lsp_adapter, new_task));
5060 }
5061 })?;
5062
5063 let mut has_completions_returned = false;
5064 let mut completions = Vec::new();
5065 for (lsp_adapter, task) in tasks {
5066 if let Ok(Some(new_completions)) = task.await {
5067 has_completions_returned = true;
5068 populate_labels_for_completions(
5069 new_completions,
5070 language.clone(),
5071 lsp_adapter,
5072 &mut completions,
5073 )
5074 .await;
5075 }
5076 }
5077 if has_completions_returned {
5078 Ok(Some(completions))
5079 } else {
5080 Ok(None)
5081 }
5082 })
5083 } else {
5084 Task::ready(Err(anyhow!("No upstream client or local language server")))
5085 }
5086 }
5087
5088 pub fn resolve_completions(
5089 &self,
5090 buffer: Entity<Buffer>,
5091 completion_indices: Vec<usize>,
5092 completions: Rc<RefCell<Box<[Completion]>>>,
5093 cx: &mut Context<Self>,
5094 ) -> Task<Result<bool>> {
5095 let client = self.upstream_client();
5096
5097 let buffer_id = buffer.read(cx).remote_id();
5098 let buffer_snapshot = buffer.read(cx).snapshot();
5099
5100 cx.spawn(async move |this, cx| {
5101 let mut did_resolve = false;
5102 if let Some((client, project_id)) = client {
5103 for completion_index in completion_indices {
5104 let server_id = {
5105 let completion = &completions.borrow()[completion_index];
5106 completion.source.server_id()
5107 };
5108 if let Some(server_id) = server_id {
5109 if Self::resolve_completion_remote(
5110 project_id,
5111 server_id,
5112 buffer_id,
5113 completions.clone(),
5114 completion_index,
5115 client.clone(),
5116 )
5117 .await
5118 .log_err()
5119 .is_some()
5120 {
5121 did_resolve = true;
5122 }
5123 } else {
5124 resolve_word_completion(
5125 &buffer_snapshot,
5126 &mut completions.borrow_mut()[completion_index],
5127 );
5128 }
5129 }
5130 } else {
5131 for completion_index in completion_indices {
5132 let server_id = {
5133 let completion = &completions.borrow()[completion_index];
5134 completion.source.server_id()
5135 };
5136 if let Some(server_id) = server_id {
5137 let server_and_adapter = this
5138 .read_with(cx, |lsp_store, _| {
5139 let server = lsp_store.language_server_for_id(server_id)?;
5140 let adapter =
5141 lsp_store.language_server_adapter_for_id(server.server_id())?;
5142 Some((server, adapter))
5143 })
5144 .ok()
5145 .flatten();
5146 let Some((server, adapter)) = server_and_adapter else {
5147 continue;
5148 };
5149
5150 let resolved = Self::resolve_completion_local(
5151 server,
5152 &buffer_snapshot,
5153 completions.clone(),
5154 completion_index,
5155 )
5156 .await
5157 .log_err()
5158 .is_some();
5159 if resolved {
5160 Self::regenerate_completion_labels(
5161 adapter,
5162 &buffer_snapshot,
5163 completions.clone(),
5164 completion_index,
5165 )
5166 .await
5167 .log_err();
5168 did_resolve = true;
5169 }
5170 } else {
5171 resolve_word_completion(
5172 &buffer_snapshot,
5173 &mut completions.borrow_mut()[completion_index],
5174 );
5175 }
5176 }
5177 }
5178
5179 Ok(did_resolve)
5180 })
5181 }
5182
5183 async fn resolve_completion_local(
5184 server: Arc<lsp::LanguageServer>,
5185 snapshot: &BufferSnapshot,
5186 completions: Rc<RefCell<Box<[Completion]>>>,
5187 completion_index: usize,
5188 ) -> Result<()> {
5189 let server_id = server.server_id();
5190 let can_resolve = server
5191 .capabilities()
5192 .completion_provider
5193 .as_ref()
5194 .and_then(|options| options.resolve_provider)
5195 .unwrap_or(false);
5196 if !can_resolve {
5197 return Ok(());
5198 }
5199
5200 let request = {
5201 let completion = &completions.borrow()[completion_index];
5202 match &completion.source {
5203 CompletionSource::Lsp {
5204 lsp_completion,
5205 resolved,
5206 server_id: completion_server_id,
5207 ..
5208 } => {
5209 if *resolved {
5210 return Ok(());
5211 }
5212 anyhow::ensure!(
5213 server_id == *completion_server_id,
5214 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5215 );
5216 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5217 }
5218 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5219 return Ok(());
5220 }
5221 }
5222 };
5223 let resolved_completion = request.await?;
5224
5225 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5226 // Technically we don't have to parse the whole `text_edit`, since the only
5227 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5228 // is `typescript-language-server` and they only update `text_edit.new_text`.
5229 // But we should not rely on that.
5230 let edit = parse_completion_text_edit(text_edit, snapshot);
5231
5232 if let Some((old_range, mut new_text)) = edit {
5233 LineEnding::normalize(&mut new_text);
5234
5235 let mut completions = completions.borrow_mut();
5236 let completion = &mut completions[completion_index];
5237
5238 completion.new_text = new_text;
5239 completion.old_range = old_range;
5240 }
5241 }
5242
5243 let mut completions = completions.borrow_mut();
5244 let completion = &mut completions[completion_index];
5245 if let CompletionSource::Lsp {
5246 lsp_completion,
5247 resolved,
5248 server_id: completion_server_id,
5249 ..
5250 } = &mut completion.source
5251 {
5252 if *resolved {
5253 return Ok(());
5254 }
5255 anyhow::ensure!(
5256 server_id == *completion_server_id,
5257 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5258 );
5259 *lsp_completion = Box::new(resolved_completion);
5260 *resolved = true;
5261 }
5262 Ok(())
5263 }
5264
5265 async fn regenerate_completion_labels(
5266 adapter: Arc<CachedLspAdapter>,
5267 snapshot: &BufferSnapshot,
5268 completions: Rc<RefCell<Box<[Completion]>>>,
5269 completion_index: usize,
5270 ) -> Result<()> {
5271 let completion_item = completions.borrow()[completion_index]
5272 .source
5273 .lsp_completion(true)
5274 .map(Cow::into_owned);
5275 if let Some(lsp_documentation) = completion_item
5276 .as_ref()
5277 .and_then(|completion_item| completion_item.documentation.clone())
5278 {
5279 let mut completions = completions.borrow_mut();
5280 let completion = &mut completions[completion_index];
5281 completion.documentation = Some(lsp_documentation.into());
5282 } else {
5283 let mut completions = completions.borrow_mut();
5284 let completion = &mut completions[completion_index];
5285 completion.documentation = Some(CompletionDocumentation::Undocumented);
5286 }
5287
5288 let mut new_label = match completion_item {
5289 Some(completion_item) => {
5290 // 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
5291 // So we have to update the label here anyway...
5292 let language = snapshot.language();
5293 match language {
5294 Some(language) => {
5295 adapter
5296 .labels_for_completions(&[completion_item.clone()], language)
5297 .await?
5298 }
5299 None => Vec::new(),
5300 }
5301 .pop()
5302 .flatten()
5303 .unwrap_or_else(|| {
5304 CodeLabel::fallback_for_completion(
5305 &completion_item,
5306 language.map(|language| language.as_ref()),
5307 )
5308 })
5309 }
5310 None => CodeLabel::plain(
5311 completions.borrow()[completion_index].new_text.clone(),
5312 None,
5313 ),
5314 };
5315 ensure_uniform_list_compatible_label(&mut new_label);
5316
5317 let mut completions = completions.borrow_mut();
5318 let completion = &mut completions[completion_index];
5319 if completion.label.filter_text() == new_label.filter_text() {
5320 completion.label = new_label;
5321 } else {
5322 log::error!(
5323 "Resolved completion changed display label from {} to {}. \
5324 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5325 completion.label.text(),
5326 new_label.text(),
5327 completion.label.filter_text(),
5328 new_label.filter_text()
5329 );
5330 }
5331
5332 Ok(())
5333 }
5334
5335 async fn resolve_completion_remote(
5336 project_id: u64,
5337 server_id: LanguageServerId,
5338 buffer_id: BufferId,
5339 completions: Rc<RefCell<Box<[Completion]>>>,
5340 completion_index: usize,
5341 client: AnyProtoClient,
5342 ) -> Result<()> {
5343 let lsp_completion = {
5344 let completion = &completions.borrow()[completion_index];
5345 match &completion.source {
5346 CompletionSource::Lsp {
5347 lsp_completion,
5348 resolved,
5349 server_id: completion_server_id,
5350 ..
5351 } => {
5352 anyhow::ensure!(
5353 server_id == *completion_server_id,
5354 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5355 );
5356 if *resolved {
5357 return Ok(());
5358 }
5359 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5360 }
5361 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5362 return Ok(());
5363 }
5364 }
5365 };
5366 let request = proto::ResolveCompletionDocumentation {
5367 project_id,
5368 language_server_id: server_id.0 as u64,
5369 lsp_completion,
5370 buffer_id: buffer_id.into(),
5371 };
5372
5373 let response = client
5374 .request(request)
5375 .await
5376 .context("completion documentation resolve proto request")?;
5377 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5378
5379 let documentation = if response.documentation.is_empty() {
5380 CompletionDocumentation::Undocumented
5381 } else if response.documentation_is_markdown {
5382 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5383 } else if response.documentation.lines().count() <= 1 {
5384 CompletionDocumentation::SingleLine(response.documentation.into())
5385 } else {
5386 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5387 };
5388
5389 let mut completions = completions.borrow_mut();
5390 let completion = &mut completions[completion_index];
5391 completion.documentation = Some(documentation);
5392 if let CompletionSource::Lsp {
5393 lsp_completion,
5394 resolved,
5395 server_id: completion_server_id,
5396 lsp_defaults: _,
5397 } = &mut completion.source
5398 {
5399 if *resolved {
5400 return Ok(());
5401 }
5402 anyhow::ensure!(
5403 server_id == *completion_server_id,
5404 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5405 );
5406 *lsp_completion = Box::new(resolved_lsp_completion);
5407 *resolved = true;
5408 }
5409
5410 let old_range = response
5411 .old_start
5412 .and_then(deserialize_anchor)
5413 .zip(response.old_end.and_then(deserialize_anchor));
5414 if let Some((old_start, old_end)) = old_range {
5415 if !response.new_text.is_empty() {
5416 completion.new_text = response.new_text;
5417 completion.old_range = old_start..old_end;
5418 }
5419 }
5420
5421 Ok(())
5422 }
5423
5424 pub fn apply_additional_edits_for_completion(
5425 &self,
5426 buffer_handle: Entity<Buffer>,
5427 completions: Rc<RefCell<Box<[Completion]>>>,
5428 completion_index: usize,
5429 push_to_history: bool,
5430 cx: &mut Context<Self>,
5431 ) -> Task<Result<Option<Transaction>>> {
5432 if let Some((client, project_id)) = self.upstream_client() {
5433 let buffer = buffer_handle.read(cx);
5434 let buffer_id = buffer.remote_id();
5435 cx.spawn(async move |_, cx| {
5436 let request = {
5437 let completion = completions.borrow()[completion_index].clone();
5438 proto::ApplyCompletionAdditionalEdits {
5439 project_id,
5440 buffer_id: buffer_id.into(),
5441 completion: Some(Self::serialize_completion(&CoreCompletion {
5442 old_range: completion.old_range,
5443 new_text: completion.new_text,
5444 source: completion.source,
5445 })),
5446 }
5447 };
5448
5449 if let Some(transaction) = client.request(request).await?.transaction {
5450 let transaction = language::proto::deserialize_transaction(transaction)?;
5451 buffer_handle
5452 .update(cx, |buffer, _| {
5453 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5454 })?
5455 .await?;
5456 if push_to_history {
5457 buffer_handle.update(cx, |buffer, _| {
5458 buffer.push_transaction(transaction.clone(), Instant::now());
5459 })?;
5460 }
5461 Ok(Some(transaction))
5462 } else {
5463 Ok(None)
5464 }
5465 })
5466 } else {
5467 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5468 let completion = &completions.borrow()[completion_index];
5469 let server_id = completion.source.server_id()?;
5470 Some(
5471 self.language_server_for_local_buffer(buffer, server_id, cx)?
5472 .1
5473 .clone(),
5474 )
5475 }) else {
5476 return Task::ready(Ok(None));
5477 };
5478 let snapshot = buffer_handle.read(&cx).snapshot();
5479
5480 cx.spawn(async move |this, cx| {
5481 Self::resolve_completion_local(
5482 server.clone(),
5483 &snapshot,
5484 completions.clone(),
5485 completion_index,
5486 )
5487 .await
5488 .context("resolving completion")?;
5489 let completion = completions.borrow()[completion_index].clone();
5490 let additional_text_edits = completion
5491 .source
5492 .lsp_completion(true)
5493 .as_ref()
5494 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5495 if let Some(edits) = additional_text_edits {
5496 let edits = this
5497 .update(cx, |this, cx| {
5498 this.as_local_mut().unwrap().edits_from_lsp(
5499 &buffer_handle,
5500 edits,
5501 server.server_id(),
5502 None,
5503 cx,
5504 )
5505 })?
5506 .await?;
5507
5508 buffer_handle.update(cx, |buffer, cx| {
5509 buffer.finalize_last_transaction();
5510 buffer.start_transaction();
5511
5512 for (range, text) in edits {
5513 let primary = &completion.old_range;
5514 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5515 && primary.end.cmp(&range.start, buffer).is_ge();
5516 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5517 && range.end.cmp(&primary.end, buffer).is_ge();
5518
5519 //Skip additional edits which overlap with the primary completion edit
5520 //https://github.com/zed-industries/zed/pull/1871
5521 if !start_within && !end_within {
5522 buffer.edit([(range, text)], None, cx);
5523 }
5524 }
5525
5526 let transaction = if buffer.end_transaction(cx).is_some() {
5527 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5528 if !push_to_history {
5529 buffer.forget_transaction(transaction.id);
5530 }
5531 Some(transaction)
5532 } else {
5533 None
5534 };
5535 Ok(transaction)
5536 })?
5537 } else {
5538 Ok(None)
5539 }
5540 })
5541 }
5542 }
5543
5544 pub fn inlay_hints(
5545 &mut self,
5546 buffer_handle: Entity<Buffer>,
5547 range: Range<Anchor>,
5548 cx: &mut Context<Self>,
5549 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5550 let buffer = buffer_handle.read(cx);
5551 let range_start = range.start;
5552 let range_end = range.end;
5553 let buffer_id = buffer.remote_id().into();
5554 let lsp_request = InlayHints { range };
5555
5556 if let Some((client, project_id)) = self.upstream_client() {
5557 let request = proto::InlayHints {
5558 project_id,
5559 buffer_id,
5560 start: Some(serialize_anchor(&range_start)),
5561 end: Some(serialize_anchor(&range_end)),
5562 version: serialize_version(&buffer_handle.read(cx).version()),
5563 };
5564 cx.spawn(async move |project, cx| {
5565 let response = client
5566 .request(request)
5567 .await
5568 .context("inlay hints proto request")?;
5569 LspCommand::response_from_proto(
5570 lsp_request,
5571 response,
5572 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5573 buffer_handle.clone(),
5574 cx.clone(),
5575 )
5576 .await
5577 .context("inlay hints proto response conversion")
5578 })
5579 } else {
5580 let lsp_request_task = self.request_lsp(
5581 buffer_handle.clone(),
5582 LanguageServerToQuery::FirstCapable,
5583 lsp_request,
5584 cx,
5585 );
5586 cx.spawn(async move |_, cx| {
5587 buffer_handle
5588 .update(cx, |buffer, _| {
5589 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5590 })?
5591 .await
5592 .context("waiting for inlay hint request range edits")?;
5593 lsp_request_task.await.context("inlay hints LSP request")
5594 })
5595 }
5596 }
5597
5598 pub fn signature_help<T: ToPointUtf16>(
5599 &mut self,
5600 buffer: &Entity<Buffer>,
5601 position: T,
5602 cx: &mut Context<Self>,
5603 ) -> Task<Vec<SignatureHelp>> {
5604 let position = position.to_point_utf16(buffer.read(cx));
5605
5606 if let Some((client, upstream_project_id)) = self.upstream_client() {
5607 let request_task = client.request(proto::MultiLspQuery {
5608 buffer_id: buffer.read(cx).remote_id().into(),
5609 version: serialize_version(&buffer.read(cx).version()),
5610 project_id: upstream_project_id,
5611 strategy: Some(proto::multi_lsp_query::Strategy::All(
5612 proto::AllLanguageServers {},
5613 )),
5614 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
5615 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
5616 )),
5617 });
5618 let buffer = buffer.clone();
5619 cx.spawn(async move |weak_project, cx| {
5620 let Some(project) = weak_project.upgrade() else {
5621 return Vec::new();
5622 };
5623 join_all(
5624 request_task
5625 .await
5626 .log_err()
5627 .map(|response| response.responses)
5628 .unwrap_or_default()
5629 .into_iter()
5630 .filter_map(|lsp_response| match lsp_response.response? {
5631 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
5632 Some(response)
5633 }
5634 unexpected => {
5635 debug_panic!("Unexpected response: {unexpected:?}");
5636 None
5637 }
5638 })
5639 .map(|signature_response| {
5640 let response = GetSignatureHelp { position }.response_from_proto(
5641 signature_response,
5642 project.clone(),
5643 buffer.clone(),
5644 cx.clone(),
5645 );
5646 async move { response.await.log_err().flatten() }
5647 }),
5648 )
5649 .await
5650 .into_iter()
5651 .flatten()
5652 .collect()
5653 })
5654 } else {
5655 let all_actions_task = self.request_multiple_lsp_locally(
5656 buffer,
5657 Some(position),
5658 GetSignatureHelp { position },
5659 cx,
5660 );
5661 cx.spawn(async move |_, _| {
5662 all_actions_task
5663 .await
5664 .into_iter()
5665 .flatten()
5666 .filter(|help| !help.label.is_empty())
5667 .collect::<Vec<_>>()
5668 })
5669 }
5670 }
5671
5672 pub fn hover(
5673 &mut self,
5674 buffer: &Entity<Buffer>,
5675 position: PointUtf16,
5676 cx: &mut Context<Self>,
5677 ) -> Task<Vec<Hover>> {
5678 if let Some((client, upstream_project_id)) = self.upstream_client() {
5679 let request_task = client.request(proto::MultiLspQuery {
5680 buffer_id: buffer.read(cx).remote_id().into(),
5681 version: serialize_version(&buffer.read(cx).version()),
5682 project_id: upstream_project_id,
5683 strategy: Some(proto::multi_lsp_query::Strategy::All(
5684 proto::AllLanguageServers {},
5685 )),
5686 request: Some(proto::multi_lsp_query::Request::GetHover(
5687 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
5688 )),
5689 });
5690 let buffer = buffer.clone();
5691 cx.spawn(async move |weak_project, cx| {
5692 let Some(project) = weak_project.upgrade() else {
5693 return Vec::new();
5694 };
5695 join_all(
5696 request_task
5697 .await
5698 .log_err()
5699 .map(|response| response.responses)
5700 .unwrap_or_default()
5701 .into_iter()
5702 .filter_map(|lsp_response| match lsp_response.response? {
5703 proto::lsp_response::Response::GetHoverResponse(response) => {
5704 Some(response)
5705 }
5706 unexpected => {
5707 debug_panic!("Unexpected response: {unexpected:?}");
5708 None
5709 }
5710 })
5711 .map(|hover_response| {
5712 let response = GetHover { position }.response_from_proto(
5713 hover_response,
5714 project.clone(),
5715 buffer.clone(),
5716 cx.clone(),
5717 );
5718 async move {
5719 response
5720 .await
5721 .log_err()
5722 .flatten()
5723 .and_then(remove_empty_hover_blocks)
5724 }
5725 }),
5726 )
5727 .await
5728 .into_iter()
5729 .flatten()
5730 .collect()
5731 })
5732 } else {
5733 let all_actions_task = self.request_multiple_lsp_locally(
5734 buffer,
5735 Some(position),
5736 GetHover { position },
5737 cx,
5738 );
5739 cx.spawn(async move |_, _| {
5740 all_actions_task
5741 .await
5742 .into_iter()
5743 .filter_map(|hover| remove_empty_hover_blocks(hover?))
5744 .collect::<Vec<Hover>>()
5745 })
5746 }
5747 }
5748
5749 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
5750 let language_registry = self.languages.clone();
5751
5752 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
5753 let request = upstream_client.request(proto::GetProjectSymbols {
5754 project_id: *project_id,
5755 query: query.to_string(),
5756 });
5757 cx.foreground_executor().spawn(async move {
5758 let response = request.await?;
5759 let mut symbols = Vec::new();
5760 let core_symbols = response
5761 .symbols
5762 .into_iter()
5763 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
5764 .collect::<Vec<_>>();
5765 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
5766 .await;
5767 Ok(symbols)
5768 })
5769 } else if let Some(local) = self.as_local() {
5770 struct WorkspaceSymbolsResult {
5771 server_id: LanguageServerId,
5772 lsp_adapter: Arc<CachedLspAdapter>,
5773 worktree: WeakEntity<Worktree>,
5774 worktree_abs_path: Arc<Path>,
5775 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
5776 }
5777
5778 let mut requests = Vec::new();
5779 let mut requested_servers = BTreeSet::new();
5780 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
5781 let Some(worktree_handle) = self
5782 .worktree_store
5783 .read(cx)
5784 .worktree_for_id(*worktree_id, cx)
5785 else {
5786 continue;
5787 };
5788 let worktree = worktree_handle.read(cx);
5789 if !worktree.is_visible() {
5790 continue;
5791 }
5792
5793 let mut servers_to_query = server_ids
5794 .difference(&requested_servers)
5795 .cloned()
5796 .collect::<BTreeSet<_>>();
5797 for server_id in &servers_to_query {
5798 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
5799 Some(LanguageServerState::Running {
5800 adapter, server, ..
5801 }) => (adapter.clone(), server),
5802
5803 _ => continue 'next_server,
5804 };
5805 let supports_workspace_symbol_request =
5806 match server.capabilities().workspace_symbol_provider {
5807 Some(OneOf::Left(supported)) => supported,
5808 Some(OneOf::Right(_)) => true,
5809 None => false,
5810 };
5811 if !supports_workspace_symbol_request {
5812 continue 'next_server;
5813 }
5814 let worktree_abs_path = worktree.abs_path().clone();
5815 let worktree_handle = worktree_handle.clone();
5816 let server_id = server.server_id();
5817 requests.push(
5818 server
5819 .request::<lsp::request::WorkspaceSymbolRequest>(
5820 lsp::WorkspaceSymbolParams {
5821 query: query.to_string(),
5822 ..Default::default()
5823 },
5824 )
5825 .log_err()
5826 .map(move |response| {
5827 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
5828 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
5829 flat_responses.into_iter().map(|lsp_symbol| {
5830 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
5831 }).collect::<Vec<_>>()
5832 }
5833 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
5834 nested_responses.into_iter().filter_map(|lsp_symbol| {
5835 let location = match lsp_symbol.location {
5836 OneOf::Left(location) => location,
5837 OneOf::Right(_) => {
5838 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
5839 return None
5840 }
5841 };
5842 Some((lsp_symbol.name, lsp_symbol.kind, location))
5843 }).collect::<Vec<_>>()
5844 }
5845 }).unwrap_or_default();
5846
5847 WorkspaceSymbolsResult {
5848 server_id,
5849 lsp_adapter,
5850 worktree: worktree_handle.downgrade(),
5851 worktree_abs_path,
5852 lsp_symbols,
5853 }
5854 }),
5855 );
5856 }
5857 requested_servers.append(&mut servers_to_query);
5858 }
5859
5860 cx.spawn(async move |this, cx| {
5861 let responses = futures::future::join_all(requests).await;
5862 let this = match this.upgrade() {
5863 Some(this) => this,
5864 None => return Ok(Vec::new()),
5865 };
5866
5867 let mut symbols = Vec::new();
5868 for result in responses {
5869 let core_symbols = this.update(cx, |this, cx| {
5870 result
5871 .lsp_symbols
5872 .into_iter()
5873 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
5874 let abs_path = symbol_location.uri.to_file_path().ok()?;
5875 let source_worktree = result.worktree.upgrade()?;
5876 let source_worktree_id = source_worktree.read(cx).id();
5877
5878 let path;
5879 let worktree;
5880 if let Some((tree, rel_path)) =
5881 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
5882 {
5883 worktree = tree;
5884 path = rel_path;
5885 } else {
5886 worktree = source_worktree.clone();
5887 path = relativize_path(&result.worktree_abs_path, &abs_path);
5888 }
5889
5890 let worktree_id = worktree.read(cx).id();
5891 let project_path = ProjectPath {
5892 worktree_id,
5893 path: path.into(),
5894 };
5895 let signature = this.symbol_signature(&project_path);
5896 Some(CoreSymbol {
5897 source_language_server_id: result.server_id,
5898 language_server_name: result.lsp_adapter.name.clone(),
5899 source_worktree_id,
5900 path: project_path,
5901 kind: symbol_kind,
5902 name: symbol_name,
5903 range: range_from_lsp(symbol_location.range),
5904 signature,
5905 })
5906 })
5907 .collect()
5908 })?;
5909
5910 populate_labels_for_symbols(
5911 core_symbols,
5912 &language_registry,
5913 Some(result.lsp_adapter),
5914 &mut symbols,
5915 )
5916 .await;
5917 }
5918
5919 Ok(symbols)
5920 })
5921 } else {
5922 Task::ready(Err(anyhow!("No upstream client or local language server")))
5923 }
5924 }
5925
5926 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
5927 let mut summary = DiagnosticSummary::default();
5928 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
5929 summary.error_count += path_summary.error_count;
5930 summary.warning_count += path_summary.warning_count;
5931 }
5932 summary
5933 }
5934
5935 pub fn diagnostic_summaries<'a>(
5936 &'a self,
5937 include_ignored: bool,
5938 cx: &'a App,
5939 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5940 self.worktree_store
5941 .read(cx)
5942 .visible_worktrees(cx)
5943 .filter_map(|worktree| {
5944 let worktree = worktree.read(cx);
5945 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
5946 })
5947 .flat_map(move |(worktree, summaries)| {
5948 let worktree_id = worktree.id();
5949 summaries
5950 .iter()
5951 .filter(move |(path, _)| {
5952 include_ignored
5953 || worktree
5954 .entry_for_path(path.as_ref())
5955 .map_or(false, |entry| !entry.is_ignored)
5956 })
5957 .flat_map(move |(path, summaries)| {
5958 summaries.iter().map(move |(server_id, summary)| {
5959 (
5960 ProjectPath {
5961 worktree_id,
5962 path: path.clone(),
5963 },
5964 *server_id,
5965 *summary,
5966 )
5967 })
5968 })
5969 })
5970 }
5971
5972 pub fn on_buffer_edited(
5973 &mut self,
5974 buffer: Entity<Buffer>,
5975 cx: &mut Context<Self>,
5976 ) -> Option<()> {
5977 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
5978 Some(
5979 self.as_local()?
5980 .language_servers_for_buffer(buffer, cx)
5981 .map(|i| i.1.clone())
5982 .collect(),
5983 )
5984 })?;
5985
5986 let buffer = buffer.read(cx);
5987 let file = File::from_dyn(buffer.file())?;
5988 let abs_path = file.as_local()?.abs_path(cx);
5989 let uri = lsp::Url::from_file_path(abs_path).unwrap();
5990 let next_snapshot = buffer.text_snapshot();
5991 for language_server in language_servers {
5992 let language_server = language_server.clone();
5993
5994 let buffer_snapshots = self
5995 .as_local_mut()
5996 .unwrap()
5997 .buffer_snapshots
5998 .get_mut(&buffer.remote_id())
5999 .and_then(|m| m.get_mut(&language_server.server_id()))?;
6000 let previous_snapshot = buffer_snapshots.last()?;
6001
6002 let build_incremental_change = || {
6003 buffer
6004 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6005 .map(|edit| {
6006 let edit_start = edit.new.start.0;
6007 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6008 let new_text = next_snapshot
6009 .text_for_range(edit.new.start.1..edit.new.end.1)
6010 .collect();
6011 lsp::TextDocumentContentChangeEvent {
6012 range: Some(lsp::Range::new(
6013 point_to_lsp(edit_start),
6014 point_to_lsp(edit_end),
6015 )),
6016 range_length: None,
6017 text: new_text,
6018 }
6019 })
6020 .collect()
6021 };
6022
6023 let document_sync_kind = language_server
6024 .capabilities()
6025 .text_document_sync
6026 .as_ref()
6027 .and_then(|sync| match sync {
6028 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6029 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6030 });
6031
6032 let content_changes: Vec<_> = match document_sync_kind {
6033 Some(lsp::TextDocumentSyncKind::FULL) => {
6034 vec![lsp::TextDocumentContentChangeEvent {
6035 range: None,
6036 range_length: None,
6037 text: next_snapshot.text(),
6038 }]
6039 }
6040 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6041 _ => {
6042 #[cfg(any(test, feature = "test-support"))]
6043 {
6044 build_incremental_change()
6045 }
6046
6047 #[cfg(not(any(test, feature = "test-support")))]
6048 {
6049 continue;
6050 }
6051 }
6052 };
6053
6054 let next_version = previous_snapshot.version + 1;
6055 buffer_snapshots.push(LspBufferSnapshot {
6056 version: next_version,
6057 snapshot: next_snapshot.clone(),
6058 });
6059
6060 language_server
6061 .notify::<lsp::notification::DidChangeTextDocument>(
6062 &lsp::DidChangeTextDocumentParams {
6063 text_document: lsp::VersionedTextDocumentIdentifier::new(
6064 uri.clone(),
6065 next_version,
6066 ),
6067 content_changes,
6068 },
6069 )
6070 .log_err();
6071 }
6072
6073 None
6074 }
6075
6076 pub fn on_buffer_saved(
6077 &mut self,
6078 buffer: Entity<Buffer>,
6079 cx: &mut Context<Self>,
6080 ) -> Option<()> {
6081 let file = File::from_dyn(buffer.read(cx).file())?;
6082 let worktree_id = file.worktree_id(cx);
6083 let abs_path = file.as_local()?.abs_path(cx);
6084 let text_document = lsp::TextDocumentIdentifier {
6085 uri: lsp::Url::from_file_path(abs_path).log_err()?,
6086 };
6087 let local = self.as_local()?;
6088
6089 for server in local.language_servers_for_worktree(worktree_id) {
6090 if let Some(include_text) = include_text(server.as_ref()) {
6091 let text = if include_text {
6092 Some(buffer.read(cx).text())
6093 } else {
6094 None
6095 };
6096 server
6097 .notify::<lsp::notification::DidSaveTextDocument>(
6098 &lsp::DidSaveTextDocumentParams {
6099 text_document: text_document.clone(),
6100 text,
6101 },
6102 )
6103 .log_err();
6104 }
6105 }
6106
6107 let language_servers = buffer.update(cx, |buffer, cx| {
6108 local.language_server_ids_for_buffer(buffer, cx)
6109 });
6110 for language_server_id in language_servers {
6111 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6112 }
6113
6114 None
6115 }
6116
6117 pub(crate) async fn refresh_workspace_configurations(
6118 this: &WeakEntity<Self>,
6119 fs: Arc<dyn Fs>,
6120 cx: &mut AsyncApp,
6121 ) {
6122 maybe!(async move {
6123 let servers = this
6124 .update(cx, |this, cx| {
6125 let Some(local) = this.as_local() else {
6126 return Vec::default();
6127 };
6128 local
6129 .language_server_ids
6130 .iter()
6131 .flat_map(|((worktree_id, _), server_ids)| {
6132 let worktree = this
6133 .worktree_store
6134 .read(cx)
6135 .worktree_for_id(*worktree_id, cx);
6136 let delegate = worktree.map(|worktree| {
6137 LocalLspAdapterDelegate::new(
6138 local.languages.clone(),
6139 &local.environment,
6140 cx.weak_entity(),
6141 &worktree,
6142 local.http_client.clone(),
6143 local.fs.clone(),
6144 cx,
6145 )
6146 });
6147
6148 server_ids.iter().filter_map(move |server_id| {
6149 let states = local.language_servers.get(server_id)?;
6150
6151 match states {
6152 LanguageServerState::Starting { .. } => None,
6153 LanguageServerState::Running {
6154 adapter, server, ..
6155 } => Some((
6156 adapter.adapter.clone(),
6157 server.clone(),
6158 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
6159 )),
6160 }
6161 })
6162 })
6163 .collect::<Vec<_>>()
6164 })
6165 .ok()?;
6166
6167 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
6168 for (adapter, server, delegate) in servers {
6169 let settings = LocalLspStore::workspace_configuration_for_adapter(
6170 adapter,
6171 fs.as_ref(),
6172 &delegate,
6173 toolchain_store.clone(),
6174 cx,
6175 )
6176 .await
6177 .ok()?;
6178
6179 server
6180 .notify::<lsp::notification::DidChangeConfiguration>(
6181 &lsp::DidChangeConfigurationParams { settings },
6182 )
6183 .ok();
6184 }
6185 Some(())
6186 })
6187 .await;
6188 }
6189
6190 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
6191 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
6192 toolchain_store.read(cx).as_language_toolchain_store()
6193 } else {
6194 Arc::new(EmptyToolchainStore)
6195 }
6196 }
6197 fn maintain_workspace_config(
6198 fs: Arc<dyn Fs>,
6199 external_refresh_requests: watch::Receiver<()>,
6200 cx: &mut Context<Self>,
6201 ) -> Task<Result<()>> {
6202 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
6203 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
6204
6205 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
6206 *settings_changed_tx.borrow_mut() = ();
6207 });
6208
6209 let mut joint_future =
6210 futures::stream::select(settings_changed_rx, external_refresh_requests);
6211 cx.spawn(async move |this, cx| {
6212 while let Some(()) = joint_future.next().await {
6213 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
6214 }
6215
6216 drop(settings_observation);
6217 anyhow::Ok(())
6218 })
6219 }
6220
6221 pub fn language_servers_for_local_buffer<'a>(
6222 &'a self,
6223 buffer: &Buffer,
6224 cx: &mut App,
6225 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6226 let local = self.as_local();
6227 let language_server_ids = local
6228 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
6229 .unwrap_or_default();
6230
6231 language_server_ids
6232 .into_iter()
6233 .filter_map(
6234 move |server_id| match local?.language_servers.get(&server_id)? {
6235 LanguageServerState::Running {
6236 adapter, server, ..
6237 } => Some((adapter, server)),
6238 _ => None,
6239 },
6240 )
6241 }
6242
6243 pub fn language_server_for_local_buffer<'a>(
6244 &'a self,
6245 buffer: &'a Buffer,
6246 server_id: LanguageServerId,
6247 cx: &'a mut App,
6248 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6249 self.as_local()?
6250 .language_servers_for_buffer(buffer, cx)
6251 .find(|(_, s)| s.server_id() == server_id)
6252 }
6253
6254 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
6255 self.diagnostic_summaries.remove(&id_to_remove);
6256 if let Some(local) = self.as_local_mut() {
6257 let to_remove = local.remove_worktree(id_to_remove, cx);
6258 for server in to_remove {
6259 self.language_server_statuses.remove(&server);
6260 }
6261 }
6262 }
6263
6264 pub fn shared(
6265 &mut self,
6266 project_id: u64,
6267 downstream_client: AnyProtoClient,
6268 _: &mut Context<Self>,
6269 ) {
6270 self.downstream_client = Some((downstream_client.clone(), project_id));
6271
6272 for (server_id, status) in &self.language_server_statuses {
6273 downstream_client
6274 .send(proto::StartLanguageServer {
6275 project_id,
6276 server: Some(proto::LanguageServer {
6277 id: server_id.0 as u64,
6278 name: status.name.clone(),
6279 worktree_id: None,
6280 }),
6281 })
6282 .log_err();
6283 }
6284 }
6285
6286 pub fn disconnected_from_host(&mut self) {
6287 self.downstream_client.take();
6288 }
6289
6290 pub fn disconnected_from_ssh_remote(&mut self) {
6291 if let LspStoreMode::Remote(RemoteLspStore {
6292 upstream_client, ..
6293 }) = &mut self.mode
6294 {
6295 upstream_client.take();
6296 }
6297 }
6298
6299 pub(crate) fn set_language_server_statuses_from_proto(
6300 &mut self,
6301 language_servers: Vec<proto::LanguageServer>,
6302 ) {
6303 self.language_server_statuses = language_servers
6304 .into_iter()
6305 .map(|server| {
6306 (
6307 LanguageServerId(server.id as usize),
6308 LanguageServerStatus {
6309 name: server.name,
6310 pending_work: Default::default(),
6311 has_pending_diagnostic_updates: false,
6312 progress_tokens: Default::default(),
6313 },
6314 )
6315 })
6316 .collect();
6317 }
6318
6319 fn register_local_language_server(
6320 &mut self,
6321 worktree: Entity<Worktree>,
6322 language_server_name: LanguageServerName,
6323 language_server_id: LanguageServerId,
6324 cx: &mut App,
6325 ) {
6326 let Some(local) = self.as_local_mut() else {
6327 return;
6328 };
6329 let worktree_id = worktree.read(cx).id();
6330 let path = ProjectPath {
6331 worktree_id,
6332 path: Arc::from("".as_ref()),
6333 };
6334 let delegate = LocalLspAdapterDelegate::from_local_lsp(local, &worktree, cx);
6335 local.lsp_tree.update(cx, |this, cx| {
6336 for node in this.get(
6337 path,
6338 AdapterQuery::Adapter(&language_server_name),
6339 delegate,
6340 cx,
6341 ) {
6342 node.server_id_or_init(|disposition| {
6343 assert_eq!(disposition.server_name, &language_server_name);
6344
6345 language_server_id
6346 });
6347 }
6348 });
6349 local
6350 .language_server_ids
6351 .entry((worktree_id, language_server_name))
6352 .or_default()
6353 .insert(language_server_id);
6354 }
6355
6356 pub fn update_diagnostic_entries(
6357 &mut self,
6358 server_id: LanguageServerId,
6359 abs_path: PathBuf,
6360 version: Option<i32>,
6361 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6362 cx: &mut Context<Self>,
6363 ) -> anyhow::Result<()> {
6364 self.merge_diagnostic_entries(server_id, abs_path, version, diagnostics, |_| false, cx)
6365 }
6366
6367 pub fn merge_diagnostic_entries<F: Fn(&Diagnostic) -> bool + Clone>(
6368 &mut self,
6369 server_id: LanguageServerId,
6370 abs_path: PathBuf,
6371 version: Option<i32>,
6372 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6373 filter: F,
6374 cx: &mut Context<Self>,
6375 ) -> Result<(), anyhow::Error> {
6376 let Some((worktree, relative_path)) =
6377 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
6378 else {
6379 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
6380 return Ok(());
6381 };
6382
6383 let project_path = ProjectPath {
6384 worktree_id: worktree.read(cx).id(),
6385 path: relative_path.into(),
6386 };
6387
6388 if let Some(buffer) = self.buffer_store.read(cx).get_by_path(&project_path, cx) {
6389 let snapshot = self
6390 .as_local_mut()
6391 .unwrap()
6392 .buffer_snapshot_for_lsp_version(&buffer, server_id, version, cx)?;
6393
6394 diagnostics.extend(
6395 buffer
6396 .read(cx)
6397 .get_diagnostics(server_id)
6398 .into_iter()
6399 .flat_map(|diag| {
6400 diag.iter().filter(|v| filter(&v.diagnostic)).map(|v| {
6401 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
6402 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
6403 DiagnosticEntry {
6404 range: start..end,
6405 diagnostic: v.diagnostic.clone(),
6406 }
6407 })
6408 }),
6409 );
6410
6411 self.as_local_mut().unwrap().update_buffer_diagnostics(
6412 &buffer,
6413 server_id,
6414 version,
6415 diagnostics.clone(),
6416 cx,
6417 )?;
6418 }
6419
6420 let updated = worktree.update(cx, |worktree, cx| {
6421 self.update_worktree_diagnostics(
6422 worktree.id(),
6423 server_id,
6424 project_path.path.clone(),
6425 diagnostics,
6426 cx,
6427 )
6428 })?;
6429 if updated {
6430 cx.emit(LspStoreEvent::DiagnosticsUpdated {
6431 language_server_id: server_id,
6432 path: project_path,
6433 })
6434 }
6435 Ok(())
6436 }
6437
6438 fn update_worktree_diagnostics(
6439 &mut self,
6440 worktree_id: WorktreeId,
6441 server_id: LanguageServerId,
6442 worktree_path: Arc<Path>,
6443 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
6444 _: &mut Context<Worktree>,
6445 ) -> Result<bool> {
6446 let local = match &mut self.mode {
6447 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
6448 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
6449 };
6450
6451 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
6452 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
6453 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
6454
6455 let old_summary = summaries_by_server_id
6456 .remove(&server_id)
6457 .unwrap_or_default();
6458
6459 let new_summary = DiagnosticSummary::new(&diagnostics);
6460 if new_summary.is_empty() {
6461 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
6462 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6463 diagnostics_by_server_id.remove(ix);
6464 }
6465 if diagnostics_by_server_id.is_empty() {
6466 diagnostics_for_tree.remove(&worktree_path);
6467 }
6468 }
6469 } else {
6470 summaries_by_server_id.insert(server_id, new_summary);
6471 let diagnostics_by_server_id = diagnostics_for_tree
6472 .entry(worktree_path.clone())
6473 .or_default();
6474 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
6475 Ok(ix) => {
6476 diagnostics_by_server_id[ix] = (server_id, diagnostics);
6477 }
6478 Err(ix) => {
6479 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
6480 }
6481 }
6482 }
6483
6484 if !old_summary.is_empty() || !new_summary.is_empty() {
6485 if let Some((downstream_client, project_id)) = &self.downstream_client {
6486 downstream_client
6487 .send(proto::UpdateDiagnosticSummary {
6488 project_id: *project_id,
6489 worktree_id: worktree_id.to_proto(),
6490 summary: Some(proto::DiagnosticSummary {
6491 path: worktree_path.to_proto(),
6492 language_server_id: server_id.0 as u64,
6493 error_count: new_summary.error_count as u32,
6494 warning_count: new_summary.warning_count as u32,
6495 }),
6496 })
6497 .log_err();
6498 }
6499 }
6500
6501 Ok(!old_summary.is_empty() || !new_summary.is_empty())
6502 }
6503
6504 pub fn open_buffer_for_symbol(
6505 &mut self,
6506 symbol: &Symbol,
6507 cx: &mut Context<Self>,
6508 ) -> Task<Result<Entity<Buffer>>> {
6509 if let Some((client, project_id)) = self.upstream_client() {
6510 let request = client.request(proto::OpenBufferForSymbol {
6511 project_id,
6512 symbol: Some(Self::serialize_symbol(symbol)),
6513 });
6514 cx.spawn(async move |this, cx| {
6515 let response = request.await?;
6516 let buffer_id = BufferId::new(response.buffer_id)?;
6517 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
6518 .await
6519 })
6520 } else if let Some(local) = self.as_local() {
6521 let Some(language_server_id) = local
6522 .language_server_ids
6523 .get(&(
6524 symbol.source_worktree_id,
6525 symbol.language_server_name.clone(),
6526 ))
6527 .and_then(|ids| {
6528 ids.contains(&symbol.source_language_server_id)
6529 .then_some(symbol.source_language_server_id)
6530 })
6531 else {
6532 return Task::ready(Err(anyhow!(
6533 "language server for worktree and language not found"
6534 )));
6535 };
6536
6537 let worktree_abs_path = if let Some(worktree_abs_path) = self
6538 .worktree_store
6539 .read(cx)
6540 .worktree_for_id(symbol.path.worktree_id, cx)
6541 .map(|worktree| worktree.read(cx).abs_path())
6542 {
6543 worktree_abs_path
6544 } else {
6545 return Task::ready(Err(anyhow!("worktree not found for symbol")));
6546 };
6547
6548 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
6549 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
6550 uri
6551 } else {
6552 return Task::ready(Err(anyhow!("invalid symbol path")));
6553 };
6554
6555 self.open_local_buffer_via_lsp(
6556 symbol_uri,
6557 language_server_id,
6558 symbol.language_server_name.clone(),
6559 cx,
6560 )
6561 } else {
6562 Task::ready(Err(anyhow!("no upstream client or local store")))
6563 }
6564 }
6565
6566 pub fn open_local_buffer_via_lsp(
6567 &mut self,
6568 mut abs_path: lsp::Url,
6569 language_server_id: LanguageServerId,
6570 language_server_name: LanguageServerName,
6571 cx: &mut Context<Self>,
6572 ) -> Task<Result<Entity<Buffer>>> {
6573 cx.spawn(async move |lsp_store, cx| {
6574 // Escape percent-encoded string.
6575 let current_scheme = abs_path.scheme().to_owned();
6576 let _ = abs_path.set_scheme("file");
6577
6578 let abs_path = abs_path
6579 .to_file_path()
6580 .map_err(|_| anyhow!("can't convert URI to path"))?;
6581 let p = abs_path.clone();
6582 let yarn_worktree = lsp_store
6583 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
6584 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
6585 cx.spawn(async move |this, cx| {
6586 let t = this
6587 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
6588 .ok()?;
6589 t.await
6590 })
6591 }),
6592 None => Task::ready(None),
6593 })?
6594 .await;
6595 let (worktree_root_target, known_relative_path) =
6596 if let Some((zip_root, relative_path)) = yarn_worktree {
6597 (zip_root, Some(relative_path))
6598 } else {
6599 (Arc::<Path>::from(abs_path.as_path()), None)
6600 };
6601 let (worktree, relative_path) = if let Some(result) =
6602 lsp_store.update(cx, |lsp_store, cx| {
6603 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6604 worktree_store.find_worktree(&worktree_root_target, cx)
6605 })
6606 })? {
6607 let relative_path =
6608 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
6609 (result.0, relative_path)
6610 } else {
6611 let worktree = lsp_store
6612 .update(cx, |lsp_store, cx| {
6613 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
6614 worktree_store.create_worktree(&worktree_root_target, false, cx)
6615 })
6616 })?
6617 .await?;
6618 if worktree.update(cx, |worktree, _| worktree.is_local())? {
6619 lsp_store
6620 .update(cx, |lsp_store, cx| {
6621 lsp_store.register_local_language_server(
6622 worktree.clone(),
6623 language_server_name,
6624 language_server_id,
6625 cx,
6626 )
6627 })
6628 .ok();
6629 }
6630 let worktree_root = worktree.update(cx, |worktree, _| worktree.abs_path())?;
6631 let relative_path = if let Some(known_path) = known_relative_path {
6632 known_path
6633 } else {
6634 abs_path.strip_prefix(worktree_root)?.into()
6635 };
6636 (worktree, relative_path)
6637 };
6638 let project_path = ProjectPath {
6639 worktree_id: worktree.update(cx, |worktree, _| worktree.id())?,
6640 path: relative_path,
6641 };
6642 lsp_store
6643 .update(cx, |lsp_store, cx| {
6644 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
6645 buffer_store.open_buffer(project_path, cx)
6646 })
6647 })?
6648 .await
6649 })
6650 }
6651
6652 fn request_multiple_lsp_locally<P, R>(
6653 &mut self,
6654 buffer: &Entity<Buffer>,
6655 position: Option<P>,
6656 request: R,
6657 cx: &mut Context<Self>,
6658 ) -> Task<Vec<R::Response>>
6659 where
6660 P: ToOffset,
6661 R: LspCommand + Clone,
6662 <R::LspRequest as lsp::request::Request>::Result: Send,
6663 <R::LspRequest as lsp::request::Request>::Params: Send,
6664 {
6665 let Some(local) = self.as_local() else {
6666 return Task::ready(Vec::new());
6667 };
6668
6669 let snapshot = buffer.read(cx).snapshot();
6670 let scope = position.and_then(|position| snapshot.language_scope_at(position));
6671
6672 let server_ids = buffer.update(cx, |buffer, cx| {
6673 local
6674 .language_servers_for_buffer(buffer, cx)
6675 .filter(|(adapter, _)| {
6676 scope
6677 .as_ref()
6678 .map(|scope| scope.language_allowed(&adapter.name))
6679 .unwrap_or(true)
6680 })
6681 .map(|(_, server)| server.server_id())
6682 .collect::<Vec<_>>()
6683 });
6684
6685 let mut response_results = server_ids
6686 .into_iter()
6687 .map(|server_id| {
6688 self.request_lsp(
6689 buffer.clone(),
6690 LanguageServerToQuery::Other(server_id),
6691 request.clone(),
6692 cx,
6693 )
6694 })
6695 .collect::<FuturesUnordered<_>>();
6696
6697 cx.spawn(async move |_, _| {
6698 let mut responses = Vec::with_capacity(response_results.len());
6699 while let Some(response_result) = response_results.next().await {
6700 if let Some(response) = response_result.log_err() {
6701 responses.push(response);
6702 }
6703 }
6704 responses
6705 })
6706 }
6707
6708 async fn handle_lsp_command<T: LspCommand>(
6709 this: Entity<Self>,
6710 envelope: TypedEnvelope<T::ProtoRequest>,
6711 mut cx: AsyncApp,
6712 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6713 where
6714 <T::LspRequest as lsp::request::Request>::Params: Send,
6715 <T::LspRequest as lsp::request::Request>::Result: Send,
6716 {
6717 let sender_id = envelope.original_sender_id().unwrap_or_default();
6718 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
6719 let buffer_handle = this.update(&mut cx, |this, cx| {
6720 this.buffer_store.read(cx).get_existing(buffer_id)
6721 })??;
6722 let request = T::from_proto(
6723 envelope.payload,
6724 this.clone(),
6725 buffer_handle.clone(),
6726 cx.clone(),
6727 )
6728 .await?;
6729 let response = this
6730 .update(&mut cx, |this, cx| {
6731 this.request_lsp(
6732 buffer_handle.clone(),
6733 LanguageServerToQuery::FirstCapable,
6734 request,
6735 cx,
6736 )
6737 })?
6738 .await?;
6739 this.update(&mut cx, |this, cx| {
6740 Ok(T::response_to_proto(
6741 response,
6742 this,
6743 sender_id,
6744 &buffer_handle.read(cx).version(),
6745 cx,
6746 ))
6747 })?
6748 }
6749
6750 async fn handle_multi_lsp_query(
6751 this: Entity<Self>,
6752 envelope: TypedEnvelope<proto::MultiLspQuery>,
6753 mut cx: AsyncApp,
6754 ) -> Result<proto::MultiLspQueryResponse> {
6755 let response_from_ssh = this.update(&mut cx, |this, _| {
6756 let (upstream_client, project_id) = this.upstream_client()?;
6757 let mut payload = envelope.payload.clone();
6758 payload.project_id = project_id;
6759
6760 Some(upstream_client.request(payload))
6761 })?;
6762 if let Some(response_from_ssh) = response_from_ssh {
6763 return response_from_ssh.await;
6764 }
6765
6766 let sender_id = envelope.original_sender_id().unwrap_or_default();
6767 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6768 let version = deserialize_version(&envelope.payload.version);
6769 let buffer = this.update(&mut cx, |this, cx| {
6770 this.buffer_store.read(cx).get_existing(buffer_id)
6771 })??;
6772 buffer
6773 .update(&mut cx, |buffer, _| {
6774 buffer.wait_for_version(version.clone())
6775 })?
6776 .await?;
6777 let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
6778 match envelope
6779 .payload
6780 .strategy
6781 .context("invalid request without the strategy")?
6782 {
6783 proto::multi_lsp_query::Strategy::All(_) => {
6784 // currently, there's only one multiple language servers query strategy,
6785 // so just ensure it's specified correctly
6786 }
6787 }
6788 match envelope.payload.request {
6789 Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
6790 let get_hover =
6791 GetHover::from_proto(get_hover, this.clone(), buffer.clone(), cx.clone())
6792 .await?;
6793 let all_hovers = this
6794 .update(&mut cx, |this, cx| {
6795 this.request_multiple_lsp_locally(
6796 &buffer,
6797 Some(get_hover.position),
6798 get_hover,
6799 cx,
6800 )
6801 })?
6802 .await
6803 .into_iter()
6804 .filter_map(|hover| remove_empty_hover_blocks(hover?));
6805 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6806 responses: all_hovers
6807 .map(|hover| proto::LspResponse {
6808 response: Some(proto::lsp_response::Response::GetHoverResponse(
6809 GetHover::response_to_proto(
6810 Some(hover),
6811 project,
6812 sender_id,
6813 &buffer_version,
6814 cx,
6815 ),
6816 )),
6817 })
6818 .collect(),
6819 })
6820 }
6821 Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
6822 let get_code_actions = GetCodeActions::from_proto(
6823 get_code_actions,
6824 this.clone(),
6825 buffer.clone(),
6826 cx.clone(),
6827 )
6828 .await?;
6829
6830 let all_actions = this
6831 .update(&mut cx, |project, cx| {
6832 project.request_multiple_lsp_locally(
6833 &buffer,
6834 Some(get_code_actions.range.start),
6835 get_code_actions,
6836 cx,
6837 )
6838 })?
6839 .await
6840 .into_iter();
6841
6842 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6843 responses: all_actions
6844 .map(|code_actions| proto::LspResponse {
6845 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
6846 GetCodeActions::response_to_proto(
6847 code_actions,
6848 project,
6849 sender_id,
6850 &buffer_version,
6851 cx,
6852 ),
6853 )),
6854 })
6855 .collect(),
6856 })
6857 }
6858 Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
6859 let get_signature_help = GetSignatureHelp::from_proto(
6860 get_signature_help,
6861 this.clone(),
6862 buffer.clone(),
6863 cx.clone(),
6864 )
6865 .await?;
6866
6867 let all_signatures = this
6868 .update(&mut cx, |project, cx| {
6869 project.request_multiple_lsp_locally(
6870 &buffer,
6871 Some(get_signature_help.position),
6872 get_signature_help,
6873 cx,
6874 )
6875 })?
6876 .await
6877 .into_iter();
6878
6879 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6880 responses: all_signatures
6881 .map(|signature_help| proto::LspResponse {
6882 response: Some(
6883 proto::lsp_response::Response::GetSignatureHelpResponse(
6884 GetSignatureHelp::response_to_proto(
6885 signature_help,
6886 project,
6887 sender_id,
6888 &buffer_version,
6889 cx,
6890 ),
6891 ),
6892 ),
6893 })
6894 .collect(),
6895 })
6896 }
6897 Some(proto::multi_lsp_query::Request::GetCodeLens(get_code_lens)) => {
6898 let get_code_lens = GetCodeLens::from_proto(
6899 get_code_lens,
6900 this.clone(),
6901 buffer.clone(),
6902 cx.clone(),
6903 )
6904 .await?;
6905
6906 let code_lens_actions = this
6907 .update(&mut cx, |project, cx| {
6908 project.request_multiple_lsp_locally(
6909 &buffer,
6910 None::<usize>,
6911 get_code_lens,
6912 cx,
6913 )
6914 })?
6915 .await
6916 .into_iter();
6917
6918 this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
6919 responses: code_lens_actions
6920 .map(|actions| proto::LspResponse {
6921 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
6922 GetCodeLens::response_to_proto(
6923 actions,
6924 project,
6925 sender_id,
6926 &buffer_version,
6927 cx,
6928 ),
6929 )),
6930 })
6931 .collect(),
6932 })
6933 }
6934 None => anyhow::bail!("empty multi lsp query request"),
6935 }
6936 }
6937
6938 async fn handle_apply_code_action(
6939 this: Entity<Self>,
6940 envelope: TypedEnvelope<proto::ApplyCodeAction>,
6941 mut cx: AsyncApp,
6942 ) -> Result<proto::ApplyCodeActionResponse> {
6943 let sender_id = envelope.original_sender_id().unwrap_or_default();
6944 let action = Self::deserialize_code_action(
6945 envelope
6946 .payload
6947 .action
6948 .ok_or_else(|| anyhow!("invalid action"))?,
6949 )?;
6950 let apply_code_action = this.update(&mut cx, |this, cx| {
6951 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6952 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
6953 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
6954 })??;
6955
6956 let project_transaction = apply_code_action.await?;
6957 let project_transaction = this.update(&mut cx, |this, cx| {
6958 this.buffer_store.update(cx, |buffer_store, cx| {
6959 buffer_store.serialize_project_transaction_for_peer(
6960 project_transaction,
6961 sender_id,
6962 cx,
6963 )
6964 })
6965 })?;
6966 Ok(proto::ApplyCodeActionResponse {
6967 transaction: Some(project_transaction),
6968 })
6969 }
6970
6971 async fn handle_register_buffer_with_language_servers(
6972 this: Entity<Self>,
6973 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
6974 mut cx: AsyncApp,
6975 ) -> Result<proto::Ack> {
6976 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
6977 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
6978 this.update(&mut cx, |this, cx| {
6979 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
6980 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
6981 project_id: upstream_project_id,
6982 buffer_id: buffer_id.to_proto(),
6983 });
6984 }
6985
6986 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
6987 anyhow::bail!("buffer is not open");
6988 };
6989
6990 let handle = this.register_buffer_with_language_servers(&buffer, false, cx);
6991 this.buffer_store().update(cx, |buffer_store, _| {
6992 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
6993 });
6994
6995 Ok(())
6996 })??;
6997 Ok(proto::Ack {})
6998 }
6999
7000 async fn handle_language_server_id_for_name(
7001 lsp_store: Entity<Self>,
7002 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7003 mut cx: AsyncApp,
7004 ) -> Result<proto::LanguageServerIdForNameResponse> {
7005 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7006 let name = &envelope.payload.name;
7007 lsp_store
7008 .update(&mut cx, |lsp_store, cx| {
7009 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7010 let server_id = buffer.update(cx, |buffer, cx| {
7011 lsp_store
7012 .language_servers_for_local_buffer(buffer, cx)
7013 .find_map(|(adapter, server)| {
7014 if adapter.name.0.as_ref() == name {
7015 Some(server.server_id())
7016 } else {
7017 None
7018 }
7019 })
7020 });
7021 Ok(server_id)
7022 })?
7023 .map(|server_id| proto::LanguageServerIdForNameResponse {
7024 server_id: server_id.map(|id| id.to_proto()),
7025 })
7026 }
7027
7028 async fn handle_rename_project_entry(
7029 this: Entity<Self>,
7030 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7031 mut cx: AsyncApp,
7032 ) -> Result<proto::ProjectEntryResponse> {
7033 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7034 let (worktree_id, worktree, old_path, is_dir) = this
7035 .update(&mut cx, |this, cx| {
7036 this.worktree_store
7037 .read(cx)
7038 .worktree_and_entry_for_id(entry_id, cx)
7039 .map(|(worktree, entry)| {
7040 (
7041 worktree.read(cx).id(),
7042 worktree,
7043 entry.path.clone(),
7044 entry.is_dir(),
7045 )
7046 })
7047 })?
7048 .ok_or_else(|| anyhow!("worktree not found"))?;
7049 let (old_abs_path, new_abs_path) = {
7050 let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
7051 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
7052 (root_path.join(&old_path), root_path.join(&new_path))
7053 };
7054
7055 Self::will_rename_entry(
7056 this.downgrade(),
7057 worktree_id,
7058 &old_abs_path,
7059 &new_abs_path,
7060 is_dir,
7061 cx.clone(),
7062 )
7063 .await;
7064 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
7065 this.update(&mut cx, |this, _| {
7066 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
7067 })
7068 .ok();
7069 response
7070 }
7071
7072 async fn handle_update_diagnostic_summary(
7073 this: Entity<Self>,
7074 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7075 mut cx: AsyncApp,
7076 ) -> Result<()> {
7077 this.update(&mut cx, |this, cx| {
7078 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7079 if let Some(message) = envelope.payload.summary {
7080 let project_path = ProjectPath {
7081 worktree_id,
7082 path: Arc::<Path>::from_proto(message.path),
7083 };
7084 let path = project_path.path.clone();
7085 let server_id = LanguageServerId(message.language_server_id as usize);
7086 let summary = DiagnosticSummary {
7087 error_count: message.error_count as usize,
7088 warning_count: message.warning_count as usize,
7089 };
7090
7091 if summary.is_empty() {
7092 if let Some(worktree_summaries) =
7093 this.diagnostic_summaries.get_mut(&worktree_id)
7094 {
7095 if let Some(summaries) = worktree_summaries.get_mut(&path) {
7096 summaries.remove(&server_id);
7097 if summaries.is_empty() {
7098 worktree_summaries.remove(&path);
7099 }
7100 }
7101 }
7102 } else {
7103 this.diagnostic_summaries
7104 .entry(worktree_id)
7105 .or_default()
7106 .entry(path)
7107 .or_default()
7108 .insert(server_id, summary);
7109 }
7110 if let Some((downstream_client, project_id)) = &this.downstream_client {
7111 downstream_client
7112 .send(proto::UpdateDiagnosticSummary {
7113 project_id: *project_id,
7114 worktree_id: worktree_id.to_proto(),
7115 summary: Some(proto::DiagnosticSummary {
7116 path: project_path.path.as_ref().to_proto(),
7117 language_server_id: server_id.0 as u64,
7118 error_count: summary.error_count as u32,
7119 warning_count: summary.warning_count as u32,
7120 }),
7121 })
7122 .log_err();
7123 }
7124 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7125 language_server_id: LanguageServerId(message.language_server_id as usize),
7126 path: project_path,
7127 });
7128 }
7129 Ok(())
7130 })?
7131 }
7132
7133 async fn handle_start_language_server(
7134 this: Entity<Self>,
7135 envelope: TypedEnvelope<proto::StartLanguageServer>,
7136 mut cx: AsyncApp,
7137 ) -> Result<()> {
7138 let server = envelope
7139 .payload
7140 .server
7141 .ok_or_else(|| anyhow!("invalid server"))?;
7142
7143 this.update(&mut cx, |this, cx| {
7144 let server_id = LanguageServerId(server.id as usize);
7145 this.language_server_statuses.insert(
7146 server_id,
7147 LanguageServerStatus {
7148 name: server.name.clone(),
7149 pending_work: Default::default(),
7150 has_pending_diagnostic_updates: false,
7151 progress_tokens: Default::default(),
7152 },
7153 );
7154 cx.emit(LspStoreEvent::LanguageServerAdded(
7155 server_id,
7156 LanguageServerName(server.name.into()),
7157 server.worktree_id.map(WorktreeId::from_proto),
7158 ));
7159 cx.notify();
7160 })?;
7161 Ok(())
7162 }
7163
7164 async fn handle_update_language_server(
7165 this: Entity<Self>,
7166 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7167 mut cx: AsyncApp,
7168 ) -> Result<()> {
7169 this.update(&mut cx, |this, cx| {
7170 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7171
7172 match envelope
7173 .payload
7174 .variant
7175 .ok_or_else(|| anyhow!("invalid variant"))?
7176 {
7177 proto::update_language_server::Variant::WorkStart(payload) => {
7178 this.on_lsp_work_start(
7179 language_server_id,
7180 payload.token,
7181 LanguageServerProgress {
7182 title: payload.title,
7183 is_disk_based_diagnostics_progress: false,
7184 is_cancellable: payload.is_cancellable.unwrap_or(false),
7185 message: payload.message,
7186 percentage: payload.percentage.map(|p| p as usize),
7187 last_update_at: cx.background_executor().now(),
7188 },
7189 cx,
7190 );
7191 }
7192
7193 proto::update_language_server::Variant::WorkProgress(payload) => {
7194 this.on_lsp_work_progress(
7195 language_server_id,
7196 payload.token,
7197 LanguageServerProgress {
7198 title: None,
7199 is_disk_based_diagnostics_progress: false,
7200 is_cancellable: payload.is_cancellable.unwrap_or(false),
7201 message: payload.message,
7202 percentage: payload.percentage.map(|p| p as usize),
7203 last_update_at: cx.background_executor().now(),
7204 },
7205 cx,
7206 );
7207 }
7208
7209 proto::update_language_server::Variant::WorkEnd(payload) => {
7210 this.on_lsp_work_end(language_server_id, payload.token, cx);
7211 }
7212
7213 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7214 this.disk_based_diagnostics_started(language_server_id, cx);
7215 }
7216
7217 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7218 this.disk_based_diagnostics_finished(language_server_id, cx)
7219 }
7220 }
7221
7222 Ok(())
7223 })?
7224 }
7225
7226 async fn handle_language_server_log(
7227 this: Entity<Self>,
7228 envelope: TypedEnvelope<proto::LanguageServerLog>,
7229 mut cx: AsyncApp,
7230 ) -> Result<()> {
7231 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7232 let log_type = envelope
7233 .payload
7234 .log_type
7235 .map(LanguageServerLogType::from_proto)
7236 .context("invalid language server log type")?;
7237
7238 let message = envelope.payload.message;
7239
7240 this.update(&mut cx, |_, cx| {
7241 cx.emit(LspStoreEvent::LanguageServerLog(
7242 language_server_id,
7243 log_type,
7244 message,
7245 ));
7246 })
7247 }
7248
7249 pub fn disk_based_diagnostics_started(
7250 &mut self,
7251 language_server_id: LanguageServerId,
7252 cx: &mut Context<Self>,
7253 ) {
7254 if let Some(language_server_status) =
7255 self.language_server_statuses.get_mut(&language_server_id)
7256 {
7257 language_server_status.has_pending_diagnostic_updates = true;
7258 }
7259
7260 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
7261 cx.emit(LspStoreEvent::LanguageServerUpdate {
7262 language_server_id,
7263 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
7264 Default::default(),
7265 ),
7266 })
7267 }
7268
7269 pub fn disk_based_diagnostics_finished(
7270 &mut self,
7271 language_server_id: LanguageServerId,
7272 cx: &mut Context<Self>,
7273 ) {
7274 if let Some(language_server_status) =
7275 self.language_server_statuses.get_mut(&language_server_id)
7276 {
7277 language_server_status.has_pending_diagnostic_updates = false;
7278 }
7279
7280 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
7281 cx.emit(LspStoreEvent::LanguageServerUpdate {
7282 language_server_id,
7283 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
7284 Default::default(),
7285 ),
7286 })
7287 }
7288
7289 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
7290 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
7291 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
7292 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
7293 // the language server might take some time to publish diagnostics.
7294 fn simulate_disk_based_diagnostics_events_if_needed(
7295 &mut self,
7296 language_server_id: LanguageServerId,
7297 cx: &mut Context<Self>,
7298 ) {
7299 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
7300
7301 let Some(LanguageServerState::Running {
7302 simulate_disk_based_diagnostics_completion,
7303 adapter,
7304 ..
7305 }) = self
7306 .as_local_mut()
7307 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
7308 else {
7309 return;
7310 };
7311
7312 if adapter.disk_based_diagnostics_progress_token.is_some() {
7313 return;
7314 }
7315
7316 let prev_task =
7317 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
7318 cx.background_executor()
7319 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
7320 .await;
7321
7322 this.update(cx, |this, cx| {
7323 this.disk_based_diagnostics_finished(language_server_id, cx);
7324
7325 if let Some(LanguageServerState::Running {
7326 simulate_disk_based_diagnostics_completion,
7327 ..
7328 }) = this.as_local_mut().and_then(|local_store| {
7329 local_store.language_servers.get_mut(&language_server_id)
7330 }) {
7331 *simulate_disk_based_diagnostics_completion = None;
7332 }
7333 })
7334 .ok();
7335 }));
7336
7337 if prev_task.is_none() {
7338 self.disk_based_diagnostics_started(language_server_id, cx);
7339 }
7340 }
7341
7342 pub fn language_server_statuses(
7343 &self,
7344 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
7345 self.language_server_statuses
7346 .iter()
7347 .map(|(key, value)| (*key, value))
7348 }
7349
7350 pub(super) fn did_rename_entry(
7351 &self,
7352 worktree_id: WorktreeId,
7353 old_path: &Path,
7354 new_path: &Path,
7355 is_dir: bool,
7356 ) {
7357 maybe!({
7358 let local_store = self.as_local()?;
7359
7360 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
7361 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
7362
7363 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7364 let Some(filter) = local_store
7365 .language_server_paths_watched_for_rename
7366 .get(&language_server.server_id())
7367 else {
7368 continue;
7369 };
7370
7371 if filter.should_send_did_rename(&old_uri, is_dir) {
7372 language_server
7373 .notify::<DidRenameFiles>(&RenameFilesParams {
7374 files: vec![FileRename {
7375 old_uri: old_uri.clone(),
7376 new_uri: new_uri.clone(),
7377 }],
7378 })
7379 .log_err();
7380 }
7381 }
7382 Some(())
7383 });
7384 }
7385
7386 pub(super) fn will_rename_entry(
7387 this: WeakEntity<Self>,
7388 worktree_id: WorktreeId,
7389 old_path: &Path,
7390 new_path: &Path,
7391 is_dir: bool,
7392 cx: AsyncApp,
7393 ) -> Task<()> {
7394 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
7395 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
7396 cx.spawn(async move |cx| {
7397 let mut tasks = vec![];
7398 this.update(cx, |this, cx| {
7399 let local_store = this.as_local()?;
7400 let old_uri = old_uri?;
7401 let new_uri = new_uri?;
7402 for language_server in local_store.language_servers_for_worktree(worktree_id) {
7403 let Some(filter) = local_store
7404 .language_server_paths_watched_for_rename
7405 .get(&language_server.server_id())
7406 else {
7407 continue;
7408 };
7409 let Some(adapter) =
7410 this.language_server_adapter_for_id(language_server.server_id())
7411 else {
7412 continue;
7413 };
7414 if filter.should_send_will_rename(&old_uri, is_dir) {
7415 let apply_edit = cx.spawn({
7416 let old_uri = old_uri.clone();
7417 let new_uri = new_uri.clone();
7418 let language_server = language_server.clone();
7419 async move |this, cx| {
7420 let edit = language_server
7421 .request::<WillRenameFiles>(RenameFilesParams {
7422 files: vec![FileRename { old_uri, new_uri }],
7423 })
7424 .log_err()
7425 .await
7426 .flatten()?;
7427
7428 LocalLspStore::deserialize_workspace_edit(
7429 this.upgrade()?,
7430 edit,
7431 false,
7432 adapter.clone(),
7433 language_server.clone(),
7434 cx,
7435 )
7436 .await
7437 .ok();
7438 Some(())
7439 }
7440 });
7441 tasks.push(apply_edit);
7442 }
7443 }
7444 Some(())
7445 })
7446 .ok()
7447 .flatten();
7448 for task in tasks {
7449 // Await on tasks sequentially so that the order of application of edits is deterministic
7450 // (at least with regards to the order of registration of language servers)
7451 task.await;
7452 }
7453 })
7454 }
7455
7456 fn lsp_notify_abs_paths_changed(
7457 &mut self,
7458 server_id: LanguageServerId,
7459 changes: Vec<PathEvent>,
7460 ) {
7461 maybe!({
7462 let server = self.language_server_for_id(server_id)?;
7463 let changes = changes
7464 .into_iter()
7465 .filter_map(|event| {
7466 let typ = match event.kind? {
7467 PathEventKind::Created => lsp::FileChangeType::CREATED,
7468 PathEventKind::Removed => lsp::FileChangeType::DELETED,
7469 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
7470 };
7471 Some(lsp::FileEvent {
7472 uri: lsp::Url::from_file_path(&event.path).ok()?,
7473 typ,
7474 })
7475 })
7476 .collect::<Vec<_>>();
7477 if !changes.is_empty() {
7478 server
7479 .notify::<lsp::notification::DidChangeWatchedFiles>(
7480 &lsp::DidChangeWatchedFilesParams { changes },
7481 )
7482 .log_err();
7483 }
7484 Some(())
7485 });
7486 }
7487
7488 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7489 let local_lsp_store = self.as_local()?;
7490 if let Some(LanguageServerState::Running { server, .. }) =
7491 local_lsp_store.language_servers.get(&id)
7492 {
7493 Some(server.clone())
7494 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
7495 Some(Arc::clone(server))
7496 } else {
7497 None
7498 }
7499 }
7500
7501 fn on_lsp_progress(
7502 &mut self,
7503 progress: lsp::ProgressParams,
7504 language_server_id: LanguageServerId,
7505 disk_based_diagnostics_progress_token: Option<String>,
7506 cx: &mut Context<Self>,
7507 ) {
7508 let token = match progress.token {
7509 lsp::NumberOrString::String(token) => token,
7510 lsp::NumberOrString::Number(token) => {
7511 log::info!("skipping numeric progress token {}", token);
7512 return;
7513 }
7514 };
7515
7516 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
7517 let language_server_status =
7518 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7519 status
7520 } else {
7521 return;
7522 };
7523
7524 if !language_server_status.progress_tokens.contains(&token) {
7525 return;
7526 }
7527
7528 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
7529 .as_ref()
7530 .map_or(false, |disk_based_token| {
7531 token.starts_with(disk_based_token)
7532 });
7533
7534 match progress {
7535 lsp::WorkDoneProgress::Begin(report) => {
7536 if is_disk_based_diagnostics_progress {
7537 self.disk_based_diagnostics_started(language_server_id, cx);
7538 }
7539 self.on_lsp_work_start(
7540 language_server_id,
7541 token.clone(),
7542 LanguageServerProgress {
7543 title: Some(report.title),
7544 is_disk_based_diagnostics_progress,
7545 is_cancellable: report.cancellable.unwrap_or(false),
7546 message: report.message.clone(),
7547 percentage: report.percentage.map(|p| p as usize),
7548 last_update_at: cx.background_executor().now(),
7549 },
7550 cx,
7551 );
7552 }
7553 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
7554 language_server_id,
7555 token,
7556 LanguageServerProgress {
7557 title: None,
7558 is_disk_based_diagnostics_progress,
7559 is_cancellable: report.cancellable.unwrap_or(false),
7560 message: report.message,
7561 percentage: report.percentage.map(|p| p as usize),
7562 last_update_at: cx.background_executor().now(),
7563 },
7564 cx,
7565 ),
7566 lsp::WorkDoneProgress::End(_) => {
7567 language_server_status.progress_tokens.remove(&token);
7568 self.on_lsp_work_end(language_server_id, token.clone(), cx);
7569 if is_disk_based_diagnostics_progress {
7570 self.disk_based_diagnostics_finished(language_server_id, cx);
7571 }
7572 }
7573 }
7574 }
7575
7576 fn on_lsp_work_start(
7577 &mut self,
7578 language_server_id: LanguageServerId,
7579 token: String,
7580 progress: LanguageServerProgress,
7581 cx: &mut Context<Self>,
7582 ) {
7583 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7584 status.pending_work.insert(token.clone(), progress.clone());
7585 cx.notify();
7586 }
7587 cx.emit(LspStoreEvent::LanguageServerUpdate {
7588 language_server_id,
7589 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
7590 token,
7591 title: progress.title,
7592 message: progress.message,
7593 percentage: progress.percentage.map(|p| p as u32),
7594 is_cancellable: Some(progress.is_cancellable),
7595 }),
7596 })
7597 }
7598
7599 fn on_lsp_work_progress(
7600 &mut self,
7601 language_server_id: LanguageServerId,
7602 token: String,
7603 progress: LanguageServerProgress,
7604 cx: &mut Context<Self>,
7605 ) {
7606 let mut did_update = false;
7607 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7608 match status.pending_work.entry(token.clone()) {
7609 btree_map::Entry::Vacant(entry) => {
7610 entry.insert(progress.clone());
7611 did_update = true;
7612 }
7613 btree_map::Entry::Occupied(mut entry) => {
7614 let entry = entry.get_mut();
7615 if (progress.last_update_at - entry.last_update_at)
7616 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
7617 {
7618 entry.last_update_at = progress.last_update_at;
7619 if progress.message.is_some() {
7620 entry.message = progress.message.clone();
7621 }
7622 if progress.percentage.is_some() {
7623 entry.percentage = progress.percentage;
7624 }
7625 if progress.is_cancellable != entry.is_cancellable {
7626 entry.is_cancellable = progress.is_cancellable;
7627 }
7628 did_update = true;
7629 }
7630 }
7631 }
7632 }
7633
7634 if did_update {
7635 cx.emit(LspStoreEvent::LanguageServerUpdate {
7636 language_server_id,
7637 message: proto::update_language_server::Variant::WorkProgress(
7638 proto::LspWorkProgress {
7639 token,
7640 message: progress.message,
7641 percentage: progress.percentage.map(|p| p as u32),
7642 is_cancellable: Some(progress.is_cancellable),
7643 },
7644 ),
7645 })
7646 }
7647 }
7648
7649 fn on_lsp_work_end(
7650 &mut self,
7651 language_server_id: LanguageServerId,
7652 token: String,
7653 cx: &mut Context<Self>,
7654 ) {
7655 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
7656 if let Some(work) = status.pending_work.remove(&token) {
7657 if !work.is_disk_based_diagnostics_progress {
7658 cx.emit(LspStoreEvent::RefreshInlayHints);
7659 }
7660 }
7661 cx.notify();
7662 }
7663
7664 cx.emit(LspStoreEvent::LanguageServerUpdate {
7665 language_server_id,
7666 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
7667 })
7668 }
7669
7670 pub async fn handle_resolve_completion_documentation(
7671 this: Entity<Self>,
7672 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7673 mut cx: AsyncApp,
7674 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7675 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7676
7677 let completion = this
7678 .read_with(&cx, |this, cx| {
7679 let id = LanguageServerId(envelope.payload.language_server_id as usize);
7680 let Some(server) = this.language_server_for_id(id) else {
7681 return Err(anyhow!("No language server {id}"));
7682 };
7683
7684 Ok(cx.background_spawn(async move {
7685 let can_resolve = server
7686 .capabilities()
7687 .completion_provider
7688 .as_ref()
7689 .and_then(|options| options.resolve_provider)
7690 .unwrap_or(false);
7691 if can_resolve {
7692 server
7693 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
7694 .await
7695 } else {
7696 anyhow::Ok(lsp_completion)
7697 }
7698 }))
7699 })??
7700 .await?;
7701
7702 let mut documentation_is_markdown = false;
7703 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
7704 let documentation = match completion.documentation {
7705 Some(lsp::Documentation::String(text)) => text,
7706
7707 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7708 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
7709 value
7710 }
7711
7712 _ => String::new(),
7713 };
7714
7715 // If we have a new buffer_id, that means we're talking to a new client
7716 // and want to check for new text_edits in the completion too.
7717 let mut old_start = None;
7718 let mut old_end = None;
7719 let mut new_text = String::default();
7720 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
7721 let buffer_snapshot = this.update(&mut cx, |this, cx| {
7722 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7723 anyhow::Ok(buffer.read(cx).snapshot())
7724 })??;
7725
7726 if let Some(text_edit) = completion.text_edit.as_ref() {
7727 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
7728
7729 if let Some((old_range, mut text_edit_new_text)) = edit {
7730 LineEnding::normalize(&mut text_edit_new_text);
7731
7732 new_text = text_edit_new_text;
7733 old_start = Some(serialize_anchor(&old_range.start));
7734 old_end = Some(serialize_anchor(&old_range.end));
7735 }
7736 }
7737 }
7738
7739 Ok(proto::ResolveCompletionDocumentationResponse {
7740 documentation,
7741 documentation_is_markdown,
7742 old_start,
7743 old_end,
7744 new_text,
7745 lsp_completion,
7746 })
7747 }
7748
7749 async fn handle_on_type_formatting(
7750 this: Entity<Self>,
7751 envelope: TypedEnvelope<proto::OnTypeFormatting>,
7752 mut cx: AsyncApp,
7753 ) -> Result<proto::OnTypeFormattingResponse> {
7754 let on_type_formatting = this.update(&mut cx, |this, cx| {
7755 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7756 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7757 let position = envelope
7758 .payload
7759 .position
7760 .and_then(deserialize_anchor)
7761 .ok_or_else(|| anyhow!("invalid position"))?;
7762 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7763 buffer,
7764 position,
7765 envelope.payload.trigger.clone(),
7766 cx,
7767 ))
7768 })??;
7769
7770 let transaction = on_type_formatting
7771 .await?
7772 .as_ref()
7773 .map(language::proto::serialize_transaction);
7774 Ok(proto::OnTypeFormattingResponse { transaction })
7775 }
7776
7777 async fn handle_refresh_inlay_hints(
7778 this: Entity<Self>,
7779 _: TypedEnvelope<proto::RefreshInlayHints>,
7780 mut cx: AsyncApp,
7781 ) -> Result<proto::Ack> {
7782 this.update(&mut cx, |_, cx| {
7783 cx.emit(LspStoreEvent::RefreshInlayHints);
7784 })?;
7785 Ok(proto::Ack {})
7786 }
7787
7788 async fn handle_inlay_hints(
7789 this: Entity<Self>,
7790 envelope: TypedEnvelope<proto::InlayHints>,
7791 mut cx: AsyncApp,
7792 ) -> Result<proto::InlayHintsResponse> {
7793 let sender_id = envelope.original_sender_id().unwrap_or_default();
7794 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7795 let buffer = this.update(&mut cx, |this, cx| {
7796 this.buffer_store.read(cx).get_existing(buffer_id)
7797 })??;
7798 buffer
7799 .update(&mut cx, |buffer, _| {
7800 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7801 })?
7802 .await
7803 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
7804
7805 let start = envelope
7806 .payload
7807 .start
7808 .and_then(deserialize_anchor)
7809 .context("missing range start")?;
7810 let end = envelope
7811 .payload
7812 .end
7813 .and_then(deserialize_anchor)
7814 .context("missing range end")?;
7815 let buffer_hints = this
7816 .update(&mut cx, |lsp_store, cx| {
7817 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
7818 })?
7819 .await
7820 .context("inlay hints fetch")?;
7821
7822 this.update(&mut cx, |project, cx| {
7823 InlayHints::response_to_proto(
7824 buffer_hints,
7825 project,
7826 sender_id,
7827 &buffer.read(cx).version(),
7828 cx,
7829 )
7830 })
7831 }
7832
7833 async fn handle_resolve_inlay_hint(
7834 this: Entity<Self>,
7835 envelope: TypedEnvelope<proto::ResolveInlayHint>,
7836 mut cx: AsyncApp,
7837 ) -> Result<proto::ResolveInlayHintResponse> {
7838 let proto_hint = envelope
7839 .payload
7840 .hint
7841 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7842 let hint = InlayHints::proto_to_project_hint(proto_hint)
7843 .context("resolved proto inlay hint conversion")?;
7844 let buffer = this.update(&mut cx, |this, cx| {
7845 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7846 this.buffer_store.read(cx).get_existing(buffer_id)
7847 })??;
7848 let response_hint = this
7849 .update(&mut cx, |this, cx| {
7850 this.resolve_inlay_hint(
7851 hint,
7852 buffer,
7853 LanguageServerId(envelope.payload.language_server_id as usize),
7854 cx,
7855 )
7856 })?
7857 .await
7858 .context("inlay hints fetch")?;
7859 Ok(proto::ResolveInlayHintResponse {
7860 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7861 })
7862 }
7863
7864 async fn handle_refresh_code_lens(
7865 this: Entity<Self>,
7866 _: TypedEnvelope<proto::RefreshCodeLens>,
7867 mut cx: AsyncApp,
7868 ) -> Result<proto::Ack> {
7869 this.update(&mut cx, |_, cx| {
7870 cx.emit(LspStoreEvent::RefreshCodeLens);
7871 })?;
7872 Ok(proto::Ack {})
7873 }
7874
7875 async fn handle_open_buffer_for_symbol(
7876 this: Entity<Self>,
7877 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7878 mut cx: AsyncApp,
7879 ) -> Result<proto::OpenBufferForSymbolResponse> {
7880 let peer_id = envelope.original_sender_id().unwrap_or_default();
7881 let symbol = envelope
7882 .payload
7883 .symbol
7884 .ok_or_else(|| anyhow!("invalid symbol"))?;
7885 let symbol = Self::deserialize_symbol(symbol)?;
7886 let symbol = this.update(&mut cx, |this, _| {
7887 let signature = this.symbol_signature(&symbol.path);
7888 if signature == symbol.signature {
7889 Ok(symbol)
7890 } else {
7891 Err(anyhow!("invalid symbol signature"))
7892 }
7893 })??;
7894 let buffer = this
7895 .update(&mut cx, |this, cx| {
7896 this.open_buffer_for_symbol(
7897 &Symbol {
7898 language_server_name: symbol.language_server_name,
7899 source_worktree_id: symbol.source_worktree_id,
7900 source_language_server_id: symbol.source_language_server_id,
7901 path: symbol.path,
7902 name: symbol.name,
7903 kind: symbol.kind,
7904 range: symbol.range,
7905 signature: symbol.signature,
7906 label: CodeLabel {
7907 text: Default::default(),
7908 runs: Default::default(),
7909 filter_range: Default::default(),
7910 },
7911 },
7912 cx,
7913 )
7914 })?
7915 .await?;
7916
7917 this.update(&mut cx, |this, cx| {
7918 let is_private = buffer
7919 .read(cx)
7920 .file()
7921 .map(|f| f.is_private())
7922 .unwrap_or_default();
7923 if is_private {
7924 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
7925 } else {
7926 this.buffer_store
7927 .update(cx, |buffer_store, cx| {
7928 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
7929 })
7930 .detach_and_log_err(cx);
7931 let buffer_id = buffer.read(cx).remote_id().to_proto();
7932 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
7933 }
7934 })?
7935 }
7936
7937 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7938 let mut hasher = Sha256::new();
7939 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7940 hasher.update(project_path.path.to_string_lossy().as_bytes());
7941 hasher.update(self.nonce.to_be_bytes());
7942 hasher.finalize().as_slice().try_into().unwrap()
7943 }
7944
7945 pub async fn handle_get_project_symbols(
7946 this: Entity<Self>,
7947 envelope: TypedEnvelope<proto::GetProjectSymbols>,
7948 mut cx: AsyncApp,
7949 ) -> Result<proto::GetProjectSymbolsResponse> {
7950 let symbols = this
7951 .update(&mut cx, |this, cx| {
7952 this.symbols(&envelope.payload.query, cx)
7953 })?
7954 .await?;
7955
7956 Ok(proto::GetProjectSymbolsResponse {
7957 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
7958 })
7959 }
7960
7961 pub async fn handle_restart_language_servers(
7962 this: Entity<Self>,
7963 envelope: TypedEnvelope<proto::RestartLanguageServers>,
7964 mut cx: AsyncApp,
7965 ) -> Result<proto::Ack> {
7966 this.update(&mut cx, |this, cx| {
7967 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
7968 this.restart_language_servers_for_buffers(buffers, cx);
7969 })?;
7970
7971 Ok(proto::Ack {})
7972 }
7973
7974 pub async fn handle_cancel_language_server_work(
7975 this: Entity<Self>,
7976 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
7977 mut cx: AsyncApp,
7978 ) -> Result<proto::Ack> {
7979 this.update(&mut cx, |this, cx| {
7980 if let Some(work) = envelope.payload.work {
7981 match work {
7982 proto::cancel_language_server_work::Work::Buffers(buffers) => {
7983 let buffers =
7984 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
7985 this.cancel_language_server_work_for_buffers(buffers, cx);
7986 }
7987 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
7988 let server_id = LanguageServerId::from_proto(work.language_server_id);
7989 this.cancel_language_server_work(server_id, work.token, cx);
7990 }
7991 }
7992 }
7993 })?;
7994
7995 Ok(proto::Ack {})
7996 }
7997
7998 fn buffer_ids_to_buffers(
7999 &mut self,
8000 buffer_ids: impl Iterator<Item = u64>,
8001 cx: &mut Context<Self>,
8002 ) -> Vec<Entity<Buffer>> {
8003 buffer_ids
8004 .into_iter()
8005 .flat_map(|buffer_id| {
8006 self.buffer_store
8007 .read(cx)
8008 .get(BufferId::new(buffer_id).log_err()?)
8009 })
8010 .collect::<Vec<_>>()
8011 }
8012
8013 async fn handle_apply_additional_edits_for_completion(
8014 this: Entity<Self>,
8015 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8016 mut cx: AsyncApp,
8017 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8018 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8019 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8020 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8021 let completion = Self::deserialize_completion(
8022 envelope
8023 .payload
8024 .completion
8025 .ok_or_else(|| anyhow!("invalid completion"))?,
8026 )?;
8027 anyhow::Ok((buffer, completion))
8028 })??;
8029
8030 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8031 this.apply_additional_edits_for_completion(
8032 buffer,
8033 Rc::new(RefCell::new(Box::new([Completion {
8034 old_range: completion.old_range,
8035 new_text: completion.new_text,
8036 source: completion.source,
8037 documentation: None,
8038 label: CodeLabel {
8039 text: Default::default(),
8040 runs: Default::default(),
8041 filter_range: Default::default(),
8042 },
8043 icon_path: None,
8044 confirm: None,
8045 }]))),
8046 0,
8047 false,
8048 cx,
8049 )
8050 })?;
8051
8052 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8053 transaction: apply_additional_edits
8054 .await?
8055 .as_ref()
8056 .map(language::proto::serialize_transaction),
8057 })
8058 }
8059
8060 pub fn last_formatting_failure(&self) -> Option<&str> {
8061 self.last_formatting_failure.as_deref()
8062 }
8063
8064 pub fn reset_last_formatting_failure(&mut self) {
8065 self.last_formatting_failure = None;
8066 }
8067
8068 pub fn environment_for_buffer(
8069 &self,
8070 buffer: &Entity<Buffer>,
8071 cx: &mut Context<Self>,
8072 ) -> Shared<Task<Option<HashMap<String, String>>>> {
8073 let worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
8074 let worktree_abs_path = worktree_id.and_then(|worktree_id| {
8075 self.worktree_store
8076 .read(cx)
8077 .worktree_for_id(worktree_id, cx)
8078 .map(|entry| entry.read(cx).abs_path().clone())
8079 });
8080
8081 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
8082 environment.update(cx, |env, cx| env.get_environment(worktree_abs_path, cx))
8083 } else {
8084 Task::ready(None).shared()
8085 }
8086 }
8087
8088 pub fn format(
8089 &mut self,
8090 buffers: HashSet<Entity<Buffer>>,
8091 target: LspFormatTarget,
8092 push_to_history: bool,
8093 trigger: FormatTrigger,
8094 cx: &mut Context<Self>,
8095 ) -> Task<anyhow::Result<ProjectTransaction>> {
8096 let logger = zlog::scoped!("format");
8097 if let Some(_) = self.as_local() {
8098 zlog::trace!(logger => "Formatting locally");
8099 let logger = zlog::scoped!(logger => "local");
8100 let buffers = buffers
8101 .into_iter()
8102 .map(|buffer_handle| {
8103 let buffer = buffer_handle.read(cx);
8104 let buffer_abs_path = File::from_dyn(buffer.file())
8105 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
8106
8107 (buffer_handle, buffer_abs_path, buffer.remote_id())
8108 })
8109 .collect::<Vec<_>>();
8110
8111 cx.spawn(async move |lsp_store, cx| {
8112 let mut formattable_buffers = Vec::with_capacity(buffers.len());
8113
8114 for (handle, abs_path, id) in buffers {
8115 let env = lsp_store
8116 .update(cx, |lsp_store, cx| {
8117 lsp_store.environment_for_buffer(&handle, cx)
8118 })?
8119 .await;
8120
8121 let ranges = match &target {
8122 LspFormatTarget::Buffers => None,
8123 LspFormatTarget::Ranges(ranges) => {
8124 let Some(ranges) = ranges.get(&id) else {
8125 return Err(anyhow!("No format ranges provided for buffer"));
8126 };
8127 Some(ranges.clone())
8128 }
8129 };
8130
8131 formattable_buffers.push(FormattableBuffer {
8132 handle,
8133 abs_path,
8134 env,
8135 ranges,
8136 });
8137 }
8138 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
8139
8140 let format_timer = zlog::time!(logger => "Formatting buffers");
8141 let result = LocalLspStore::format_locally(
8142 lsp_store.clone(),
8143 formattable_buffers,
8144 push_to_history,
8145 trigger,
8146 logger,
8147 cx,
8148 )
8149 .await;
8150 format_timer.end();
8151
8152 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
8153
8154 lsp_store.update(cx, |lsp_store, _| {
8155 lsp_store.update_last_formatting_failure(&result);
8156 })?;
8157
8158 result
8159 })
8160 } else if let Some((client, project_id)) = self.upstream_client() {
8161 zlog::trace!(logger => "Formatting remotely");
8162 let logger = zlog::scoped!(logger => "remote");
8163 // Don't support formatting ranges via remote
8164 match target {
8165 LspFormatTarget::Buffers => {}
8166 LspFormatTarget::Ranges(_) => {
8167 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
8168 return Task::ready(Ok(ProjectTransaction::default()));
8169 }
8170 }
8171
8172 let buffer_store = self.buffer_store();
8173 cx.spawn(async move |lsp_store, cx| {
8174 zlog::trace!(logger => "Sending remote format request");
8175 let request_timer = zlog::time!(logger => "remote format request");
8176 let result = client
8177 .request(proto::FormatBuffers {
8178 project_id,
8179 trigger: trigger as i32,
8180 buffer_ids: buffers
8181 .iter()
8182 .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
8183 .collect::<Result<_>>()?,
8184 })
8185 .await
8186 .and_then(|result| result.transaction.context("missing transaction"));
8187 request_timer.end();
8188
8189 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
8190
8191 lsp_store.update(cx, |lsp_store, _| {
8192 lsp_store.update_last_formatting_failure(&result);
8193 })?;
8194
8195 let transaction_response = result?;
8196 let _timer = zlog::time!(logger => "deserializing project transaction");
8197 buffer_store
8198 .update(cx, |buffer_store, cx| {
8199 buffer_store.deserialize_project_transaction(
8200 transaction_response,
8201 push_to_history,
8202 cx,
8203 )
8204 })?
8205 .await
8206 })
8207 } else {
8208 zlog::trace!(logger => "Not formatting");
8209 Task::ready(Ok(ProjectTransaction::default()))
8210 }
8211 }
8212
8213 async fn handle_format_buffers(
8214 this: Entity<Self>,
8215 envelope: TypedEnvelope<proto::FormatBuffers>,
8216 mut cx: AsyncApp,
8217 ) -> Result<proto::FormatBuffersResponse> {
8218 let sender_id = envelope.original_sender_id().unwrap_or_default();
8219 let format = this.update(&mut cx, |this, cx| {
8220 let mut buffers = HashSet::default();
8221 for buffer_id in &envelope.payload.buffer_ids {
8222 let buffer_id = BufferId::new(*buffer_id)?;
8223 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8224 }
8225 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8226 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
8227 })??;
8228
8229 let project_transaction = format.await?;
8230 let project_transaction = this.update(&mut cx, |this, cx| {
8231 this.buffer_store.update(cx, |buffer_store, cx| {
8232 buffer_store.serialize_project_transaction_for_peer(
8233 project_transaction,
8234 sender_id,
8235 cx,
8236 )
8237 })
8238 })?;
8239 Ok(proto::FormatBuffersResponse {
8240 transaction: Some(project_transaction),
8241 })
8242 }
8243
8244 async fn handle_apply_code_action_kind(
8245 this: Entity<Self>,
8246 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
8247 mut cx: AsyncApp,
8248 ) -> Result<proto::ApplyCodeActionKindResponse> {
8249 let sender_id = envelope.original_sender_id().unwrap_or_default();
8250 let format = this.update(&mut cx, |this, cx| {
8251 let mut buffers = HashSet::default();
8252 for buffer_id in &envelope.payload.buffer_ids {
8253 let buffer_id = BufferId::new(*buffer_id)?;
8254 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
8255 }
8256 let kind = match envelope.payload.kind.as_str() {
8257 "" => Ok(CodeActionKind::EMPTY),
8258 "quickfix" => Ok(CodeActionKind::QUICKFIX),
8259 "refactor" => Ok(CodeActionKind::REFACTOR),
8260 "refactor.extract" => Ok(CodeActionKind::REFACTOR_EXTRACT),
8261 "refactor.inline" => Ok(CodeActionKind::REFACTOR_INLINE),
8262 "refactor.rewrite" => Ok(CodeActionKind::REFACTOR_REWRITE),
8263 "source" => Ok(CodeActionKind::SOURCE),
8264 "source.organizeImports" => Ok(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
8265 "source.fixAll" => Ok(CodeActionKind::SOURCE_FIX_ALL),
8266 _ => Err(anyhow!("Invalid code action kind")),
8267 }?;
8268 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
8269 })??;
8270
8271 let project_transaction = format.await?;
8272 let project_transaction = this.update(&mut cx, |this, cx| {
8273 this.buffer_store.update(cx, |buffer_store, cx| {
8274 buffer_store.serialize_project_transaction_for_peer(
8275 project_transaction,
8276 sender_id,
8277 cx,
8278 )
8279 })
8280 })?;
8281 Ok(proto::ApplyCodeActionKindResponse {
8282 transaction: Some(project_transaction),
8283 })
8284 }
8285
8286 async fn shutdown_language_server(
8287 server_state: Option<LanguageServerState>,
8288 name: LanguageServerName,
8289 cx: &mut AsyncApp,
8290 ) {
8291 let server = match server_state {
8292 Some(LanguageServerState::Starting { startup, .. }) => {
8293 let mut timer = cx
8294 .background_executor()
8295 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
8296 .fuse();
8297
8298 select! {
8299 server = startup.fuse() => server,
8300 _ = timer => {
8301 log::info!(
8302 "timeout waiting for language server {} to finish launching before stopping",
8303 name
8304 );
8305 None
8306 },
8307 }
8308 }
8309
8310 Some(LanguageServerState::Running { server, .. }) => Some(server),
8311
8312 None => None,
8313 };
8314
8315 if let Some(server) = server {
8316 if let Some(shutdown) = server.shutdown() {
8317 shutdown.await;
8318 }
8319 }
8320 }
8321
8322 // Returns a list of all of the worktrees which no longer have a language server and the root path
8323 // for the stopped server
8324 fn stop_local_language_server(
8325 &mut self,
8326 server_id: LanguageServerId,
8327 name: LanguageServerName,
8328 cx: &mut Context<Self>,
8329 ) -> Task<Vec<WorktreeId>> {
8330 let local = match &mut self.mode {
8331 LspStoreMode::Local(local) => local,
8332 _ => {
8333 return Task::ready(Vec::new());
8334 }
8335 };
8336
8337 let mut orphaned_worktrees = vec![];
8338 // Remove this server ID from all entries in the given worktree.
8339 local.language_server_ids.retain(|(worktree, _), ids| {
8340 if !ids.remove(&server_id) {
8341 return true;
8342 }
8343
8344 if ids.is_empty() {
8345 orphaned_worktrees.push(*worktree);
8346 false
8347 } else {
8348 true
8349 }
8350 });
8351 let _ = self.language_server_statuses.remove(&server_id);
8352 log::info!("stopping language server {name}");
8353 self.buffer_store.update(cx, |buffer_store, cx| {
8354 for buffer in buffer_store.buffers() {
8355 buffer.update(cx, |buffer, cx| {
8356 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
8357 buffer.set_completion_triggers(server_id, Default::default(), cx);
8358 });
8359 }
8360 });
8361
8362 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
8363 summaries.retain(|path, summaries_by_server_id| {
8364 if summaries_by_server_id.remove(&server_id).is_some() {
8365 if let Some((client, project_id)) = self.downstream_client.clone() {
8366 client
8367 .send(proto::UpdateDiagnosticSummary {
8368 project_id,
8369 worktree_id: worktree_id.to_proto(),
8370 summary: Some(proto::DiagnosticSummary {
8371 path: path.as_ref().to_proto(),
8372 language_server_id: server_id.0 as u64,
8373 error_count: 0,
8374 warning_count: 0,
8375 }),
8376 })
8377 .log_err();
8378 }
8379 !summaries_by_server_id.is_empty()
8380 } else {
8381 true
8382 }
8383 });
8384 }
8385
8386 let local = self.as_local_mut().unwrap();
8387 for diagnostics in local.diagnostics.values_mut() {
8388 diagnostics.retain(|_, diagnostics_by_server_id| {
8389 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
8390 diagnostics_by_server_id.remove(ix);
8391 !diagnostics_by_server_id.is_empty()
8392 } else {
8393 true
8394 }
8395 });
8396 }
8397 local.language_server_watched_paths.remove(&server_id);
8398 let server_state = local.language_servers.remove(&server_id);
8399 cx.notify();
8400 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
8401 cx.spawn(async move |_, cx| {
8402 Self::shutdown_language_server(server_state, name, cx).await;
8403 orphaned_worktrees
8404 })
8405 }
8406
8407 pub fn restart_language_servers_for_buffers(
8408 &mut self,
8409 buffers: Vec<Entity<Buffer>>,
8410 cx: &mut Context<Self>,
8411 ) {
8412 if let Some((client, project_id)) = self.upstream_client() {
8413 let request = client.request(proto::RestartLanguageServers {
8414 project_id,
8415 buffer_ids: buffers
8416 .into_iter()
8417 .map(|b| b.read(cx).remote_id().to_proto())
8418 .collect(),
8419 });
8420 cx.background_spawn(request).detach_and_log_err(cx);
8421 } else {
8422 let Some(local) = self.as_local_mut() else {
8423 return;
8424 };
8425 let language_servers_to_stop = buffers
8426 .iter()
8427 .flat_map(|buffer| {
8428 buffer.update(cx, |buffer, cx| {
8429 local.language_server_ids_for_buffer(buffer, cx)
8430 })
8431 })
8432 .collect::<BTreeSet<_>>();
8433 local.lsp_tree.update(cx, |this, _| {
8434 this.remove_nodes(&language_servers_to_stop);
8435 });
8436 let tasks = language_servers_to_stop
8437 .into_iter()
8438 .map(|server| {
8439 let name = self
8440 .language_server_statuses
8441 .get(&server)
8442 .map(|state| state.name.as_str().into())
8443 .unwrap_or_else(|| LanguageServerName::from("Unknown"));
8444 self.stop_local_language_server(server, name, cx)
8445 })
8446 .collect::<Vec<_>>();
8447
8448 cx.spawn(async move |this, cx| {
8449 cx.background_spawn(futures::future::join_all(tasks)).await;
8450 this.update(cx, |this, cx| {
8451 for buffer in buffers {
8452 this.register_buffer_with_language_servers(&buffer, true, cx);
8453 }
8454 })
8455 .ok()
8456 })
8457 .detach();
8458 }
8459 }
8460
8461 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
8462 let (worktree, relative_path) =
8463 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
8464
8465 let project_path = ProjectPath {
8466 worktree_id: worktree.read(cx).id(),
8467 path: relative_path.into(),
8468 };
8469
8470 Some(
8471 self.buffer_store()
8472 .read(cx)
8473 .get_by_path(&project_path, cx)?
8474 .read(cx),
8475 )
8476 }
8477
8478 pub fn update_diagnostics(
8479 &mut self,
8480 language_server_id: LanguageServerId,
8481 params: lsp::PublishDiagnosticsParams,
8482 disk_based_sources: &[String],
8483 cx: &mut Context<Self>,
8484 ) -> Result<()> {
8485 self.merge_diagnostics(
8486 language_server_id,
8487 params,
8488 disk_based_sources,
8489 |_| false,
8490 cx,
8491 )
8492 }
8493
8494 pub fn merge_diagnostics<F: Fn(&Diagnostic) -> bool + Clone>(
8495 &mut self,
8496 language_server_id: LanguageServerId,
8497 mut params: lsp::PublishDiagnosticsParams,
8498 disk_based_sources: &[String],
8499 filter: F,
8500 cx: &mut Context<Self>,
8501 ) -> Result<()> {
8502 if !self.mode.is_local() {
8503 anyhow::bail!("called update_diagnostics on remote");
8504 }
8505 let abs_path = params
8506 .uri
8507 .to_file_path()
8508 .map_err(|_| anyhow!("URI is not a file"))?;
8509 let mut diagnostics = Vec::default();
8510 let mut primary_diagnostic_group_ids = HashMap::default();
8511 let mut sources_by_group_id = HashMap::default();
8512 let mut supporting_diagnostics = HashMap::default();
8513
8514 // Ensure that primary diagnostics are always the most severe
8515 params.diagnostics.sort_by_key(|item| item.severity);
8516
8517 for diagnostic in ¶ms.diagnostics {
8518 let source = diagnostic.source.as_ref();
8519 let range = range_from_lsp(diagnostic.range);
8520 let is_supporting = diagnostic
8521 .related_information
8522 .as_ref()
8523 .map_or(false, |infos| {
8524 infos.iter().any(|info| {
8525 primary_diagnostic_group_ids.contains_key(&(
8526 source,
8527 diagnostic.code.clone(),
8528 range_from_lsp(info.location.range),
8529 ))
8530 })
8531 });
8532
8533 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
8534 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
8535 });
8536
8537 if is_supporting {
8538 supporting_diagnostics.insert(
8539 (source, diagnostic.code.clone(), range),
8540 (diagnostic.severity, is_unnecessary),
8541 );
8542 } else {
8543 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
8544 let is_disk_based =
8545 source.map_or(false, |source| disk_based_sources.contains(source));
8546
8547 sources_by_group_id.insert(group_id, source);
8548 primary_diagnostic_group_ids
8549 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
8550
8551 diagnostics.push(DiagnosticEntry {
8552 range,
8553 diagnostic: Diagnostic {
8554 source: diagnostic.source.clone(),
8555 code: diagnostic.code.clone(),
8556 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
8557 message: diagnostic.message.trim().to_string(),
8558 group_id,
8559 is_primary: true,
8560 is_disk_based,
8561 is_unnecessary,
8562 data: diagnostic.data.clone(),
8563 },
8564 });
8565 if let Some(infos) = &diagnostic.related_information {
8566 for info in infos {
8567 if info.location.uri == params.uri && !info.message.is_empty() {
8568 let range = range_from_lsp(info.location.range);
8569 diagnostics.push(DiagnosticEntry {
8570 range,
8571 diagnostic: Diagnostic {
8572 source: diagnostic.source.clone(),
8573 code: diagnostic.code.clone(),
8574 severity: DiagnosticSeverity::INFORMATION,
8575 message: info.message.trim().to_string(),
8576 group_id,
8577 is_primary: false,
8578 is_disk_based,
8579 is_unnecessary: false,
8580 data: diagnostic.data.clone(),
8581 },
8582 });
8583 }
8584 }
8585 }
8586 }
8587 }
8588
8589 for entry in &mut diagnostics {
8590 let diagnostic = &mut entry.diagnostic;
8591 if !diagnostic.is_primary {
8592 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
8593 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
8594 source,
8595 diagnostic.code.clone(),
8596 entry.range.clone(),
8597 )) {
8598 if let Some(severity) = severity {
8599 diagnostic.severity = severity;
8600 }
8601 diagnostic.is_unnecessary = is_unnecessary;
8602 }
8603 }
8604 }
8605
8606 self.merge_diagnostic_entries(
8607 language_server_id,
8608 abs_path,
8609 params.version,
8610 diagnostics,
8611 filter,
8612 cx,
8613 )?;
8614 Ok(())
8615 }
8616
8617 fn insert_newly_running_language_server(
8618 &mut self,
8619 adapter: Arc<CachedLspAdapter>,
8620 language_server: Arc<LanguageServer>,
8621 server_id: LanguageServerId,
8622 key: (WorktreeId, LanguageServerName),
8623 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
8624 cx: &mut Context<Self>,
8625 ) {
8626 let Some(local) = self.as_local_mut() else {
8627 return;
8628 };
8629 // If the language server for this key doesn't match the server id, don't store the
8630 // server. Which will cause it to be dropped, killing the process
8631 if local
8632 .language_server_ids
8633 .get(&key)
8634 .map(|ids| !ids.contains(&server_id))
8635 .unwrap_or(false)
8636 {
8637 return;
8638 }
8639
8640 // Update language_servers collection with Running variant of LanguageServerState
8641 // indicating that the server is up and running and ready
8642 let workspace_folders = workspace_folders.lock().clone();
8643 local.language_servers.insert(
8644 server_id,
8645 LanguageServerState::running(
8646 workspace_folders,
8647 adapter.clone(),
8648 language_server.clone(),
8649 None,
8650 ),
8651 );
8652 if let Some(file_ops_caps) = language_server
8653 .capabilities()
8654 .workspace
8655 .as_ref()
8656 .and_then(|ws| ws.file_operations.as_ref())
8657 {
8658 let did_rename_caps = file_ops_caps.did_rename.as_ref();
8659 let will_rename_caps = file_ops_caps.will_rename.as_ref();
8660 if did_rename_caps.or(will_rename_caps).is_some() {
8661 let watcher = RenamePathsWatchedForServer::default()
8662 .with_did_rename_patterns(did_rename_caps)
8663 .with_will_rename_patterns(will_rename_caps);
8664 local
8665 .language_server_paths_watched_for_rename
8666 .insert(server_id, watcher);
8667 }
8668 }
8669
8670 self.language_server_statuses.insert(
8671 server_id,
8672 LanguageServerStatus {
8673 name: language_server.name().to_string(),
8674 pending_work: Default::default(),
8675 has_pending_diagnostic_updates: false,
8676 progress_tokens: Default::default(),
8677 },
8678 );
8679
8680 cx.emit(LspStoreEvent::LanguageServerAdded(
8681 server_id,
8682 language_server.name(),
8683 Some(key.0),
8684 ));
8685 cx.emit(LspStoreEvent::RefreshInlayHints);
8686
8687 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
8688 downstream_client
8689 .send(proto::StartLanguageServer {
8690 project_id: *project_id,
8691 server: Some(proto::LanguageServer {
8692 id: server_id.0 as u64,
8693 name: language_server.name().to_string(),
8694 worktree_id: Some(key.0.to_proto()),
8695 }),
8696 })
8697 .log_err();
8698 }
8699
8700 // Tell the language server about every open buffer in the worktree that matches the language.
8701 self.buffer_store.clone().update(cx, |buffer_store, cx| {
8702 for buffer_handle in buffer_store.buffers() {
8703 let buffer = buffer_handle.read(cx);
8704 let file = match File::from_dyn(buffer.file()) {
8705 Some(file) => file,
8706 None => continue,
8707 };
8708 let language = match buffer.language() {
8709 Some(language) => language,
8710 None => continue,
8711 };
8712
8713 if file.worktree.read(cx).id() != key.0
8714 || !self
8715 .languages
8716 .lsp_adapters(&language.name())
8717 .iter()
8718 .any(|a| a.name == key.1)
8719 {
8720 continue;
8721 }
8722 // didOpen
8723 let file = match file.as_local() {
8724 Some(file) => file,
8725 None => continue,
8726 };
8727
8728 let local = self.as_local_mut().unwrap();
8729
8730 if local.registered_buffers.contains_key(&buffer.remote_id()) {
8731 let versions = local
8732 .buffer_snapshots
8733 .entry(buffer.remote_id())
8734 .or_default()
8735 .entry(server_id)
8736 .and_modify(|_| {
8737 assert!(
8738 false,
8739 "There should not be an existing snapshot for a newly inserted buffer"
8740 )
8741 })
8742 .or_insert_with(|| {
8743 vec![LspBufferSnapshot {
8744 version: 0,
8745 snapshot: buffer.text_snapshot(),
8746 }]
8747 });
8748
8749 let snapshot = versions.last().unwrap();
8750 let version = snapshot.version;
8751 let initial_snapshot = &snapshot.snapshot;
8752 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
8753 language_server.register_buffer(
8754 uri,
8755 adapter.language_id(&language.name()),
8756 version,
8757 initial_snapshot.text(),
8758 );
8759 }
8760 buffer_handle.update(cx, |buffer, cx| {
8761 buffer.set_completion_triggers(
8762 server_id,
8763 language_server
8764 .capabilities()
8765 .completion_provider
8766 .as_ref()
8767 .and_then(|provider| {
8768 provider
8769 .trigger_characters
8770 .as_ref()
8771 .map(|characters| characters.iter().cloned().collect())
8772 })
8773 .unwrap_or_default(),
8774 cx,
8775 )
8776 });
8777 }
8778 });
8779
8780 cx.notify();
8781 }
8782
8783 pub fn language_servers_running_disk_based_diagnostics(
8784 &self,
8785 ) -> impl Iterator<Item = LanguageServerId> + '_ {
8786 self.language_server_statuses
8787 .iter()
8788 .filter_map(|(id, status)| {
8789 if status.has_pending_diagnostic_updates {
8790 Some(*id)
8791 } else {
8792 None
8793 }
8794 })
8795 }
8796
8797 pub(crate) fn cancel_language_server_work_for_buffers(
8798 &mut self,
8799 buffers: impl IntoIterator<Item = Entity<Buffer>>,
8800 cx: &mut Context<Self>,
8801 ) {
8802 if let Some((client, project_id)) = self.upstream_client() {
8803 let request = client.request(proto::CancelLanguageServerWork {
8804 project_id,
8805 work: Some(proto::cancel_language_server_work::Work::Buffers(
8806 proto::cancel_language_server_work::Buffers {
8807 buffer_ids: buffers
8808 .into_iter()
8809 .map(|b| b.read(cx).remote_id().to_proto())
8810 .collect(),
8811 },
8812 )),
8813 });
8814 cx.background_spawn(request).detach_and_log_err(cx);
8815 } else if let Some(local) = self.as_local() {
8816 let servers = buffers
8817 .into_iter()
8818 .flat_map(|buffer| {
8819 buffer.update(cx, |buffer, cx| {
8820 local.language_server_ids_for_buffer(buffer, cx).into_iter()
8821 })
8822 })
8823 .collect::<HashSet<_>>();
8824 for server_id in servers {
8825 self.cancel_language_server_work(server_id, None, cx);
8826 }
8827 }
8828 }
8829
8830 pub(crate) fn cancel_language_server_work(
8831 &mut self,
8832 server_id: LanguageServerId,
8833 token_to_cancel: Option<String>,
8834 cx: &mut Context<Self>,
8835 ) {
8836 if let Some(local) = self.as_local() {
8837 let status = self.language_server_statuses.get(&server_id);
8838 let server = local.language_servers.get(&server_id);
8839 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
8840 {
8841 for (token, progress) in &status.pending_work {
8842 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
8843 if token != token_to_cancel {
8844 continue;
8845 }
8846 }
8847 if progress.is_cancellable {
8848 server
8849 .notify::<lsp::notification::WorkDoneProgressCancel>(
8850 &WorkDoneProgressCancelParams {
8851 token: lsp::NumberOrString::String(token.clone()),
8852 },
8853 )
8854 .ok();
8855 }
8856 }
8857 }
8858 } else if let Some((client, project_id)) = self.upstream_client() {
8859 let request = client.request(proto::CancelLanguageServerWork {
8860 project_id,
8861 work: Some(
8862 proto::cancel_language_server_work::Work::LanguageServerWork(
8863 proto::cancel_language_server_work::LanguageServerWork {
8864 language_server_id: server_id.to_proto(),
8865 token: token_to_cancel,
8866 },
8867 ),
8868 ),
8869 });
8870 cx.background_spawn(request).detach_and_log_err(cx);
8871 }
8872 }
8873
8874 fn register_supplementary_language_server(
8875 &mut self,
8876 id: LanguageServerId,
8877 name: LanguageServerName,
8878 server: Arc<LanguageServer>,
8879 cx: &mut Context<Self>,
8880 ) {
8881 if let Some(local) = self.as_local_mut() {
8882 local
8883 .supplementary_language_servers
8884 .insert(id, (name.clone(), server));
8885 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
8886 }
8887 }
8888
8889 fn unregister_supplementary_language_server(
8890 &mut self,
8891 id: LanguageServerId,
8892 cx: &mut Context<Self>,
8893 ) {
8894 if let Some(local) = self.as_local_mut() {
8895 local.supplementary_language_servers.remove(&id);
8896 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
8897 }
8898 }
8899
8900 pub(crate) fn supplementary_language_servers(
8901 &self,
8902 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
8903 self.as_local().into_iter().flat_map(|local| {
8904 local
8905 .supplementary_language_servers
8906 .iter()
8907 .map(|(id, (name, _))| (*id, name.clone()))
8908 })
8909 }
8910
8911 pub fn language_server_adapter_for_id(
8912 &self,
8913 id: LanguageServerId,
8914 ) -> Option<Arc<CachedLspAdapter>> {
8915 self.as_local()
8916 .and_then(|local| local.language_servers.get(&id))
8917 .and_then(|language_server_state| match language_server_state {
8918 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
8919 _ => None,
8920 })
8921 }
8922
8923 pub(super) fn update_local_worktree_language_servers(
8924 &mut self,
8925 worktree_handle: &Entity<Worktree>,
8926 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
8927 cx: &mut Context<Self>,
8928 ) {
8929 if changes.is_empty() {
8930 return;
8931 }
8932
8933 let Some(local) = self.as_local() else { return };
8934
8935 local.prettier_store.update(cx, |prettier_store, cx| {
8936 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
8937 });
8938
8939 let worktree_id = worktree_handle.read(cx).id();
8940 let mut language_server_ids = local
8941 .language_server_ids
8942 .iter()
8943 .flat_map(|((server_worktree, _), server_ids)| {
8944 server_ids
8945 .iter()
8946 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
8947 })
8948 .collect::<Vec<_>>();
8949 language_server_ids.sort();
8950 language_server_ids.dedup();
8951
8952 let abs_path = worktree_handle.read(cx).abs_path();
8953 for server_id in &language_server_ids {
8954 if let Some(LanguageServerState::Running { server, .. }) =
8955 local.language_servers.get(server_id)
8956 {
8957 if let Some(watched_paths) = local
8958 .language_server_watched_paths
8959 .get(server_id)
8960 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
8961 {
8962 let params = lsp::DidChangeWatchedFilesParams {
8963 changes: changes
8964 .iter()
8965 .filter_map(|(path, _, change)| {
8966 if !watched_paths.is_match(path) {
8967 return None;
8968 }
8969 let typ = match change {
8970 PathChange::Loaded => return None,
8971 PathChange::Added => lsp::FileChangeType::CREATED,
8972 PathChange::Removed => lsp::FileChangeType::DELETED,
8973 PathChange::Updated => lsp::FileChangeType::CHANGED,
8974 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
8975 };
8976 Some(lsp::FileEvent {
8977 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
8978 typ,
8979 })
8980 })
8981 .collect(),
8982 };
8983 if !params.changes.is_empty() {
8984 server
8985 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
8986 .log_err();
8987 }
8988 }
8989 }
8990 }
8991 }
8992
8993 pub fn wait_for_remote_buffer(
8994 &mut self,
8995 id: BufferId,
8996 cx: &mut Context<Self>,
8997 ) -> Task<Result<Entity<Buffer>>> {
8998 self.buffer_store.update(cx, |buffer_store, cx| {
8999 buffer_store.wait_for_remote_buffer(id, cx)
9000 })
9001 }
9002
9003 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9004 proto::Symbol {
9005 language_server_name: symbol.language_server_name.0.to_string(),
9006 source_worktree_id: symbol.source_worktree_id.to_proto(),
9007 language_server_id: symbol.source_language_server_id.to_proto(),
9008 worktree_id: symbol.path.worktree_id.to_proto(),
9009 path: symbol.path.path.as_ref().to_proto(),
9010 name: symbol.name.clone(),
9011 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
9012 start: Some(proto::PointUtf16 {
9013 row: symbol.range.start.0.row,
9014 column: symbol.range.start.0.column,
9015 }),
9016 end: Some(proto::PointUtf16 {
9017 row: symbol.range.end.0.row,
9018 column: symbol.range.end.0.column,
9019 }),
9020 signature: symbol.signature.to_vec(),
9021 }
9022 }
9023
9024 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
9025 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
9026 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
9027 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
9028 let path = ProjectPath {
9029 worktree_id,
9030 path: Arc::<Path>::from_proto(serialized_symbol.path),
9031 };
9032
9033 let start = serialized_symbol
9034 .start
9035 .ok_or_else(|| anyhow!("invalid start"))?;
9036 let end = serialized_symbol
9037 .end
9038 .ok_or_else(|| anyhow!("invalid end"))?;
9039 Ok(CoreSymbol {
9040 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
9041 source_worktree_id,
9042 source_language_server_id: LanguageServerId::from_proto(
9043 serialized_symbol.language_server_id,
9044 ),
9045 path,
9046 name: serialized_symbol.name,
9047 range: Unclipped(PointUtf16::new(start.row, start.column))
9048 ..Unclipped(PointUtf16::new(end.row, end.column)),
9049 kind,
9050 signature: serialized_symbol
9051 .signature
9052 .try_into()
9053 .map_err(|_| anyhow!("invalid signature"))?,
9054 })
9055 }
9056
9057 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
9058 let mut serialized_completion = proto::Completion {
9059 old_start: Some(serialize_anchor(&completion.old_range.start)),
9060 old_end: Some(serialize_anchor(&completion.old_range.end)),
9061 new_text: completion.new_text.clone(),
9062 ..proto::Completion::default()
9063 };
9064 match &completion.source {
9065 CompletionSource::Lsp {
9066 server_id,
9067 lsp_completion,
9068 lsp_defaults,
9069 resolved,
9070 } => {
9071 serialized_completion.source = proto::completion::Source::Lsp as i32;
9072 serialized_completion.server_id = server_id.0 as u64;
9073 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
9074 serialized_completion.lsp_defaults = lsp_defaults
9075 .as_deref()
9076 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
9077 serialized_completion.resolved = *resolved;
9078 }
9079 CompletionSource::BufferWord {
9080 word_range,
9081 resolved,
9082 } => {
9083 serialized_completion.source = proto::completion::Source::BufferWord as i32;
9084 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
9085 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
9086 serialized_completion.resolved = *resolved;
9087 }
9088 CompletionSource::Custom => {
9089 serialized_completion.source = proto::completion::Source::Custom as i32;
9090 serialized_completion.resolved = true;
9091 }
9092 }
9093
9094 serialized_completion
9095 }
9096
9097 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
9098 let old_start = completion
9099 .old_start
9100 .and_then(deserialize_anchor)
9101 .context("invalid old start")?;
9102 let old_end = completion
9103 .old_end
9104 .and_then(deserialize_anchor)
9105 .context("invalid old end")?;
9106 Ok(CoreCompletion {
9107 old_range: old_start..old_end,
9108 new_text: completion.new_text,
9109 source: match proto::completion::Source::from_i32(completion.source) {
9110 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
9111 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
9112 server_id: LanguageServerId::from_proto(completion.server_id),
9113 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
9114 lsp_defaults: completion
9115 .lsp_defaults
9116 .as_deref()
9117 .map(serde_json::from_slice)
9118 .transpose()?,
9119 resolved: completion.resolved,
9120 },
9121 Some(proto::completion::Source::BufferWord) => {
9122 let word_range = completion
9123 .buffer_word_start
9124 .and_then(deserialize_anchor)
9125 .context("invalid buffer word start")?
9126 ..completion
9127 .buffer_word_end
9128 .and_then(deserialize_anchor)
9129 .context("invalid buffer word end")?;
9130 CompletionSource::BufferWord {
9131 word_range,
9132 resolved: completion.resolved,
9133 }
9134 }
9135 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
9136 },
9137 })
9138 }
9139
9140 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
9141 let (kind, lsp_action) = match &action.lsp_action {
9142 LspAction::Action(code_action) => (
9143 proto::code_action::Kind::Action as i32,
9144 serde_json::to_vec(code_action).unwrap(),
9145 ),
9146 LspAction::Command(command) => (
9147 proto::code_action::Kind::Command as i32,
9148 serde_json::to_vec(command).unwrap(),
9149 ),
9150 LspAction::CodeLens(code_lens) => (
9151 proto::code_action::Kind::CodeLens as i32,
9152 serde_json::to_vec(code_lens).unwrap(),
9153 ),
9154 };
9155
9156 proto::CodeAction {
9157 server_id: action.server_id.0 as u64,
9158 start: Some(serialize_anchor(&action.range.start)),
9159 end: Some(serialize_anchor(&action.range.end)),
9160 lsp_action,
9161 kind,
9162 resolved: action.resolved,
9163 }
9164 }
9165
9166 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
9167 let start = action
9168 .start
9169 .and_then(deserialize_anchor)
9170 .context("invalid start")?;
9171 let end = action
9172 .end
9173 .and_then(deserialize_anchor)
9174 .context("invalid end")?;
9175 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
9176 Some(proto::code_action::Kind::Action) => {
9177 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
9178 }
9179 Some(proto::code_action::Kind::Command) => {
9180 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
9181 }
9182 Some(proto::code_action::Kind::CodeLens) => {
9183 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
9184 }
9185 None => anyhow::bail!("Unknown action kind {}", action.kind),
9186 };
9187 Ok(CodeAction {
9188 server_id: LanguageServerId(action.server_id as usize),
9189 range: start..end,
9190 resolved: action.resolved,
9191 lsp_action,
9192 })
9193 }
9194
9195 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
9196 match &formatting_result {
9197 Ok(_) => self.last_formatting_failure = None,
9198 Err(error) => {
9199 let error_string = format!("{error:#}");
9200 log::error!("Formatting failed: {error_string}");
9201 self.last_formatting_failure
9202 .replace(error_string.lines().join(" "));
9203 }
9204 }
9205 }
9206}
9207
9208fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
9209 let CompletionSource::BufferWord {
9210 word_range,
9211 resolved,
9212 } = &mut completion.source
9213 else {
9214 return;
9215 };
9216 if *resolved {
9217 return;
9218 }
9219
9220 if completion.new_text
9221 != snapshot
9222 .text_for_range(word_range.clone())
9223 .collect::<String>()
9224 {
9225 return;
9226 }
9227
9228 let mut offset = 0;
9229 for chunk in snapshot.chunks(word_range.clone(), true) {
9230 let end_offset = offset + chunk.text.len();
9231 if let Some(highlight_id) = chunk.syntax_highlight_id {
9232 completion
9233 .label
9234 .runs
9235 .push((offset..end_offset, highlight_id));
9236 }
9237 offset = end_offset;
9238 }
9239 *resolved = true;
9240}
9241
9242impl EventEmitter<LspStoreEvent> for LspStore {}
9243
9244fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
9245 hover
9246 .contents
9247 .retain(|hover_block| !hover_block.text.trim().is_empty());
9248 if hover.contents.is_empty() {
9249 None
9250 } else {
9251 Some(hover)
9252 }
9253}
9254
9255async fn populate_labels_for_completions(
9256 new_completions: Vec<CoreCompletion>,
9257 language: Option<Arc<Language>>,
9258 lsp_adapter: Option<Arc<CachedLspAdapter>>,
9259 completions: &mut Vec<Completion>,
9260) {
9261 let lsp_completions = new_completions
9262 .iter()
9263 .filter_map(|new_completion| {
9264 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
9265 Some(lsp_completion.into_owned())
9266 } else {
9267 None
9268 }
9269 })
9270 .collect::<Vec<_>>();
9271
9272 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
9273 lsp_adapter
9274 .labels_for_completions(&lsp_completions, language)
9275 .await
9276 .log_err()
9277 .unwrap_or_default()
9278 } else {
9279 Vec::new()
9280 }
9281 .into_iter()
9282 .fuse();
9283
9284 for completion in new_completions {
9285 match completion.source.lsp_completion(true) {
9286 Some(lsp_completion) => {
9287 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
9288 Some(docs.into())
9289 } else {
9290 None
9291 };
9292
9293 let mut label = labels.next().flatten().unwrap_or_else(|| {
9294 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
9295 });
9296 ensure_uniform_list_compatible_label(&mut label);
9297 completions.push(Completion {
9298 label,
9299 documentation,
9300 old_range: completion.old_range,
9301 new_text: completion.new_text,
9302 source: completion.source,
9303 icon_path: None,
9304 confirm: None,
9305 });
9306 }
9307 None => {
9308 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
9309 ensure_uniform_list_compatible_label(&mut label);
9310 completions.push(Completion {
9311 label,
9312 documentation: None,
9313 old_range: completion.old_range,
9314 new_text: completion.new_text,
9315 source: completion.source,
9316 icon_path: None,
9317 confirm: None,
9318 });
9319 }
9320 }
9321 }
9322}
9323
9324#[derive(Debug)]
9325pub enum LanguageServerToQuery {
9326 /// Query language servers in order of users preference, up until one capable of handling the request is found.
9327 FirstCapable,
9328 /// Query a specific language server.
9329 Other(LanguageServerId),
9330}
9331
9332#[derive(Default)]
9333struct RenamePathsWatchedForServer {
9334 did_rename: Vec<RenameActionPredicate>,
9335 will_rename: Vec<RenameActionPredicate>,
9336}
9337
9338impl RenamePathsWatchedForServer {
9339 fn with_did_rename_patterns(
9340 mut self,
9341 did_rename: Option<&FileOperationRegistrationOptions>,
9342 ) -> Self {
9343 if let Some(did_rename) = did_rename {
9344 self.did_rename = did_rename
9345 .filters
9346 .iter()
9347 .filter_map(|filter| filter.try_into().log_err())
9348 .collect();
9349 }
9350 self
9351 }
9352 fn with_will_rename_patterns(
9353 mut self,
9354 will_rename: Option<&FileOperationRegistrationOptions>,
9355 ) -> Self {
9356 if let Some(will_rename) = will_rename {
9357 self.will_rename = will_rename
9358 .filters
9359 .iter()
9360 .filter_map(|filter| filter.try_into().log_err())
9361 .collect();
9362 }
9363 self
9364 }
9365
9366 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
9367 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
9368 }
9369 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
9370 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
9371 }
9372}
9373
9374impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
9375 type Error = globset::Error;
9376 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
9377 Ok(Self {
9378 kind: ops.pattern.matches.clone(),
9379 glob: GlobBuilder::new(&ops.pattern.glob)
9380 .case_insensitive(
9381 ops.pattern
9382 .options
9383 .as_ref()
9384 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
9385 )
9386 .build()?
9387 .compile_matcher(),
9388 })
9389 }
9390}
9391struct RenameActionPredicate {
9392 glob: GlobMatcher,
9393 kind: Option<FileOperationPatternKind>,
9394}
9395
9396impl RenameActionPredicate {
9397 // Returns true if language server should be notified
9398 fn eval(&self, path: &str, is_dir: bool) -> bool {
9399 self.kind.as_ref().map_or(true, |kind| {
9400 let expected_kind = if is_dir {
9401 FileOperationPatternKind::Folder
9402 } else {
9403 FileOperationPatternKind::File
9404 };
9405 kind == &expected_kind
9406 }) && self.glob.is_match(path)
9407 }
9408}
9409
9410#[derive(Default)]
9411struct LanguageServerWatchedPaths {
9412 worktree_paths: HashMap<WorktreeId, GlobSet>,
9413 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
9414}
9415
9416#[derive(Default)]
9417struct LanguageServerWatchedPathsBuilder {
9418 worktree_paths: HashMap<WorktreeId, GlobSet>,
9419 abs_paths: HashMap<Arc<Path>, GlobSet>,
9420}
9421
9422impl LanguageServerWatchedPathsBuilder {
9423 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
9424 self.worktree_paths.insert(worktree_id, glob_set);
9425 }
9426 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
9427 self.abs_paths.insert(path, glob_set);
9428 }
9429 fn build(
9430 self,
9431 fs: Arc<dyn Fs>,
9432 language_server_id: LanguageServerId,
9433 cx: &mut Context<LspStore>,
9434 ) -> LanguageServerWatchedPaths {
9435 let project = cx.weak_entity();
9436
9437 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
9438 let abs_paths = self
9439 .abs_paths
9440 .into_iter()
9441 .map(|(abs_path, globset)| {
9442 let task = cx.spawn({
9443 let abs_path = abs_path.clone();
9444 let fs = fs.clone();
9445
9446 let lsp_store = project.clone();
9447 async move |_, cx| {
9448 maybe!(async move {
9449 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
9450 while let Some(update) = push_updates.0.next().await {
9451 let action = lsp_store
9452 .update(cx, |this, _| {
9453 let Some(local) = this.as_local() else {
9454 return ControlFlow::Break(());
9455 };
9456 let Some(watcher) = local
9457 .language_server_watched_paths
9458 .get(&language_server_id)
9459 else {
9460 return ControlFlow::Break(());
9461 };
9462 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
9463 "Watched abs path is not registered with a watcher",
9464 );
9465 let matching_entries = update
9466 .into_iter()
9467 .filter(|event| globs.is_match(&event.path))
9468 .collect::<Vec<_>>();
9469 this.lsp_notify_abs_paths_changed(
9470 language_server_id,
9471 matching_entries,
9472 );
9473 ControlFlow::Continue(())
9474 })
9475 .ok()?;
9476
9477 if action.is_break() {
9478 break;
9479 }
9480 }
9481 Some(())
9482 })
9483 .await;
9484 }
9485 });
9486 (abs_path, (globset, task))
9487 })
9488 .collect();
9489 LanguageServerWatchedPaths {
9490 worktree_paths: self.worktree_paths,
9491 abs_paths,
9492 }
9493 }
9494}
9495
9496struct LspBufferSnapshot {
9497 version: i32,
9498 snapshot: TextBufferSnapshot,
9499}
9500
9501/// A prompt requested by LSP server.
9502#[derive(Clone, Debug)]
9503pub struct LanguageServerPromptRequest {
9504 pub level: PromptLevel,
9505 pub message: String,
9506 pub actions: Vec<MessageActionItem>,
9507 pub lsp_name: String,
9508 pub(crate) response_channel: Sender<MessageActionItem>,
9509}
9510
9511impl LanguageServerPromptRequest {
9512 pub async fn respond(self, index: usize) -> Option<()> {
9513 if let Some(response) = self.actions.into_iter().nth(index) {
9514 self.response_channel.send(response).await.ok()
9515 } else {
9516 None
9517 }
9518 }
9519}
9520impl PartialEq for LanguageServerPromptRequest {
9521 fn eq(&self, other: &Self) -> bool {
9522 self.message == other.message && self.actions == other.actions
9523 }
9524}
9525
9526#[derive(Clone, Debug, PartialEq)]
9527pub enum LanguageServerLogType {
9528 Log(MessageType),
9529 Trace(Option<String>),
9530}
9531
9532impl LanguageServerLogType {
9533 pub fn to_proto(&self) -> proto::language_server_log::LogType {
9534 match self {
9535 Self::Log(log_type) => {
9536 let message_type = match *log_type {
9537 MessageType::ERROR => 1,
9538 MessageType::WARNING => 2,
9539 MessageType::INFO => 3,
9540 MessageType::LOG => 4,
9541 other => {
9542 log::warn!("Unknown lsp log message type: {:?}", other);
9543 4
9544 }
9545 };
9546 proto::language_server_log::LogType::LogMessageType(message_type)
9547 }
9548 Self::Trace(message) => {
9549 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
9550 message: message.clone(),
9551 })
9552 }
9553 }
9554 }
9555
9556 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
9557 match log_type {
9558 proto::language_server_log::LogType::LogMessageType(message_type) => {
9559 Self::Log(match message_type {
9560 1 => MessageType::ERROR,
9561 2 => MessageType::WARNING,
9562 3 => MessageType::INFO,
9563 4 => MessageType::LOG,
9564 _ => MessageType::LOG,
9565 })
9566 }
9567 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
9568 }
9569 }
9570}
9571
9572pub enum LanguageServerState {
9573 Starting {
9574 startup: Task<Option<Arc<LanguageServer>>>,
9575 /// List of language servers that will be added to the workspace once it's initialization completes.
9576 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
9577 },
9578
9579 Running {
9580 adapter: Arc<CachedLspAdapter>,
9581 server: Arc<LanguageServer>,
9582 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
9583 },
9584}
9585
9586impl LanguageServerState {
9587 fn add_workspace_folder(&self, uri: Url) {
9588 match self {
9589 LanguageServerState::Starting {
9590 pending_workspace_folders,
9591 ..
9592 } => {
9593 pending_workspace_folders.lock().insert(uri);
9594 }
9595 LanguageServerState::Running { server, .. } => {
9596 server.add_workspace_folder(uri);
9597 }
9598 }
9599 }
9600 fn _remove_workspace_folder(&self, uri: Url) {
9601 match self {
9602 LanguageServerState::Starting {
9603 pending_workspace_folders,
9604 ..
9605 } => {
9606 pending_workspace_folders.lock().remove(&uri);
9607 }
9608 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
9609 }
9610 }
9611 fn running(
9612 workspace_folders: BTreeSet<Url>,
9613 adapter: Arc<CachedLspAdapter>,
9614 server: Arc<LanguageServer>,
9615 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
9616 ) -> Self {
9617 server.set_workspace_folders(workspace_folders);
9618 Self::Running {
9619 adapter,
9620 server,
9621 simulate_disk_based_diagnostics_completion,
9622 }
9623 }
9624}
9625
9626impl std::fmt::Debug for LanguageServerState {
9627 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9628 match self {
9629 LanguageServerState::Starting { .. } => {
9630 f.debug_struct("LanguageServerState::Starting").finish()
9631 }
9632 LanguageServerState::Running { .. } => {
9633 f.debug_struct("LanguageServerState::Running").finish()
9634 }
9635 }
9636 }
9637}
9638
9639#[derive(Clone, Debug, Serialize)]
9640pub struct LanguageServerProgress {
9641 pub is_disk_based_diagnostics_progress: bool,
9642 pub is_cancellable: bool,
9643 pub title: Option<String>,
9644 pub message: Option<String>,
9645 pub percentage: Option<usize>,
9646 #[serde(skip_serializing)]
9647 pub last_update_at: Instant,
9648}
9649
9650#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
9651pub struct DiagnosticSummary {
9652 pub error_count: usize,
9653 pub warning_count: usize,
9654}
9655
9656impl DiagnosticSummary {
9657 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
9658 let mut this = Self {
9659 error_count: 0,
9660 warning_count: 0,
9661 };
9662
9663 for entry in diagnostics {
9664 if entry.diagnostic.is_primary {
9665 match entry.diagnostic.severity {
9666 DiagnosticSeverity::ERROR => this.error_count += 1,
9667 DiagnosticSeverity::WARNING => this.warning_count += 1,
9668 _ => {}
9669 }
9670 }
9671 }
9672
9673 this
9674 }
9675
9676 pub fn is_empty(&self) -> bool {
9677 self.error_count == 0 && self.warning_count == 0
9678 }
9679
9680 pub fn to_proto(
9681 &self,
9682 language_server_id: LanguageServerId,
9683 path: &Path,
9684 ) -> proto::DiagnosticSummary {
9685 proto::DiagnosticSummary {
9686 path: path.to_proto(),
9687 language_server_id: language_server_id.0 as u64,
9688 error_count: self.error_count as u32,
9689 warning_count: self.warning_count as u32,
9690 }
9691 }
9692}
9693
9694#[derive(Clone, Debug)]
9695pub enum CompletionDocumentation {
9696 /// There is no documentation for this completion.
9697 Undocumented,
9698 /// A single line of documentation.
9699 SingleLine(SharedString),
9700 /// Multiple lines of plain text documentation.
9701 MultiLinePlainText(SharedString),
9702 /// Markdown documentation.
9703 MultiLineMarkdown(SharedString),
9704}
9705
9706impl From<lsp::Documentation> for CompletionDocumentation {
9707 fn from(docs: lsp::Documentation) -> Self {
9708 match docs {
9709 lsp::Documentation::String(text) => {
9710 if text.lines().count() <= 1 {
9711 CompletionDocumentation::SingleLine(text.into())
9712 } else {
9713 CompletionDocumentation::MultiLinePlainText(text.into())
9714 }
9715 }
9716
9717 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
9718 lsp::MarkupKind::PlainText => {
9719 if value.lines().count() <= 1 {
9720 CompletionDocumentation::SingleLine(value.into())
9721 } else {
9722 CompletionDocumentation::MultiLinePlainText(value.into())
9723 }
9724 }
9725
9726 lsp::MarkupKind::Markdown => {
9727 CompletionDocumentation::MultiLineMarkdown(value.into())
9728 }
9729 },
9730 }
9731 }
9732}
9733
9734fn glob_literal_prefix(glob: &Path) -> PathBuf {
9735 glob.components()
9736 .take_while(|component| match component {
9737 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
9738 _ => true,
9739 })
9740 .collect()
9741}
9742
9743pub struct SshLspAdapter {
9744 name: LanguageServerName,
9745 binary: LanguageServerBinary,
9746 initialization_options: Option<String>,
9747 code_action_kinds: Option<Vec<CodeActionKind>>,
9748}
9749
9750impl SshLspAdapter {
9751 pub fn new(
9752 name: LanguageServerName,
9753 binary: LanguageServerBinary,
9754 initialization_options: Option<String>,
9755 code_action_kinds: Option<String>,
9756 ) -> Self {
9757 Self {
9758 name,
9759 binary,
9760 initialization_options,
9761 code_action_kinds: code_action_kinds
9762 .as_ref()
9763 .and_then(|c| serde_json::from_str(c).ok()),
9764 }
9765 }
9766}
9767
9768#[async_trait(?Send)]
9769impl LspAdapter for SshLspAdapter {
9770 fn name(&self) -> LanguageServerName {
9771 self.name.clone()
9772 }
9773
9774 async fn initialization_options(
9775 self: Arc<Self>,
9776 _: &dyn Fs,
9777 _: &Arc<dyn LspAdapterDelegate>,
9778 ) -> Result<Option<serde_json::Value>> {
9779 let Some(options) = &self.initialization_options else {
9780 return Ok(None);
9781 };
9782 let result = serde_json::from_str(options)?;
9783 Ok(result)
9784 }
9785
9786 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
9787 self.code_action_kinds.clone()
9788 }
9789
9790 async fn check_if_user_installed(
9791 &self,
9792 _: &dyn LspAdapterDelegate,
9793 _: Arc<dyn LanguageToolchainStore>,
9794 _: &AsyncApp,
9795 ) -> Option<LanguageServerBinary> {
9796 Some(self.binary.clone())
9797 }
9798
9799 async fn cached_server_binary(
9800 &self,
9801 _: PathBuf,
9802 _: &dyn LspAdapterDelegate,
9803 ) -> Option<LanguageServerBinary> {
9804 None
9805 }
9806
9807 async fn fetch_latest_server_version(
9808 &self,
9809 _: &dyn LspAdapterDelegate,
9810 ) -> Result<Box<dyn 'static + Send + Any>> {
9811 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
9812 }
9813
9814 async fn fetch_server_binary(
9815 &self,
9816 _: Box<dyn 'static + Send + Any>,
9817 _: PathBuf,
9818 _: &dyn LspAdapterDelegate,
9819 ) -> Result<LanguageServerBinary> {
9820 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
9821 }
9822}
9823
9824pub fn language_server_settings<'a>(
9825 delegate: &'a dyn LspAdapterDelegate,
9826 language: &LanguageServerName,
9827 cx: &'a App,
9828) -> Option<&'a LspSettings> {
9829 language_server_settings_for(
9830 SettingsLocation {
9831 worktree_id: delegate.worktree_id(),
9832 path: delegate.worktree_root_path(),
9833 },
9834 language,
9835 cx,
9836 )
9837}
9838
9839pub(crate) fn language_server_settings_for<'a>(
9840 location: SettingsLocation<'a>,
9841 language: &LanguageServerName,
9842 cx: &'a App,
9843) -> Option<&'a LspSettings> {
9844 ProjectSettings::get(Some(location), cx).lsp.get(language)
9845}
9846
9847pub struct LocalLspAdapterDelegate {
9848 lsp_store: WeakEntity<LspStore>,
9849 worktree: worktree::Snapshot,
9850 fs: Arc<dyn Fs>,
9851 http_client: Arc<dyn HttpClient>,
9852 language_registry: Arc<LanguageRegistry>,
9853 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
9854}
9855
9856impl LocalLspAdapterDelegate {
9857 pub fn new(
9858 language_registry: Arc<LanguageRegistry>,
9859 environment: &Entity<ProjectEnvironment>,
9860 lsp_store: WeakEntity<LspStore>,
9861 worktree: &Entity<Worktree>,
9862 http_client: Arc<dyn HttpClient>,
9863 fs: Arc<dyn Fs>,
9864 cx: &mut App,
9865 ) -> Arc<Self> {
9866 let worktree_abs_path = worktree.read(cx).abs_path();
9867
9868 let load_shell_env_task = environment.update(cx, |env, cx| {
9869 env.get_environment(Some(worktree_abs_path), cx)
9870 });
9871
9872 Arc::new(Self {
9873 lsp_store,
9874 worktree: worktree.read(cx).snapshot(),
9875 fs,
9876 http_client,
9877 language_registry,
9878 load_shell_env_task,
9879 })
9880 }
9881
9882 fn from_local_lsp(
9883 local: &LocalLspStore,
9884 worktree: &Entity<Worktree>,
9885 cx: &mut App,
9886 ) -> Arc<Self> {
9887 Self::new(
9888 local.languages.clone(),
9889 &local.environment,
9890 local.weak.clone(),
9891 worktree,
9892 local.http_client.clone(),
9893 local.fs.clone(),
9894 cx,
9895 )
9896 }
9897}
9898
9899#[async_trait]
9900impl LspAdapterDelegate for LocalLspAdapterDelegate {
9901 fn show_notification(&self, message: &str, cx: &mut App) {
9902 self.lsp_store
9903 .update(cx, |_, cx| {
9904 cx.emit(LspStoreEvent::Notification(message.to_owned()))
9905 })
9906 .ok();
9907 }
9908
9909 fn http_client(&self) -> Arc<dyn HttpClient> {
9910 self.http_client.clone()
9911 }
9912
9913 fn worktree_id(&self) -> WorktreeId {
9914 self.worktree.id()
9915 }
9916
9917 fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool {
9918 self.worktree.entry_for_path(path).map_or(false, |entry| {
9919 is_dir.map_or(true, |is_required_to_be_dir| {
9920 is_required_to_be_dir == entry.is_dir()
9921 })
9922 })
9923 }
9924
9925 fn worktree_root_path(&self) -> &Path {
9926 self.worktree.abs_path().as_ref()
9927 }
9928
9929 async fn shell_env(&self) -> HashMap<String, String> {
9930 let task = self.load_shell_env_task.clone();
9931 task.await.unwrap_or_default()
9932 }
9933
9934 async fn npm_package_installed_version(
9935 &self,
9936 package_name: &str,
9937 ) -> Result<Option<(PathBuf, String)>> {
9938 let local_package_directory = self.worktree_root_path();
9939 let node_modules_directory = local_package_directory.join("node_modules");
9940
9941 if let Some(version) =
9942 read_package_installed_version(node_modules_directory.clone(), package_name).await?
9943 {
9944 return Ok(Some((node_modules_directory, version)));
9945 }
9946 let Some(npm) = self.which("npm".as_ref()).await else {
9947 log::warn!(
9948 "Failed to find npm executable for {:?}",
9949 local_package_directory
9950 );
9951 return Ok(None);
9952 };
9953
9954 let env = self.shell_env().await;
9955 let output = util::command::new_smol_command(&npm)
9956 .args(["root", "-g"])
9957 .envs(env)
9958 .current_dir(local_package_directory)
9959 .output()
9960 .await?;
9961 let global_node_modules =
9962 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
9963
9964 if let Some(version) =
9965 read_package_installed_version(global_node_modules.clone(), package_name).await?
9966 {
9967 return Ok(Some((global_node_modules, version)));
9968 }
9969 return Ok(None);
9970 }
9971
9972 #[cfg(not(target_os = "windows"))]
9973 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
9974 let worktree_abs_path = self.worktree.abs_path();
9975 let shell_path = self.shell_env().await.get("PATH").cloned();
9976 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
9977 }
9978
9979 #[cfg(target_os = "windows")]
9980 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
9981 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
9982 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
9983 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
9984 which::which(command).ok()
9985 }
9986
9987 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
9988 let working_dir = self.worktree_root_path();
9989 let output = util::command::new_smol_command(&command.path)
9990 .args(command.arguments)
9991 .envs(command.env.clone().unwrap_or_default())
9992 .current_dir(working_dir)
9993 .output()
9994 .await?;
9995
9996 if output.status.success() {
9997 return Ok(());
9998 }
9999 Err(anyhow!(
10000 "{}, stdout: {:?}, stderr: {:?}",
10001 output.status,
10002 String::from_utf8_lossy(&output.stdout),
10003 String::from_utf8_lossy(&output.stderr)
10004 ))
10005 }
10006
10007 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
10008 self.language_registry
10009 .update_lsp_status(server_name, status);
10010 }
10011
10012 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
10013 self.language_registry
10014 .all_lsp_adapters()
10015 .into_iter()
10016 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
10017 .collect()
10018 }
10019
10020 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
10021 let dir = self.language_registry.language_server_download_dir(name)?;
10022
10023 if !dir.exists() {
10024 smol::fs::create_dir_all(&dir)
10025 .await
10026 .context("failed to create container directory")
10027 .log_err()?;
10028 }
10029
10030 Some(dir)
10031 }
10032
10033 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10034 let entry = self
10035 .worktree
10036 .entry_for_path(&path)
10037 .with_context(|| format!("no worktree entry for path {path:?}"))?;
10038 let abs_path = self
10039 .worktree
10040 .absolutize(&entry.path)
10041 .with_context(|| format!("cannot absolutize path {path:?}"))?;
10042
10043 self.fs.load(&abs_path).await
10044 }
10045}
10046
10047async fn populate_labels_for_symbols(
10048 symbols: Vec<CoreSymbol>,
10049 language_registry: &Arc<LanguageRegistry>,
10050 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10051 output: &mut Vec<Symbol>,
10052) {
10053 #[allow(clippy::mutable_key_type)]
10054 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10055
10056 let mut unknown_paths = BTreeSet::new();
10057 for symbol in symbols {
10058 let language = language_registry
10059 .language_for_file_path(&symbol.path.path)
10060 .await
10061 .ok()
10062 .or_else(|| {
10063 unknown_paths.insert(symbol.path.path.clone());
10064 None
10065 });
10066 symbols_by_language
10067 .entry(language)
10068 .or_default()
10069 .push(symbol);
10070 }
10071
10072 for unknown_path in unknown_paths {
10073 log::info!(
10074 "no language found for symbol path {}",
10075 unknown_path.display()
10076 );
10077 }
10078
10079 let mut label_params = Vec::new();
10080 for (language, mut symbols) in symbols_by_language {
10081 label_params.clear();
10082 label_params.extend(
10083 symbols
10084 .iter_mut()
10085 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10086 );
10087
10088 let mut labels = Vec::new();
10089 if let Some(language) = language {
10090 let lsp_adapter = lsp_adapter.clone().or_else(|| {
10091 language_registry
10092 .lsp_adapters(&language.name())
10093 .first()
10094 .cloned()
10095 });
10096 if let Some(lsp_adapter) = lsp_adapter {
10097 labels = lsp_adapter
10098 .labels_for_symbols(&label_params, &language)
10099 .await
10100 .log_err()
10101 .unwrap_or_default();
10102 }
10103 }
10104
10105 for ((symbol, (name, _)), label) in symbols
10106 .into_iter()
10107 .zip(label_params.drain(..))
10108 .zip(labels.into_iter().chain(iter::repeat(None)))
10109 {
10110 output.push(Symbol {
10111 language_server_name: symbol.language_server_name,
10112 source_worktree_id: symbol.source_worktree_id,
10113 source_language_server_id: symbol.source_language_server_id,
10114 path: symbol.path,
10115 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10116 name,
10117 kind: symbol.kind,
10118 range: symbol.range,
10119 signature: symbol.signature,
10120 });
10121 }
10122 }
10123}
10124
10125fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
10126 match server.capabilities().text_document_sync.as_ref()? {
10127 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
10128 lsp::TextDocumentSyncKind::NONE => None,
10129 lsp::TextDocumentSyncKind::FULL => Some(true),
10130 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
10131 _ => None,
10132 },
10133 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
10134 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
10135 if *supported {
10136 Some(true)
10137 } else {
10138 None
10139 }
10140 }
10141 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
10142 Some(save_options.include_text.unwrap_or(false))
10143 }
10144 },
10145 }
10146}
10147
10148/// Completion items are displayed in a `UniformList`.
10149/// Usually, those items are single-line strings, but in LSP responses,
10150/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
10151/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
10152/// 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,
10153/// breaking the completions menu presentation.
10154///
10155/// 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.
10156fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
10157 let mut new_text = String::with_capacity(label.text.len());
10158 let mut offset_map = vec![0; label.text.len() + 1];
10159 let mut last_char_was_space = false;
10160 let mut new_idx = 0;
10161 let mut chars = label.text.char_indices().fuse();
10162 let mut newlines_removed = false;
10163
10164 while let Some((idx, c)) = chars.next() {
10165 offset_map[idx] = new_idx;
10166
10167 match c {
10168 '\n' if last_char_was_space => {
10169 newlines_removed = true;
10170 }
10171 '\t' | ' ' if last_char_was_space => {}
10172 '\n' if !last_char_was_space => {
10173 new_text.push(' ');
10174 new_idx += 1;
10175 last_char_was_space = true;
10176 newlines_removed = true;
10177 }
10178 ' ' | '\t' => {
10179 new_text.push(' ');
10180 new_idx += 1;
10181 last_char_was_space = true;
10182 }
10183 _ => {
10184 new_text.push(c);
10185 new_idx += c.len_utf8();
10186 last_char_was_space = false;
10187 }
10188 }
10189 }
10190 offset_map[label.text.len()] = new_idx;
10191
10192 // Only modify the label if newlines were removed.
10193 if !newlines_removed {
10194 return;
10195 }
10196
10197 let last_index = new_idx;
10198 let mut run_ranges_errors = Vec::new();
10199 label.runs.retain_mut(|(range, _)| {
10200 match offset_map.get(range.start) {
10201 Some(&start) => range.start = start,
10202 None => {
10203 run_ranges_errors.push(range.clone());
10204 return false;
10205 }
10206 }
10207
10208 match offset_map.get(range.end) {
10209 Some(&end) => range.end = end,
10210 None => {
10211 run_ranges_errors.push(range.clone());
10212 range.end = last_index;
10213 }
10214 }
10215 true
10216 });
10217 if !run_ranges_errors.is_empty() {
10218 log::error!(
10219 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
10220 label.text
10221 );
10222 }
10223
10224 let mut wrong_filter_range = None;
10225 if label.filter_range == (0..label.text.len()) {
10226 label.filter_range = 0..new_text.len();
10227 } else {
10228 let mut original_filter_range = Some(label.filter_range.clone());
10229 match offset_map.get(label.filter_range.start) {
10230 Some(&start) => label.filter_range.start = start,
10231 None => {
10232 wrong_filter_range = original_filter_range.take();
10233 label.filter_range.start = last_index;
10234 }
10235 }
10236
10237 match offset_map.get(label.filter_range.end) {
10238 Some(&end) => label.filter_range.end = end,
10239 None => {
10240 wrong_filter_range = original_filter_range.take();
10241 label.filter_range.end = last_index;
10242 }
10243 }
10244 }
10245 if let Some(wrong_filter_range) = wrong_filter_range {
10246 log::error!(
10247 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
10248 label.text
10249 );
10250 }
10251
10252 label.text = new_text;
10253}
10254
10255#[cfg(test)]
10256mod tests {
10257 use language::HighlightId;
10258
10259 use super::*;
10260
10261 #[test]
10262 fn test_glob_literal_prefix() {
10263 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
10264 assert_eq!(
10265 glob_literal_prefix(Path::new("node_modules/**/*.js")),
10266 Path::new("node_modules")
10267 );
10268 assert_eq!(
10269 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10270 Path::new("foo")
10271 );
10272 assert_eq!(
10273 glob_literal_prefix(Path::new("foo/bar/baz.js")),
10274 Path::new("foo/bar/baz.js")
10275 );
10276
10277 #[cfg(target_os = "windows")]
10278 {
10279 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
10280 assert_eq!(
10281 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
10282 Path::new("node_modules")
10283 );
10284 assert_eq!(
10285 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10286 Path::new("foo")
10287 );
10288 assert_eq!(
10289 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
10290 Path::new("foo/bar/baz.js")
10291 );
10292 }
10293 }
10294
10295 #[test]
10296 fn test_multi_len_chars_normalization() {
10297 let mut label = CodeLabel {
10298 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
10299 runs: vec![(0..6, HighlightId(1))],
10300 filter_range: 0..6,
10301 };
10302 ensure_uniform_list_compatible_label(&mut label);
10303 assert_eq!(
10304 label,
10305 CodeLabel {
10306 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
10307 runs: vec![(0..6, HighlightId(1))],
10308 filter_range: 0..6,
10309 }
10310 );
10311 }
10312}