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