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