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