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 =
3492 Shared<Task<std::result::Result<HashSet<DocumentColor>, Arc<anyhow::Error>>>>;
3493
3494#[derive(Debug)]
3495struct LspData {
3496 mtime: MTime,
3497 buffer_lsp_data: HashMap<LanguageServerId, HashMap<PathBuf, BufferLspData>>,
3498 colors_update: HashMap<PathBuf, DocumentColorTask>,
3499 last_version_queried: HashMap<PathBuf, Global>,
3500}
3501
3502#[derive(Debug, Default)]
3503struct BufferLspData {
3504 colors: Option<HashSet<DocumentColor>>,
3505}
3506
3507pub enum LspStoreEvent {
3508 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
3509 LanguageServerRemoved(LanguageServerId),
3510 LanguageServerUpdate {
3511 language_server_id: LanguageServerId,
3512 message: proto::update_language_server::Variant,
3513 },
3514 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
3515 LanguageServerPrompt(LanguageServerPromptRequest),
3516 LanguageDetected {
3517 buffer: Entity<Buffer>,
3518 new_language: Option<Arc<Language>>,
3519 },
3520 Notification(String),
3521 RefreshInlayHints,
3522 RefreshCodeLens,
3523 DiagnosticsUpdated {
3524 language_server_id: LanguageServerId,
3525 path: ProjectPath,
3526 },
3527 DiskBasedDiagnosticsStarted {
3528 language_server_id: LanguageServerId,
3529 },
3530 DiskBasedDiagnosticsFinished {
3531 language_server_id: LanguageServerId,
3532 },
3533 SnippetEdit {
3534 buffer_id: BufferId,
3535 edits: Vec<(lsp::Range, Snippet)>,
3536 most_recent_edit: clock::Lamport,
3537 },
3538}
3539
3540#[derive(Clone, Debug, Serialize)]
3541pub struct LanguageServerStatus {
3542 pub name: String,
3543 pub pending_work: BTreeMap<String, LanguageServerProgress>,
3544 pub has_pending_diagnostic_updates: bool,
3545 progress_tokens: HashSet<String>,
3546}
3547
3548#[derive(Clone, Debug)]
3549struct CoreSymbol {
3550 pub language_server_name: LanguageServerName,
3551 pub source_worktree_id: WorktreeId,
3552 pub source_language_server_id: LanguageServerId,
3553 pub path: ProjectPath,
3554 pub name: String,
3555 pub kind: lsp::SymbolKind,
3556 pub range: Range<Unclipped<PointUtf16>>,
3557 pub signature: [u8; 32],
3558}
3559
3560impl LspStore {
3561 pub fn init(client: &AnyProtoClient) {
3562 client.add_entity_request_handler(Self::handle_multi_lsp_query);
3563 client.add_entity_request_handler(Self::handle_restart_language_servers);
3564 client.add_entity_request_handler(Self::handle_stop_language_servers);
3565 client.add_entity_request_handler(Self::handle_cancel_language_server_work);
3566 client.add_entity_message_handler(Self::handle_start_language_server);
3567 client.add_entity_message_handler(Self::handle_update_language_server);
3568 client.add_entity_message_handler(Self::handle_language_server_log);
3569 client.add_entity_message_handler(Self::handle_update_diagnostic_summary);
3570 client.add_entity_request_handler(Self::handle_format_buffers);
3571 client.add_entity_request_handler(Self::handle_apply_code_action_kind);
3572 client.add_entity_request_handler(Self::handle_resolve_completion_documentation);
3573 client.add_entity_request_handler(Self::handle_apply_code_action);
3574 client.add_entity_request_handler(Self::handle_inlay_hints);
3575 client.add_entity_request_handler(Self::handle_get_project_symbols);
3576 client.add_entity_request_handler(Self::handle_resolve_inlay_hint);
3577 client.add_entity_request_handler(Self::handle_get_color_presentation);
3578 client.add_entity_request_handler(Self::handle_open_buffer_for_symbol);
3579 client.add_entity_request_handler(Self::handle_refresh_inlay_hints);
3580 client.add_entity_request_handler(Self::handle_refresh_code_lens);
3581 client.add_entity_request_handler(Self::handle_on_type_formatting);
3582 client.add_entity_request_handler(Self::handle_apply_additional_edits_for_completion);
3583 client.add_entity_request_handler(Self::handle_register_buffer_with_language_servers);
3584 client.add_entity_request_handler(Self::handle_rename_project_entry);
3585 client.add_entity_request_handler(Self::handle_language_server_id_for_name);
3586 client.add_entity_request_handler(Self::handle_pull_workspace_diagnostics);
3587 client.add_entity_request_handler(Self::handle_lsp_command::<GetCodeActions>);
3588 client.add_entity_request_handler(Self::handle_lsp_command::<GetCompletions>);
3589 client.add_entity_request_handler(Self::handle_lsp_command::<GetHover>);
3590 client.add_entity_request_handler(Self::handle_lsp_command::<GetDefinition>);
3591 client.add_entity_request_handler(Self::handle_lsp_command::<GetDeclaration>);
3592 client.add_entity_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
3593 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
3594 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
3595 client.add_entity_request_handler(Self::handle_lsp_command::<GetReferences>);
3596 client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
3597 client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
3598 client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
3599
3600 client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
3601 client.add_entity_request_handler(Self::handle_lsp_ext_run_flycheck);
3602 client.add_entity_request_handler(Self::handle_lsp_ext_clear_flycheck);
3603 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
3604 client.add_entity_request_handler(Self::handle_lsp_command::<lsp_ext_command::OpenDocs>);
3605 client.add_entity_request_handler(
3606 Self::handle_lsp_command::<lsp_ext_command::GoToParentModule>,
3607 );
3608 client.add_entity_request_handler(
3609 Self::handle_lsp_command::<lsp_ext_command::GetLspRunnables>,
3610 );
3611 client.add_entity_request_handler(
3612 Self::handle_lsp_command::<lsp_ext_command::SwitchSourceHeader>,
3613 );
3614 client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentDiagnostics>);
3615 }
3616
3617 pub fn as_remote(&self) -> Option<&RemoteLspStore> {
3618 match &self.mode {
3619 LspStoreMode::Remote(remote_lsp_store) => Some(remote_lsp_store),
3620 _ => None,
3621 }
3622 }
3623
3624 pub fn as_local(&self) -> Option<&LocalLspStore> {
3625 match &self.mode {
3626 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3627 _ => None,
3628 }
3629 }
3630
3631 pub fn as_local_mut(&mut self) -> Option<&mut LocalLspStore> {
3632 match &mut self.mode {
3633 LspStoreMode::Local(local_lsp_store) => Some(local_lsp_store),
3634 _ => None,
3635 }
3636 }
3637
3638 pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
3639 match &self.mode {
3640 LspStoreMode::Remote(RemoteLspStore {
3641 upstream_client: Some(upstream_client),
3642 upstream_project_id,
3643 ..
3644 }) => Some((upstream_client.clone(), *upstream_project_id)),
3645
3646 LspStoreMode::Remote(RemoteLspStore {
3647 upstream_client: None,
3648 ..
3649 }) => None,
3650 LspStoreMode::Local(_) => None,
3651 }
3652 }
3653
3654 pub fn new_local(
3655 buffer_store: Entity<BufferStore>,
3656 worktree_store: Entity<WorktreeStore>,
3657 prettier_store: Entity<PrettierStore>,
3658 toolchain_store: Entity<ToolchainStore>,
3659 environment: Entity<ProjectEnvironment>,
3660 manifest_tree: Entity<ManifestTree>,
3661 languages: Arc<LanguageRegistry>,
3662 http_client: Arc<dyn HttpClient>,
3663 fs: Arc<dyn Fs>,
3664 cx: &mut Context<Self>,
3665 ) -> Self {
3666 let yarn = YarnPathStore::new(fs.clone(), cx);
3667 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3668 .detach();
3669 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3670 .detach();
3671 cx.subscribe(&prettier_store, Self::on_prettier_store_event)
3672 .detach();
3673 cx.subscribe(&toolchain_store, Self::on_toolchain_store_event)
3674 .detach();
3675 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx).as_ref() {
3676 cx.subscribe(
3677 extension_events,
3678 Self::reload_zed_json_schemas_on_extensions_changed,
3679 )
3680 .detach();
3681 } else {
3682 log::debug!("No extension events global found. Skipping JSON schema auto-reload setup");
3683 }
3684 cx.observe_global::<SettingsStore>(Self::on_settings_changed)
3685 .detach();
3686
3687 let _maintain_workspace_config = {
3688 let (sender, receiver) = watch::channel();
3689 (
3690 Self::maintain_workspace_config(fs.clone(), receiver, cx),
3691 sender,
3692 )
3693 };
3694
3695 Self {
3696 mode: LspStoreMode::Local(LocalLspStore {
3697 weak: cx.weak_entity(),
3698 worktree_store: worktree_store.clone(),
3699 toolchain_store: toolchain_store.clone(),
3700 supplementary_language_servers: Default::default(),
3701 languages: languages.clone(),
3702 language_server_ids: Default::default(),
3703 language_servers: Default::default(),
3704 last_workspace_edits_by_language_server: Default::default(),
3705 language_server_watched_paths: Default::default(),
3706 language_server_paths_watched_for_rename: Default::default(),
3707 language_server_watcher_registrations: Default::default(),
3708 buffers_being_formatted: Default::default(),
3709 buffer_snapshots: Default::default(),
3710 prettier_store,
3711 environment,
3712 http_client,
3713 fs,
3714 yarn,
3715 next_diagnostic_group_id: Default::default(),
3716 diagnostics: Default::default(),
3717 _subscription: cx.on_app_quit(|this, cx| {
3718 this.as_local_mut().unwrap().shutdown_language_servers(cx)
3719 }),
3720 lsp_tree: LanguageServerTree::new(manifest_tree, languages.clone(), cx),
3721 registered_buffers: HashMap::default(),
3722 buffer_pull_diagnostics_result_ids: HashMap::default(),
3723 }),
3724 last_formatting_failure: None,
3725 downstream_client: None,
3726 buffer_store,
3727 worktree_store,
3728 toolchain_store: Some(toolchain_store),
3729 languages: languages.clone(),
3730 language_server_statuses: Default::default(),
3731 nonce: StdRng::from_entropy().r#gen(),
3732 diagnostic_summaries: HashMap::default(),
3733 lsp_data: None,
3734 active_entry: None,
3735 _maintain_workspace_config,
3736 _maintain_buffer_languages: Self::maintain_buffer_languages(languages, cx),
3737 }
3738 }
3739
3740 fn send_lsp_proto_request<R: LspCommand>(
3741 &self,
3742 buffer: Entity<Buffer>,
3743 client: AnyProtoClient,
3744 upstream_project_id: u64,
3745 request: R,
3746 cx: &mut Context<LspStore>,
3747 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
3748 let message = request.to_proto(upstream_project_id, buffer.read(cx));
3749 cx.spawn(async move |this, cx| {
3750 let response = client.request(message).await?;
3751 let this = this.upgrade().context("project dropped")?;
3752 request
3753 .response_from_proto(response, this, buffer, cx.clone())
3754 .await
3755 })
3756 }
3757
3758 pub(super) fn new_remote(
3759 buffer_store: Entity<BufferStore>,
3760 worktree_store: Entity<WorktreeStore>,
3761 toolchain_store: Option<Entity<ToolchainStore>>,
3762 languages: Arc<LanguageRegistry>,
3763 upstream_client: AnyProtoClient,
3764 project_id: u64,
3765 fs: Arc<dyn Fs>,
3766 cx: &mut Context<Self>,
3767 ) -> Self {
3768 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
3769 .detach();
3770 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
3771 .detach();
3772 let _maintain_workspace_config = {
3773 let (sender, receiver) = watch::channel();
3774 (Self::maintain_workspace_config(fs, receiver, cx), sender)
3775 };
3776 Self {
3777 mode: LspStoreMode::Remote(RemoteLspStore {
3778 upstream_client: Some(upstream_client),
3779 upstream_project_id: project_id,
3780 }),
3781 downstream_client: None,
3782 last_formatting_failure: None,
3783 buffer_store,
3784 worktree_store,
3785 languages: languages.clone(),
3786 language_server_statuses: Default::default(),
3787 nonce: StdRng::from_entropy().r#gen(),
3788 diagnostic_summaries: HashMap::default(),
3789 lsp_data: None,
3790 active_entry: None,
3791 toolchain_store,
3792 _maintain_workspace_config,
3793 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
3794 }
3795 }
3796
3797 fn on_buffer_store_event(
3798 &mut self,
3799 _: Entity<BufferStore>,
3800 event: &BufferStoreEvent,
3801 cx: &mut Context<Self>,
3802 ) {
3803 match event {
3804 BufferStoreEvent::BufferAdded(buffer) => {
3805 self.on_buffer_added(buffer, cx).log_err();
3806 }
3807 BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
3808 let buffer_id = buffer.read(cx).remote_id();
3809 if let Some(local) = self.as_local_mut() {
3810 if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
3811 local.reset_buffer(buffer, old_file, cx);
3812
3813 if local.registered_buffers.contains_key(&buffer_id) {
3814 local.unregister_old_buffer_from_language_servers(buffer, old_file, cx);
3815 }
3816 }
3817 }
3818
3819 self.detect_language_for_buffer(buffer, cx);
3820 if let Some(local) = self.as_local_mut() {
3821 local.initialize_buffer(buffer, cx);
3822 if local.registered_buffers.contains_key(&buffer_id) {
3823 local.register_buffer_with_language_servers(buffer, cx);
3824 }
3825 }
3826 }
3827 _ => {}
3828 }
3829 }
3830
3831 fn on_worktree_store_event(
3832 &mut self,
3833 _: Entity<WorktreeStore>,
3834 event: &WorktreeStoreEvent,
3835 cx: &mut Context<Self>,
3836 ) {
3837 match event {
3838 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3839 if !worktree.read(cx).is_local() {
3840 return;
3841 }
3842 cx.subscribe(worktree, |this, worktree, event, cx| match event {
3843 worktree::Event::UpdatedEntries(changes) => {
3844 this.update_local_worktree_language_servers(&worktree, changes, cx);
3845 }
3846 worktree::Event::UpdatedGitRepositories(_)
3847 | worktree::Event::DeletedEntry(_) => {}
3848 })
3849 .detach()
3850 }
3851 WorktreeStoreEvent::WorktreeRemoved(_, id) => self.remove_worktree(*id, cx),
3852 WorktreeStoreEvent::WorktreeUpdateSent(worktree) => {
3853 worktree.update(cx, |worktree, _cx| self.send_diagnostic_summaries(worktree));
3854 }
3855 WorktreeStoreEvent::WorktreeReleased(..)
3856 | WorktreeStoreEvent::WorktreeOrderChanged
3857 | WorktreeStoreEvent::WorktreeUpdatedEntries(..)
3858 | WorktreeStoreEvent::WorktreeUpdatedGitRepositories(..)
3859 | WorktreeStoreEvent::WorktreeDeletedEntry(..) => {}
3860 }
3861 }
3862
3863 fn on_prettier_store_event(
3864 &mut self,
3865 _: Entity<PrettierStore>,
3866 event: &PrettierStoreEvent,
3867 cx: &mut Context<Self>,
3868 ) {
3869 match event {
3870 PrettierStoreEvent::LanguageServerRemoved(prettier_server_id) => {
3871 self.unregister_supplementary_language_server(*prettier_server_id, cx);
3872 }
3873 PrettierStoreEvent::LanguageServerAdded {
3874 new_server_id,
3875 name,
3876 prettier_server,
3877 } => {
3878 self.register_supplementary_language_server(
3879 *new_server_id,
3880 name.clone(),
3881 prettier_server.clone(),
3882 cx,
3883 );
3884 }
3885 }
3886 }
3887
3888 fn on_toolchain_store_event(
3889 &mut self,
3890 _: Entity<ToolchainStore>,
3891 event: &ToolchainStoreEvent,
3892 _: &mut Context<Self>,
3893 ) {
3894 match event {
3895 ToolchainStoreEvent::ToolchainActivated { .. } => {
3896 self.request_workspace_config_refresh()
3897 }
3898 }
3899 }
3900
3901 fn request_workspace_config_refresh(&mut self) {
3902 *self._maintain_workspace_config.1.borrow_mut() = ();
3903 }
3904
3905 pub fn prettier_store(&self) -> Option<Entity<PrettierStore>> {
3906 self.as_local().map(|local| local.prettier_store.clone())
3907 }
3908
3909 fn on_buffer_event(
3910 &mut self,
3911 buffer: Entity<Buffer>,
3912 event: &language::BufferEvent,
3913 cx: &mut Context<Self>,
3914 ) {
3915 match event {
3916 language::BufferEvent::Edited => {
3917 self.on_buffer_edited(buffer, cx);
3918 }
3919
3920 language::BufferEvent::Saved => {
3921 self.on_buffer_saved(buffer, cx);
3922 }
3923
3924 _ => {}
3925 }
3926 }
3927
3928 fn on_buffer_added(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3929 buffer
3930 .read(cx)
3931 .set_language_registry(self.languages.clone());
3932
3933 cx.subscribe(buffer, |this, buffer, event, cx| {
3934 this.on_buffer_event(buffer, event, cx);
3935 })
3936 .detach();
3937
3938 self.detect_language_for_buffer(buffer, cx);
3939 if let Some(local) = self.as_local_mut() {
3940 local.initialize_buffer(buffer, cx);
3941 }
3942
3943 Ok(())
3944 }
3945
3946 pub fn reload_zed_json_schemas_on_extensions_changed(
3947 &mut self,
3948 _: Entity<extension::ExtensionEvents>,
3949 evt: &extension::Event,
3950 cx: &mut Context<Self>,
3951 ) {
3952 match evt {
3953 extension::Event::ExtensionInstalled(_)
3954 | extension::Event::ExtensionUninstalled(_)
3955 | extension::Event::ConfigureExtensionRequested(_) => return,
3956 extension::Event::ExtensionsInstalledChanged => {}
3957 }
3958 if self.as_local().is_none() {
3959 return;
3960 }
3961 cx.spawn(async move |this, cx| {
3962 let weak_ref = this.clone();
3963
3964 let servers = this
3965 .update(cx, |this, cx| {
3966 let local = this.as_local()?;
3967
3968 let mut servers = Vec::new();
3969 for ((worktree_id, _), server_ids) in &local.language_server_ids {
3970 for server_id in server_ids {
3971 let Some(states) = local.language_servers.get(server_id) else {
3972 continue;
3973 };
3974 let (json_adapter, json_server) = match states {
3975 LanguageServerState::Running {
3976 adapter, server, ..
3977 } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
3978 (adapter.adapter.clone(), server.clone())
3979 }
3980 _ => continue,
3981 };
3982
3983 let Some(worktree) = this
3984 .worktree_store
3985 .read(cx)
3986 .worktree_for_id(*worktree_id, cx)
3987 else {
3988 continue;
3989 };
3990 let json_delegate: Arc<dyn LspAdapterDelegate> =
3991 LocalLspAdapterDelegate::new(
3992 local.languages.clone(),
3993 &local.environment,
3994 weak_ref.clone(),
3995 &worktree,
3996 local.http_client.clone(),
3997 local.fs.clone(),
3998 cx,
3999 );
4000
4001 servers.push((json_adapter, json_server, json_delegate));
4002 }
4003 }
4004 return Some(servers);
4005 })
4006 .ok()
4007 .flatten();
4008
4009 let Some(servers) = servers else {
4010 return;
4011 };
4012
4013 let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
4014 let local = this.as_local()?;
4015 let toolchain_store = this.toolchain_store(cx);
4016 return Some((local.fs.clone(), toolchain_store));
4017 }) else {
4018 return;
4019 };
4020 for (adapter, server, delegate) in servers {
4021 adapter.clear_zed_json_schema_cache().await;
4022
4023 let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
4024 adapter,
4025 fs.as_ref(),
4026 &delegate,
4027 toolchain_store.clone(),
4028 cx,
4029 )
4030 .await
4031 .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
4032 .ok()
4033 else {
4034 continue;
4035 };
4036 server
4037 .notify::<lsp::notification::DidChangeConfiguration>(
4038 &lsp::DidChangeConfigurationParams {
4039 settings: json_workspace_config,
4040 },
4041 )
4042 .ok();
4043 }
4044 })
4045 .detach();
4046 }
4047
4048 pub(crate) fn register_buffer_with_language_servers(
4049 &mut self,
4050 buffer: &Entity<Buffer>,
4051 ignore_refcounts: bool,
4052 cx: &mut Context<Self>,
4053 ) -> OpenLspBufferHandle {
4054 let buffer_id = buffer.read(cx).remote_id();
4055 let handle = cx.new(|_| buffer.clone());
4056 if let Some(local) = self.as_local_mut() {
4057 let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
4058 if !ignore_refcounts {
4059 *refcount += 1;
4060 }
4061
4062 // We run early exits on non-existing buffers AFTER we mark the buffer as registered in order to handle buffer saving.
4063 // 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
4064 // 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
4065 // servers in practice (we don't support non-file URI schemes in our LSP impl).
4066 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
4067 return handle;
4068 };
4069 if !file.is_local() {
4070 return handle;
4071 }
4072
4073 if ignore_refcounts || *refcount == 1 {
4074 local.register_buffer_with_language_servers(buffer, cx);
4075 }
4076 if !ignore_refcounts {
4077 cx.observe_release(&handle, move |this, buffer, cx| {
4078 let local = this.as_local_mut().unwrap();
4079 let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
4080 debug_panic!("bad refcounting");
4081 return;
4082 };
4083
4084 *refcount -= 1;
4085 if *refcount == 0 {
4086 local.registered_buffers.remove(&buffer_id);
4087 if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
4088 local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
4089 }
4090 }
4091 })
4092 .detach();
4093 }
4094 } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4095 let buffer_id = buffer.read(cx).remote_id().to_proto();
4096 cx.background_spawn(async move {
4097 upstream_client
4098 .request(proto::RegisterBufferWithLanguageServers {
4099 project_id: upstream_project_id,
4100 buffer_id,
4101 })
4102 .await
4103 })
4104 .detach();
4105 } else {
4106 panic!("oops!");
4107 }
4108 handle
4109 }
4110
4111 fn maintain_buffer_languages(
4112 languages: Arc<LanguageRegistry>,
4113 cx: &mut Context<Self>,
4114 ) -> Task<()> {
4115 let mut subscription = languages.subscribe();
4116 let mut prev_reload_count = languages.reload_count();
4117 cx.spawn(async move |this, cx| {
4118 while let Some(()) = subscription.next().await {
4119 if let Some(this) = this.upgrade() {
4120 // If the language registry has been reloaded, then remove and
4121 // re-assign the languages on all open buffers.
4122 let reload_count = languages.reload_count();
4123 if reload_count > prev_reload_count {
4124 prev_reload_count = reload_count;
4125 this.update(cx, |this, cx| {
4126 this.buffer_store.clone().update(cx, |buffer_store, cx| {
4127 for buffer in buffer_store.buffers() {
4128 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
4129 {
4130 buffer
4131 .update(cx, |buffer, cx| buffer.set_language(None, cx));
4132 if let Some(local) = this.as_local_mut() {
4133 local.reset_buffer(&buffer, &f, cx);
4134
4135 if local
4136 .registered_buffers
4137 .contains_key(&buffer.read(cx).remote_id())
4138 {
4139 if let Some(file_url) =
4140 file_path_to_lsp_url(&f.abs_path(cx)).log_err()
4141 {
4142 local.unregister_buffer_from_language_servers(
4143 &buffer, &file_url, cx,
4144 );
4145 }
4146 }
4147 }
4148 }
4149 }
4150 });
4151 })
4152 .ok();
4153 }
4154
4155 this.update(cx, |this, cx| {
4156 let mut plain_text_buffers = Vec::new();
4157 let mut buffers_with_unknown_injections = Vec::new();
4158 for handle in this.buffer_store.read(cx).buffers() {
4159 let buffer = handle.read(cx);
4160 if buffer.language().is_none()
4161 || buffer.language() == Some(&*language::PLAIN_TEXT)
4162 {
4163 plain_text_buffers.push(handle);
4164 } else if buffer.contains_unknown_injections() {
4165 buffers_with_unknown_injections.push(handle);
4166 }
4167 }
4168
4169 // Deprioritize the invisible worktrees so main worktrees' language servers can be started first,
4170 // and reused later in the invisible worktrees.
4171 plain_text_buffers.sort_by_key(|buffer| {
4172 Reverse(
4173 File::from_dyn(buffer.read(cx).file())
4174 .map(|file| file.worktree.read(cx).is_visible()),
4175 )
4176 });
4177
4178 for buffer in plain_text_buffers {
4179 this.detect_language_for_buffer(&buffer, cx);
4180 if let Some(local) = this.as_local_mut() {
4181 local.initialize_buffer(&buffer, cx);
4182 if local
4183 .registered_buffers
4184 .contains_key(&buffer.read(cx).remote_id())
4185 {
4186 local.register_buffer_with_language_servers(&buffer, cx);
4187 }
4188 }
4189 }
4190
4191 for buffer in buffers_with_unknown_injections {
4192 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
4193 }
4194 })
4195 .ok();
4196 }
4197 }
4198 })
4199 }
4200
4201 fn detect_language_for_buffer(
4202 &mut self,
4203 buffer_handle: &Entity<Buffer>,
4204 cx: &mut Context<Self>,
4205 ) -> Option<language::AvailableLanguage> {
4206 // If the buffer has a language, set it and start the language server if we haven't already.
4207 let buffer = buffer_handle.read(cx);
4208 let file = buffer.file()?;
4209
4210 let content = buffer.as_rope();
4211 let available_language = self.languages.language_for_file(file, Some(content), cx);
4212 if let Some(available_language) = &available_language {
4213 if let Some(Ok(Ok(new_language))) = self
4214 .languages
4215 .load_language(available_language)
4216 .now_or_never()
4217 {
4218 self.set_language_for_buffer(buffer_handle, new_language, cx);
4219 }
4220 } else {
4221 cx.emit(LspStoreEvent::LanguageDetected {
4222 buffer: buffer_handle.clone(),
4223 new_language: None,
4224 });
4225 }
4226
4227 available_language
4228 }
4229
4230 pub(crate) fn set_language_for_buffer(
4231 &mut self,
4232 buffer_entity: &Entity<Buffer>,
4233 new_language: Arc<Language>,
4234 cx: &mut Context<Self>,
4235 ) {
4236 let buffer = buffer_entity.read(cx);
4237 let buffer_file = buffer.file().cloned();
4238 let buffer_id = buffer.remote_id();
4239 if let Some(local_store) = self.as_local_mut() {
4240 if local_store.registered_buffers.contains_key(&buffer_id) {
4241 if let Some(abs_path) =
4242 File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
4243 {
4244 if let Some(file_url) = file_path_to_lsp_url(&abs_path).log_err() {
4245 local_store.unregister_buffer_from_language_servers(
4246 buffer_entity,
4247 &file_url,
4248 cx,
4249 );
4250 }
4251 }
4252 }
4253 }
4254 buffer_entity.update(cx, |buffer, cx| {
4255 if buffer.language().map_or(true, |old_language| {
4256 !Arc::ptr_eq(old_language, &new_language)
4257 }) {
4258 buffer.set_language(Some(new_language.clone()), cx);
4259 }
4260 });
4261
4262 let settings =
4263 language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
4264 let buffer_file = File::from_dyn(buffer_file.as_ref());
4265
4266 let worktree_id = if let Some(file) = buffer_file {
4267 let worktree = file.worktree.clone();
4268
4269 if let Some(local) = self.as_local_mut() {
4270 if local.registered_buffers.contains_key(&buffer_id) {
4271 local.register_buffer_with_language_servers(buffer_entity, cx);
4272 }
4273 }
4274 Some(worktree.read(cx).id())
4275 } else {
4276 None
4277 };
4278
4279 if settings.prettier.allowed {
4280 if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
4281 {
4282 let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
4283 if let Some(prettier_store) = prettier_store {
4284 prettier_store.update(cx, |prettier_store, cx| {
4285 prettier_store.install_default_prettier(
4286 worktree_id,
4287 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
4288 cx,
4289 )
4290 })
4291 }
4292 }
4293 }
4294
4295 cx.emit(LspStoreEvent::LanguageDetected {
4296 buffer: buffer_entity.clone(),
4297 new_language: Some(new_language),
4298 })
4299 }
4300
4301 pub fn buffer_store(&self) -> Entity<BufferStore> {
4302 self.buffer_store.clone()
4303 }
4304
4305 pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
4306 self.active_entry = active_entry;
4307 }
4308
4309 pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
4310 if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
4311 if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
4312 for (path, summaries) in summaries {
4313 for (&server_id, summary) in summaries {
4314 client
4315 .send(proto::UpdateDiagnosticSummary {
4316 project_id: downstream_project_id,
4317 worktree_id: worktree.id().to_proto(),
4318 summary: Some(summary.to_proto(server_id, path)),
4319 })
4320 .log_err();
4321 }
4322 }
4323 }
4324 }
4325 }
4326
4327 pub fn request_lsp<R: LspCommand>(
4328 &mut self,
4329 buffer_handle: Entity<Buffer>,
4330 server: LanguageServerToQuery,
4331 request: R,
4332 cx: &mut Context<Self>,
4333 ) -> Task<Result<R::Response>>
4334 where
4335 <R::LspRequest as lsp::request::Request>::Result: Send,
4336 <R::LspRequest as lsp::request::Request>::Params: Send,
4337 {
4338 if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
4339 return self.send_lsp_proto_request(
4340 buffer_handle,
4341 upstream_client,
4342 upstream_project_id,
4343 request,
4344 cx,
4345 );
4346 }
4347
4348 let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
4349 LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
4350 local
4351 .language_servers_for_buffer(buffer, cx)
4352 .find(|(_, server)| {
4353 request.check_capabilities(server.adapter_server_capabilities())
4354 })
4355 .map(|(_, server)| server.clone())
4356 }),
4357 LanguageServerToQuery::Other(id) => self
4358 .language_server_for_local_buffer(buffer, id, cx)
4359 .and_then(|(_, server)| {
4360 request
4361 .check_capabilities(server.adapter_server_capabilities())
4362 .then(|| Arc::clone(server))
4363 }),
4364 }) else {
4365 return Task::ready(Ok(Default::default()));
4366 };
4367
4368 let buffer = buffer_handle.read(cx);
4369 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4370
4371 let Some(file) = file else {
4372 return Task::ready(Ok(Default::default()));
4373 };
4374
4375 let lsp_params = match request.to_lsp_params_or_response(
4376 &file.abs_path(cx),
4377 buffer,
4378 &language_server,
4379 cx,
4380 ) {
4381 Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
4382 Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
4383
4384 Err(err) => {
4385 let message = format!(
4386 "{} via {} failed: {}",
4387 request.display_name(),
4388 language_server.name(),
4389 err
4390 );
4391 log::warn!("{message}");
4392 return Task::ready(Err(anyhow!(message)));
4393 }
4394 };
4395
4396 let status = request.status();
4397 if !request.check_capabilities(language_server.adapter_server_capabilities()) {
4398 return Task::ready(Ok(Default::default()));
4399 }
4400 return cx.spawn(async move |this, cx| {
4401 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
4402
4403 let id = lsp_request.id();
4404 let _cleanup = if status.is_some() {
4405 cx.update(|cx| {
4406 this.update(cx, |this, cx| {
4407 this.on_lsp_work_start(
4408 language_server.server_id(),
4409 id.to_string(),
4410 LanguageServerProgress {
4411 is_disk_based_diagnostics_progress: false,
4412 is_cancellable: false,
4413 title: None,
4414 message: status.clone(),
4415 percentage: None,
4416 last_update_at: cx.background_executor().now(),
4417 },
4418 cx,
4419 );
4420 })
4421 })
4422 .log_err();
4423
4424 Some(defer(|| {
4425 cx.update(|cx| {
4426 this.update(cx, |this, cx| {
4427 this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
4428 })
4429 })
4430 .log_err();
4431 }))
4432 } else {
4433 None
4434 };
4435
4436 let result = lsp_request.await.into_response();
4437
4438 let response = result.map_err(|err| {
4439 let message = format!(
4440 "{} via {} failed: {}",
4441 request.display_name(),
4442 language_server.name(),
4443 err
4444 );
4445 log::warn!("{message}");
4446 anyhow::anyhow!(message)
4447 })?;
4448
4449 let response = request
4450 .response_from_lsp(
4451 response,
4452 this.upgrade().context("no app context")?,
4453 buffer_handle,
4454 language_server.server_id(),
4455 cx.clone(),
4456 )
4457 .await;
4458 response
4459 });
4460 }
4461
4462 fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
4463 let mut language_formatters_to_check = Vec::new();
4464 for buffer in self.buffer_store.read(cx).buffers() {
4465 let buffer = buffer.read(cx);
4466 let buffer_file = File::from_dyn(buffer.file());
4467 let buffer_language = buffer.language();
4468 let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
4469 if buffer_language.is_some() {
4470 language_formatters_to_check.push((
4471 buffer_file.map(|f| f.worktree_id(cx)),
4472 settings.into_owned(),
4473 ));
4474 }
4475 }
4476
4477 self.refresh_server_tree(cx);
4478
4479 if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
4480 prettier_store.update(cx, |prettier_store, cx| {
4481 prettier_store.on_settings_changed(language_formatters_to_check, cx)
4482 })
4483 }
4484
4485 cx.notify();
4486 }
4487
4488 fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
4489 let buffer_store = self.buffer_store.clone();
4490 if let Some(local) = self.as_local_mut() {
4491 let mut adapters = BTreeMap::default();
4492 let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
4493 let get_adapter = {
4494 let languages = local.languages.clone();
4495 let environment = local.environment.clone();
4496 let weak = local.weak.clone();
4497 let worktree_store = local.worktree_store.clone();
4498 let http_client = local.http_client.clone();
4499 let fs = local.fs.clone();
4500 move |worktree_id, cx: &mut App| {
4501 let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
4502 Some(LocalLspAdapterDelegate::new(
4503 languages.clone(),
4504 &environment,
4505 weak.clone(),
4506 &worktree,
4507 http_client.clone(),
4508 fs.clone(),
4509 cx,
4510 ))
4511 }
4512 };
4513
4514 let mut rebase = lsp_tree.rebase();
4515 for buffer_handle in buffer_store.read(cx).buffers().sorted_by_key(|buffer| {
4516 Reverse(
4517 File::from_dyn(buffer.read(cx).file())
4518 .map(|file| file.worktree.read(cx).is_visible()),
4519 )
4520 }) {
4521 let buffer = buffer_handle.read(cx);
4522 if !local.registered_buffers.contains_key(&buffer.remote_id()) {
4523 continue;
4524 }
4525 if let Some((file, language)) = File::from_dyn(buffer.file())
4526 .cloned()
4527 .zip(buffer.language().map(|l| l.name()))
4528 {
4529 let worktree_id = file.worktree_id(cx);
4530 let Some(worktree) = local
4531 .worktree_store
4532 .read(cx)
4533 .worktree_for_id(worktree_id, cx)
4534 else {
4535 continue;
4536 };
4537
4538 let Some((reused, delegate, nodes)) = local
4539 .reuse_existing_language_server(
4540 rebase.server_tree(),
4541 &worktree,
4542 &language,
4543 cx,
4544 )
4545 .map(|(delegate, servers)| (true, delegate, servers))
4546 .or_else(|| {
4547 let lsp_delegate = adapters
4548 .entry(worktree_id)
4549 .or_insert_with(|| get_adapter(worktree_id, cx))
4550 .clone()?;
4551 let delegate = Arc::new(ManifestQueryDelegate::new(
4552 worktree.read(cx).snapshot(),
4553 ));
4554 let path = file
4555 .path()
4556 .parent()
4557 .map(Arc::from)
4558 .unwrap_or_else(|| file.path().clone());
4559 let worktree_path = ProjectPath { worktree_id, path };
4560
4561 let nodes = rebase.get(
4562 worktree_path,
4563 AdapterQuery::Language(&language),
4564 delegate.clone(),
4565 cx,
4566 );
4567
4568 Some((false, lsp_delegate, nodes.collect()))
4569 })
4570 else {
4571 continue;
4572 };
4573
4574 for node in nodes {
4575 if !reused {
4576 node.server_id_or_init(
4577 |LaunchDisposition {
4578 server_name,
4579 attach,
4580 path,
4581 settings,
4582 }| match attach {
4583 language::Attach::InstancePerRoot => {
4584 // todo: handle instance per root proper.
4585 if let Some(server_ids) = local
4586 .language_server_ids
4587 .get(&(worktree_id, server_name.clone()))
4588 {
4589 server_ids.iter().cloned().next().unwrap()
4590 } else {
4591 local.start_language_server(
4592 &worktree,
4593 delegate.clone(),
4594 local
4595 .languages
4596 .lsp_adapters(&language)
4597 .into_iter()
4598 .find(|adapter| {
4599 &adapter.name() == server_name
4600 })
4601 .expect("To find LSP adapter"),
4602 settings,
4603 cx,
4604 )
4605 }
4606 }
4607 language::Attach::Shared => {
4608 let uri = Url::from_file_path(
4609 worktree.read(cx).abs_path().join(&path.path),
4610 );
4611 let key = (worktree_id, server_name.clone());
4612 local.language_server_ids.remove(&key);
4613
4614 let server_id = local.start_language_server(
4615 &worktree,
4616 delegate.clone(),
4617 local
4618 .languages
4619 .lsp_adapters(&language)
4620 .into_iter()
4621 .find(|adapter| &adapter.name() == server_name)
4622 .expect("To find LSP adapter"),
4623 settings,
4624 cx,
4625 );
4626 if let Some(state) =
4627 local.language_servers.get(&server_id)
4628 {
4629 if let Ok(uri) = uri {
4630 state.add_workspace_folder(uri);
4631 };
4632 }
4633 server_id
4634 }
4635 },
4636 );
4637 }
4638 }
4639 }
4640 }
4641 rebase.finish()
4642 });
4643 for (id, name) in to_stop {
4644 self.stop_local_language_server(id, name, cx).detach();
4645 }
4646 }
4647 }
4648
4649 pub fn apply_code_action(
4650 &self,
4651 buffer_handle: Entity<Buffer>,
4652 mut action: CodeAction,
4653 push_to_history: bool,
4654 cx: &mut Context<Self>,
4655 ) -> Task<Result<ProjectTransaction>> {
4656 if let Some((upstream_client, project_id)) = self.upstream_client() {
4657 let request = proto::ApplyCodeAction {
4658 project_id,
4659 buffer_id: buffer_handle.read(cx).remote_id().into(),
4660 action: Some(Self::serialize_code_action(&action)),
4661 };
4662 let buffer_store = self.buffer_store();
4663 cx.spawn(async move |_, cx| {
4664 let response = upstream_client
4665 .request(request)
4666 .await?
4667 .transaction
4668 .context("missing transaction")?;
4669
4670 buffer_store
4671 .update(cx, |buffer_store, cx| {
4672 buffer_store.deserialize_project_transaction(response, push_to_history, cx)
4673 })?
4674 .await
4675 })
4676 } else if self.mode.is_local() {
4677 let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
4678 self.language_server_for_local_buffer(buffer, action.server_id, cx)
4679 .map(|(adapter, server)| (adapter.clone(), server.clone()))
4680 }) else {
4681 return Task::ready(Ok(ProjectTransaction::default()));
4682 };
4683 cx.spawn(async move |this, cx| {
4684 LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
4685 .await
4686 .context("resolving a code action")?;
4687 if let Some(edit) = action.lsp_action.edit() {
4688 if edit.changes.is_some() || edit.document_changes.is_some() {
4689 return LocalLspStore::deserialize_workspace_edit(
4690 this.upgrade().context("no app present")?,
4691 edit.clone(),
4692 push_to_history,
4693 lsp_adapter.clone(),
4694 lang_server.clone(),
4695 cx,
4696 )
4697 .await;
4698 }
4699 }
4700
4701 if let Some(command) = action.lsp_action.command() {
4702 let server_capabilities = lang_server.capabilities();
4703 let available_commands = server_capabilities
4704 .execute_command_provider
4705 .as_ref()
4706 .map(|options| options.commands.as_slice())
4707 .unwrap_or_default();
4708 if available_commands.contains(&command.command) {
4709 this.update(cx, |this, _| {
4710 this.as_local_mut()
4711 .unwrap()
4712 .last_workspace_edits_by_language_server
4713 .remove(&lang_server.server_id());
4714 })?;
4715
4716 let _result = lang_server
4717 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4718 command: command.command.clone(),
4719 arguments: command.arguments.clone().unwrap_or_default(),
4720 ..lsp::ExecuteCommandParams::default()
4721 })
4722 .await.into_response()
4723 .context("execute command")?;
4724
4725 return this.update(cx, |this, _| {
4726 this.as_local_mut()
4727 .unwrap()
4728 .last_workspace_edits_by_language_server
4729 .remove(&lang_server.server_id())
4730 .unwrap_or_default()
4731 });
4732 } else {
4733 log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
4734 }
4735 }
4736
4737 Ok(ProjectTransaction::default())
4738 })
4739 } else {
4740 Task::ready(Err(anyhow!("no upstream client and not local")))
4741 }
4742 }
4743
4744 pub fn apply_code_action_kind(
4745 &mut self,
4746 buffers: HashSet<Entity<Buffer>>,
4747 kind: CodeActionKind,
4748 push_to_history: bool,
4749 cx: &mut Context<Self>,
4750 ) -> Task<anyhow::Result<ProjectTransaction>> {
4751 if let Some(_) = self.as_local() {
4752 cx.spawn(async move |lsp_store, cx| {
4753 let buffers = buffers.into_iter().collect::<Vec<_>>();
4754 let result = LocalLspStore::execute_code_action_kind_locally(
4755 lsp_store.clone(),
4756 buffers,
4757 kind,
4758 push_to_history,
4759 cx,
4760 )
4761 .await;
4762 lsp_store.update(cx, |lsp_store, _| {
4763 lsp_store.update_last_formatting_failure(&result);
4764 })?;
4765 result
4766 })
4767 } else if let Some((client, project_id)) = self.upstream_client() {
4768 let buffer_store = self.buffer_store();
4769 cx.spawn(async move |lsp_store, cx| {
4770 let result = client
4771 .request(proto::ApplyCodeActionKind {
4772 project_id,
4773 kind: kind.as_str().to_owned(),
4774 buffer_ids: buffers
4775 .iter()
4776 .map(|buffer| {
4777 buffer.read_with(cx, |buffer, _| buffer.remote_id().into())
4778 })
4779 .collect::<Result<_>>()?,
4780 })
4781 .await
4782 .and_then(|result| result.transaction.context("missing transaction"));
4783 lsp_store.update(cx, |lsp_store, _| {
4784 lsp_store.update_last_formatting_failure(&result);
4785 })?;
4786
4787 let transaction_response = result?;
4788 buffer_store
4789 .update(cx, |buffer_store, cx| {
4790 buffer_store.deserialize_project_transaction(
4791 transaction_response,
4792 push_to_history,
4793 cx,
4794 )
4795 })?
4796 .await
4797 })
4798 } else {
4799 Task::ready(Ok(ProjectTransaction::default()))
4800 }
4801 }
4802
4803 pub fn resolve_inlay_hint(
4804 &self,
4805 hint: InlayHint,
4806 buffer_handle: Entity<Buffer>,
4807 server_id: LanguageServerId,
4808 cx: &mut Context<Self>,
4809 ) -> Task<anyhow::Result<InlayHint>> {
4810 if let Some((upstream_client, project_id)) = self.upstream_client() {
4811 let request = proto::ResolveInlayHint {
4812 project_id,
4813 buffer_id: buffer_handle.read(cx).remote_id().into(),
4814 language_server_id: server_id.0 as u64,
4815 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
4816 };
4817 cx.spawn(async move |_, _| {
4818 let response = upstream_client
4819 .request(request)
4820 .await
4821 .context("inlay hints proto request")?;
4822 match response.hint {
4823 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
4824 .context("inlay hints proto resolve response conversion"),
4825 None => Ok(hint),
4826 }
4827 })
4828 } else {
4829 let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
4830 self.language_server_for_local_buffer(buffer, server_id, cx)
4831 .map(|(_, server)| server.clone())
4832 }) else {
4833 return Task::ready(Ok(hint));
4834 };
4835 if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
4836 return Task::ready(Ok(hint));
4837 }
4838 let buffer_snapshot = buffer_handle.read(cx).snapshot();
4839 cx.spawn(async move |_, cx| {
4840 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
4841 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
4842 );
4843 let resolved_hint = resolve_task
4844 .await
4845 .into_response()
4846 .context("inlay hint resolve LSP request")?;
4847 let resolved_hint = InlayHints::lsp_to_project_hint(
4848 resolved_hint,
4849 &buffer_handle,
4850 server_id,
4851 ResolveState::Resolved,
4852 false,
4853 cx,
4854 )
4855 .await?;
4856 Ok(resolved_hint)
4857 })
4858 }
4859 }
4860
4861 pub fn resolve_color_presentation(
4862 &mut self,
4863 mut color: DocumentColor,
4864 buffer: Entity<Buffer>,
4865 server_id: LanguageServerId,
4866 cx: &mut Context<Self>,
4867 ) -> Task<Result<DocumentColor>> {
4868 if color.resolved {
4869 return Task::ready(Ok(color));
4870 }
4871
4872 if let Some((upstream_client, project_id)) = self.upstream_client() {
4873 let start = color.lsp_range.start;
4874 let end = color.lsp_range.end;
4875 let request = proto::GetColorPresentation {
4876 project_id,
4877 server_id: server_id.to_proto(),
4878 buffer_id: buffer.read(cx).remote_id().into(),
4879 color: Some(proto::ColorInformation {
4880 red: color.color.red,
4881 green: color.color.green,
4882 blue: color.color.blue,
4883 alpha: color.color.alpha,
4884 lsp_range_start: Some(proto::PointUtf16 {
4885 row: start.line,
4886 column: start.character,
4887 }),
4888 lsp_range_end: Some(proto::PointUtf16 {
4889 row: end.line,
4890 column: end.character,
4891 }),
4892 }),
4893 };
4894 cx.background_spawn(async move {
4895 let response = upstream_client
4896 .request(request)
4897 .await
4898 .context("color presentation proto request")?;
4899 color.resolved = true;
4900 color.color_presentations = response
4901 .presentations
4902 .into_iter()
4903 .map(|presentation| ColorPresentation {
4904 label: presentation.label,
4905 text_edit: presentation.text_edit.and_then(deserialize_lsp_edit),
4906 additional_text_edits: presentation
4907 .additional_text_edits
4908 .into_iter()
4909 .filter_map(deserialize_lsp_edit)
4910 .collect(),
4911 })
4912 .collect();
4913 Ok(color)
4914 })
4915 } else {
4916 let path = match buffer
4917 .update(cx, |buffer, cx| {
4918 Some(File::from_dyn(buffer.file())?.abs_path(cx))
4919 })
4920 .context("buffer with the missing path")
4921 {
4922 Ok(path) => path,
4923 Err(e) => return Task::ready(Err(e)),
4924 };
4925 let Some(lang_server) = buffer.update(cx, |buffer, cx| {
4926 self.language_server_for_local_buffer(buffer, server_id, cx)
4927 .map(|(_, server)| server.clone())
4928 }) else {
4929 return Task::ready(Ok(color));
4930 };
4931 cx.background_spawn(async move {
4932 let resolve_task = lang_server.request::<lsp::request::ColorPresentationRequest>(
4933 lsp::ColorPresentationParams {
4934 text_document: make_text_document_identifier(&path)?,
4935 color: color.color,
4936 range: color.lsp_range,
4937 work_done_progress_params: Default::default(),
4938 partial_result_params: Default::default(),
4939 },
4940 );
4941 color.color_presentations = resolve_task
4942 .await
4943 .into_response()
4944 .context("color presentation resolve LSP request")?
4945 .into_iter()
4946 .map(|presentation| ColorPresentation {
4947 label: presentation.label,
4948 text_edit: presentation.text_edit,
4949 additional_text_edits: presentation
4950 .additional_text_edits
4951 .unwrap_or_default(),
4952 })
4953 .collect();
4954 color.resolved = true;
4955 Ok(color)
4956 })
4957 }
4958 }
4959
4960 pub(crate) fn linked_edit(
4961 &mut self,
4962 buffer: &Entity<Buffer>,
4963 position: Anchor,
4964 cx: &mut Context<Self>,
4965 ) -> Task<Result<Vec<Range<Anchor>>>> {
4966 let snapshot = buffer.read(cx).snapshot();
4967 let scope = snapshot.language_scope_at(position);
4968 let Some(server_id) = self
4969 .as_local()
4970 .and_then(|local| {
4971 buffer.update(cx, |buffer, cx| {
4972 local
4973 .language_servers_for_buffer(buffer, cx)
4974 .filter(|(_, server)| {
4975 server
4976 .capabilities()
4977 .linked_editing_range_provider
4978 .is_some()
4979 })
4980 .filter(|(adapter, _)| {
4981 scope
4982 .as_ref()
4983 .map(|scope| scope.language_allowed(&adapter.name))
4984 .unwrap_or(true)
4985 })
4986 .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
4987 .next()
4988 })
4989 })
4990 .or_else(|| {
4991 self.upstream_client()
4992 .is_some()
4993 .then_some(LanguageServerToQuery::FirstCapable)
4994 })
4995 .filter(|_| {
4996 maybe!({
4997 let language = buffer.read(cx).language_at(position)?;
4998 Some(
4999 language_settings(Some(language.name()), buffer.read(cx).file(), cx)
5000 .linked_edits,
5001 )
5002 }) == Some(true)
5003 })
5004 else {
5005 return Task::ready(Ok(vec![]));
5006 };
5007
5008 self.request_lsp(
5009 buffer.clone(),
5010 server_id,
5011 LinkedEditingRange { position },
5012 cx,
5013 )
5014 }
5015
5016 fn apply_on_type_formatting(
5017 &mut self,
5018 buffer: Entity<Buffer>,
5019 position: Anchor,
5020 trigger: String,
5021 cx: &mut Context<Self>,
5022 ) -> Task<Result<Option<Transaction>>> {
5023 if let Some((client, project_id)) = self.upstream_client() {
5024 let request = proto::OnTypeFormatting {
5025 project_id,
5026 buffer_id: buffer.read(cx).remote_id().into(),
5027 position: Some(serialize_anchor(&position)),
5028 trigger,
5029 version: serialize_version(&buffer.read(cx).version()),
5030 };
5031 cx.spawn(async move |_, _| {
5032 client
5033 .request(request)
5034 .await?
5035 .transaction
5036 .map(language::proto::deserialize_transaction)
5037 .transpose()
5038 })
5039 } else if let Some(local) = self.as_local_mut() {
5040 let buffer_id = buffer.read(cx).remote_id();
5041 local.buffers_being_formatted.insert(buffer_id);
5042 cx.spawn(async move |this, cx| {
5043 let _cleanup = defer({
5044 let this = this.clone();
5045 let mut cx = cx.clone();
5046 move || {
5047 this.update(&mut cx, |this, _| {
5048 if let Some(local) = this.as_local_mut() {
5049 local.buffers_being_formatted.remove(&buffer_id);
5050 }
5051 })
5052 .ok();
5053 }
5054 });
5055
5056 buffer
5057 .update(cx, |buffer, _| {
5058 buffer.wait_for_edits(Some(position.timestamp))
5059 })?
5060 .await?;
5061 this.update(cx, |this, cx| {
5062 let position = position.to_point_utf16(buffer.read(cx));
5063 this.on_type_format(buffer, position, trigger, false, cx)
5064 })?
5065 .await
5066 })
5067 } else {
5068 Task::ready(Err(anyhow!("No upstream client or local language server")))
5069 }
5070 }
5071
5072 pub fn on_type_format<T: ToPointUtf16>(
5073 &mut self,
5074 buffer: Entity<Buffer>,
5075 position: T,
5076 trigger: String,
5077 push_to_history: bool,
5078 cx: &mut Context<Self>,
5079 ) -> Task<Result<Option<Transaction>>> {
5080 let position = position.to_point_utf16(buffer.read(cx));
5081 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5082 }
5083
5084 fn on_type_format_impl(
5085 &mut self,
5086 buffer: Entity<Buffer>,
5087 position: PointUtf16,
5088 trigger: String,
5089 push_to_history: bool,
5090 cx: &mut Context<Self>,
5091 ) -> Task<Result<Option<Transaction>>> {
5092 let options = buffer.update(cx, |buffer, cx| {
5093 lsp_command::lsp_formatting_options(
5094 language_settings(
5095 buffer.language_at(position).map(|l| l.name()),
5096 buffer.file(),
5097 cx,
5098 )
5099 .as_ref(),
5100 )
5101 });
5102
5103 cx.spawn(async move |this, cx| {
5104 if let Some(waiter) =
5105 buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())?
5106 {
5107 waiter.await?;
5108 }
5109 cx.update(|cx| {
5110 this.update(cx, |this, cx| {
5111 this.request_lsp(
5112 buffer.clone(),
5113 LanguageServerToQuery::FirstCapable,
5114 OnTypeFormatting {
5115 position,
5116 trigger,
5117 options,
5118 push_to_history,
5119 },
5120 cx,
5121 )
5122 })
5123 })??
5124 .await
5125 })
5126 }
5127
5128 pub fn code_actions(
5129 &mut self,
5130 buffer_handle: &Entity<Buffer>,
5131 range: Range<Anchor>,
5132 kinds: Option<Vec<CodeActionKind>>,
5133 cx: &mut Context<Self>,
5134 ) -> Task<Result<Vec<CodeAction>>> {
5135 if let Some((upstream_client, project_id)) = self.upstream_client() {
5136 let request_task = upstream_client.request(proto::MultiLspQuery {
5137 buffer_id: buffer_handle.read(cx).remote_id().into(),
5138 version: serialize_version(&buffer_handle.read(cx).version()),
5139 project_id,
5140 strategy: Some(proto::multi_lsp_query::Strategy::All(
5141 proto::AllLanguageServers {},
5142 )),
5143 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
5144 GetCodeActions {
5145 range: range.clone(),
5146 kinds: kinds.clone(),
5147 }
5148 .to_proto(project_id, buffer_handle.read(cx)),
5149 )),
5150 });
5151 let buffer = buffer_handle.clone();
5152 cx.spawn(async move |weak_project, cx| {
5153 let Some(project) = weak_project.upgrade() else {
5154 return Ok(Vec::new());
5155 };
5156 let responses = request_task.await?.responses;
5157 let actions = join_all(
5158 responses
5159 .into_iter()
5160 .filter_map(|lsp_response| match lsp_response.response? {
5161 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
5162 Some(response)
5163 }
5164 unexpected => {
5165 debug_panic!("Unexpected response: {unexpected:?}");
5166 None
5167 }
5168 })
5169 .map(|code_actions_response| {
5170 GetCodeActions {
5171 range: range.clone(),
5172 kinds: kinds.clone(),
5173 }
5174 .response_from_proto(
5175 code_actions_response,
5176 project.clone(),
5177 buffer.clone(),
5178 cx.clone(),
5179 )
5180 }),
5181 )
5182 .await;
5183
5184 Ok(actions
5185 .into_iter()
5186 .collect::<Result<Vec<Vec<_>>>>()?
5187 .into_iter()
5188 .flatten()
5189 .collect())
5190 })
5191 } else {
5192 let all_actions_task = self.request_multiple_lsp_locally(
5193 buffer_handle,
5194 Some(range.start),
5195 GetCodeActions {
5196 range: range.clone(),
5197 kinds: kinds.clone(),
5198 },
5199 cx,
5200 );
5201 cx.spawn(async move |_, _| {
5202 Ok(all_actions_task
5203 .await
5204 .into_iter()
5205 .flat_map(|(_, actions)| actions)
5206 .collect())
5207 })
5208 }
5209 }
5210
5211 pub fn code_lens(
5212 &mut self,
5213 buffer_handle: &Entity<Buffer>,
5214 cx: &mut Context<Self>,
5215 ) -> Task<Result<Vec<CodeAction>>> {
5216 if let Some((upstream_client, project_id)) = self.upstream_client() {
5217 let request_task = upstream_client.request(proto::MultiLspQuery {
5218 buffer_id: buffer_handle.read(cx).remote_id().into(),
5219 version: serialize_version(&buffer_handle.read(cx).version()),
5220 project_id,
5221 strategy: Some(proto::multi_lsp_query::Strategy::All(
5222 proto::AllLanguageServers {},
5223 )),
5224 request: Some(proto::multi_lsp_query::Request::GetCodeLens(
5225 GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
5226 )),
5227 });
5228 let buffer = buffer_handle.clone();
5229 cx.spawn(async move |weak_project, cx| {
5230 let Some(project) = weak_project.upgrade() else {
5231 return Ok(Vec::new());
5232 };
5233 let responses = request_task.await?.responses;
5234 let code_lens = join_all(
5235 responses
5236 .into_iter()
5237 .filter_map(|lsp_response| match lsp_response.response? {
5238 proto::lsp_response::Response::GetCodeLensResponse(response) => {
5239 Some(response)
5240 }
5241 unexpected => {
5242 debug_panic!("Unexpected response: {unexpected:?}");
5243 None
5244 }
5245 })
5246 .map(|code_lens_response| {
5247 GetCodeLens.response_from_proto(
5248 code_lens_response,
5249 project.clone(),
5250 buffer.clone(),
5251 cx.clone(),
5252 )
5253 }),
5254 )
5255 .await;
5256
5257 Ok(code_lens
5258 .into_iter()
5259 .collect::<Result<Vec<Vec<_>>>>()?
5260 .into_iter()
5261 .flatten()
5262 .collect())
5263 })
5264 } else {
5265 let code_lens_task =
5266 self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
5267 cx.spawn(async move |_, _| {
5268 Ok(code_lens_task
5269 .await
5270 .into_iter()
5271 .flat_map(|(_, code_lens)| code_lens)
5272 .collect())
5273 })
5274 }
5275 }
5276
5277 #[inline(never)]
5278 pub fn completions(
5279 &self,
5280 buffer: &Entity<Buffer>,
5281 position: PointUtf16,
5282 context: CompletionContext,
5283 cx: &mut Context<Self>,
5284 ) -> Task<Result<Vec<CompletionResponse>>> {
5285 let language_registry = self.languages.clone();
5286
5287 if let Some((upstream_client, project_id)) = self.upstream_client() {
5288 let task = self.send_lsp_proto_request(
5289 buffer.clone(),
5290 upstream_client,
5291 project_id,
5292 GetCompletions { position, context },
5293 cx,
5294 );
5295 let language = buffer.read(cx).language().cloned();
5296
5297 // In the future, we should provide project guests with the names of LSP adapters,
5298 // so that they can use the correct LSP adapter when computing labels. For now,
5299 // guests just use the first LSP adapter associated with the buffer's language.
5300 let lsp_adapter = language.as_ref().and_then(|language| {
5301 language_registry
5302 .lsp_adapters(&language.name())
5303 .first()
5304 .cloned()
5305 });
5306
5307 cx.foreground_executor().spawn(async move {
5308 let completion_response = task.await?;
5309 let completions = populate_labels_for_completions(
5310 completion_response.completions,
5311 language,
5312 lsp_adapter,
5313 )
5314 .await;
5315 Ok(vec![CompletionResponse {
5316 completions,
5317 is_incomplete: completion_response.is_incomplete,
5318 }])
5319 })
5320 } else if let Some(local) = self.as_local() {
5321 let snapshot = buffer.read(cx).snapshot();
5322 let offset = position.to_offset(&snapshot);
5323 let scope = snapshot.language_scope_at(offset);
5324 let language = snapshot.language().cloned();
5325 let completion_settings = language_settings(
5326 language.as_ref().map(|language| language.name()),
5327 buffer.read(cx).file(),
5328 cx,
5329 )
5330 .completions;
5331 if !completion_settings.lsp {
5332 return Task::ready(Ok(Vec::new()));
5333 }
5334
5335 let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
5336 local
5337 .language_servers_for_buffer(buffer, cx)
5338 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5339 .filter(|(adapter, _)| {
5340 scope
5341 .as_ref()
5342 .map(|scope| scope.language_allowed(&adapter.name))
5343 .unwrap_or(true)
5344 })
5345 .map(|(_, server)| server.server_id())
5346 .collect()
5347 });
5348
5349 let buffer = buffer.clone();
5350 let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
5351 let lsp_timeout = if lsp_timeout > 0 {
5352 Some(Duration::from_millis(lsp_timeout))
5353 } else {
5354 None
5355 };
5356 cx.spawn(async move |this, cx| {
5357 let mut tasks = Vec::with_capacity(server_ids.len());
5358 this.update(cx, |lsp_store, cx| {
5359 for server_id in server_ids {
5360 let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
5361 let lsp_timeout = lsp_timeout
5362 .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
5363 let mut timeout = cx.background_spawn(async move {
5364 match lsp_timeout {
5365 Some(lsp_timeout) => {
5366 lsp_timeout.await;
5367 true
5368 },
5369 None => false,
5370 }
5371 }).fuse();
5372 let mut lsp_request = lsp_store.request_lsp(
5373 buffer.clone(),
5374 LanguageServerToQuery::Other(server_id),
5375 GetCompletions {
5376 position,
5377 context: context.clone(),
5378 },
5379 cx,
5380 ).fuse();
5381 let new_task = cx.background_spawn(async move {
5382 select_biased! {
5383 response = lsp_request => anyhow::Ok(Some(response?)),
5384 timeout_happened = timeout => {
5385 if timeout_happened {
5386 log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
5387 Ok(None)
5388 } else {
5389 let completions = lsp_request.await?;
5390 Ok(Some(completions))
5391 }
5392 },
5393 }
5394 });
5395 tasks.push((lsp_adapter, new_task));
5396 }
5397 })?;
5398
5399 let futures = tasks.into_iter().map(async |(lsp_adapter, task)| {
5400 let completion_response = task.await.ok()??;
5401 let completions = populate_labels_for_completions(
5402 completion_response.completions,
5403 language.clone(),
5404 lsp_adapter,
5405 )
5406 .await;
5407 Some(CompletionResponse {
5408 completions,
5409 is_incomplete: completion_response.is_incomplete,
5410 })
5411 });
5412
5413 let responses: Vec<Option<CompletionResponse>> = join_all(futures).await;
5414
5415 Ok(responses.into_iter().flatten().collect())
5416 })
5417 } else {
5418 Task::ready(Err(anyhow!("No upstream client or local language server")))
5419 }
5420 }
5421
5422 pub fn resolve_completions(
5423 &self,
5424 buffer: Entity<Buffer>,
5425 completion_indices: Vec<usize>,
5426 completions: Rc<RefCell<Box<[Completion]>>>,
5427 cx: &mut Context<Self>,
5428 ) -> Task<Result<bool>> {
5429 let client = self.upstream_client();
5430
5431 let buffer_id = buffer.read(cx).remote_id();
5432 let buffer_snapshot = buffer.read(cx).snapshot();
5433
5434 cx.spawn(async move |this, cx| {
5435 let mut did_resolve = false;
5436 if let Some((client, project_id)) = client {
5437 for completion_index in completion_indices {
5438 let server_id = {
5439 let completion = &completions.borrow()[completion_index];
5440 completion.source.server_id()
5441 };
5442 if let Some(server_id) = server_id {
5443 if Self::resolve_completion_remote(
5444 project_id,
5445 server_id,
5446 buffer_id,
5447 completions.clone(),
5448 completion_index,
5449 client.clone(),
5450 )
5451 .await
5452 .log_err()
5453 .is_some()
5454 {
5455 did_resolve = true;
5456 }
5457 } else {
5458 resolve_word_completion(
5459 &buffer_snapshot,
5460 &mut completions.borrow_mut()[completion_index],
5461 );
5462 }
5463 }
5464 } else {
5465 for completion_index in completion_indices {
5466 let server_id = {
5467 let completion = &completions.borrow()[completion_index];
5468 completion.source.server_id()
5469 };
5470 if let Some(server_id) = server_id {
5471 let server_and_adapter = this
5472 .read_with(cx, |lsp_store, _| {
5473 let server = lsp_store.language_server_for_id(server_id)?;
5474 let adapter =
5475 lsp_store.language_server_adapter_for_id(server.server_id())?;
5476 Some((server, adapter))
5477 })
5478 .ok()
5479 .flatten();
5480 let Some((server, adapter)) = server_and_adapter else {
5481 continue;
5482 };
5483
5484 let resolved = Self::resolve_completion_local(
5485 server,
5486 &buffer_snapshot,
5487 completions.clone(),
5488 completion_index,
5489 )
5490 .await
5491 .log_err()
5492 .is_some();
5493 if resolved {
5494 Self::regenerate_completion_labels(
5495 adapter,
5496 &buffer_snapshot,
5497 completions.clone(),
5498 completion_index,
5499 )
5500 .await
5501 .log_err();
5502 did_resolve = true;
5503 }
5504 } else {
5505 resolve_word_completion(
5506 &buffer_snapshot,
5507 &mut completions.borrow_mut()[completion_index],
5508 );
5509 }
5510 }
5511 }
5512
5513 Ok(did_resolve)
5514 })
5515 }
5516
5517 async fn resolve_completion_local(
5518 server: Arc<lsp::LanguageServer>,
5519 snapshot: &BufferSnapshot,
5520 completions: Rc<RefCell<Box<[Completion]>>>,
5521 completion_index: usize,
5522 ) -> Result<()> {
5523 let server_id = server.server_id();
5524 let can_resolve = server
5525 .capabilities()
5526 .completion_provider
5527 .as_ref()
5528 .and_then(|options| options.resolve_provider)
5529 .unwrap_or(false);
5530 if !can_resolve {
5531 return Ok(());
5532 }
5533
5534 let request = {
5535 let completion = &completions.borrow()[completion_index];
5536 match &completion.source {
5537 CompletionSource::Lsp {
5538 lsp_completion,
5539 resolved,
5540 server_id: completion_server_id,
5541 ..
5542 } => {
5543 if *resolved {
5544 return Ok(());
5545 }
5546 anyhow::ensure!(
5547 server_id == *completion_server_id,
5548 "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5549 );
5550 server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
5551 }
5552 CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
5553 return Ok(());
5554 }
5555 }
5556 };
5557 let resolved_completion = request
5558 .await
5559 .into_response()
5560 .context("resolve completion")?;
5561
5562 if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
5563 // Technically we don't have to parse the whole `text_edit`, since the only
5564 // language server we currently use that does update `text_edit` in `completionItem/resolve`
5565 // is `typescript-language-server` and they only update `text_edit.new_text`.
5566 // But we should not rely on that.
5567 let edit = parse_completion_text_edit(text_edit, snapshot);
5568
5569 if let Some(mut parsed_edit) = edit {
5570 LineEnding::normalize(&mut parsed_edit.new_text);
5571
5572 let mut completions = completions.borrow_mut();
5573 let completion = &mut completions[completion_index];
5574
5575 completion.new_text = parsed_edit.new_text;
5576 completion.replace_range = parsed_edit.replace_range;
5577 if let CompletionSource::Lsp { insert_range, .. } = &mut completion.source {
5578 *insert_range = parsed_edit.insert_range;
5579 }
5580 }
5581 }
5582
5583 let mut completions = completions.borrow_mut();
5584 let completion = &mut completions[completion_index];
5585 if let CompletionSource::Lsp {
5586 lsp_completion,
5587 resolved,
5588 server_id: completion_server_id,
5589 ..
5590 } = &mut completion.source
5591 {
5592 if *resolved {
5593 return Ok(());
5594 }
5595 anyhow::ensure!(
5596 server_id == *completion_server_id,
5597 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5598 );
5599 *lsp_completion = Box::new(resolved_completion);
5600 *resolved = true;
5601 }
5602 Ok(())
5603 }
5604
5605 async fn regenerate_completion_labels(
5606 adapter: Arc<CachedLspAdapter>,
5607 snapshot: &BufferSnapshot,
5608 completions: Rc<RefCell<Box<[Completion]>>>,
5609 completion_index: usize,
5610 ) -> Result<()> {
5611 let completion_item = completions.borrow()[completion_index]
5612 .source
5613 .lsp_completion(true)
5614 .map(Cow::into_owned);
5615 if let Some(lsp_documentation) = completion_item
5616 .as_ref()
5617 .and_then(|completion_item| completion_item.documentation.clone())
5618 {
5619 let mut completions = completions.borrow_mut();
5620 let completion = &mut completions[completion_index];
5621 completion.documentation = Some(lsp_documentation.into());
5622 } else {
5623 let mut completions = completions.borrow_mut();
5624 let completion = &mut completions[completion_index];
5625 completion.documentation = Some(CompletionDocumentation::Undocumented);
5626 }
5627
5628 let mut new_label = match completion_item {
5629 Some(completion_item) => {
5630 // 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
5631 // So we have to update the label here anyway...
5632 let language = snapshot.language();
5633 match language {
5634 Some(language) => {
5635 adapter
5636 .labels_for_completions(&[completion_item.clone()], language)
5637 .await?
5638 }
5639 None => Vec::new(),
5640 }
5641 .pop()
5642 .flatten()
5643 .unwrap_or_else(|| {
5644 CodeLabel::fallback_for_completion(
5645 &completion_item,
5646 language.map(|language| language.as_ref()),
5647 )
5648 })
5649 }
5650 None => CodeLabel::plain(
5651 completions.borrow()[completion_index].new_text.clone(),
5652 None,
5653 ),
5654 };
5655 ensure_uniform_list_compatible_label(&mut new_label);
5656
5657 let mut completions = completions.borrow_mut();
5658 let completion = &mut completions[completion_index];
5659 if completion.label.filter_text() == new_label.filter_text() {
5660 completion.label = new_label;
5661 } else {
5662 log::error!(
5663 "Resolved completion changed display label from {} to {}. \
5664 Refusing to apply this because it changes the fuzzy match text from {} to {}",
5665 completion.label.text(),
5666 new_label.text(),
5667 completion.label.filter_text(),
5668 new_label.filter_text()
5669 );
5670 }
5671
5672 Ok(())
5673 }
5674
5675 async fn resolve_completion_remote(
5676 project_id: u64,
5677 server_id: LanguageServerId,
5678 buffer_id: BufferId,
5679 completions: Rc<RefCell<Box<[Completion]>>>,
5680 completion_index: usize,
5681 client: AnyProtoClient,
5682 ) -> Result<()> {
5683 let lsp_completion = {
5684 let completion = &completions.borrow()[completion_index];
5685 match &completion.source {
5686 CompletionSource::Lsp {
5687 lsp_completion,
5688 resolved,
5689 server_id: completion_server_id,
5690 ..
5691 } => {
5692 anyhow::ensure!(
5693 server_id == *completion_server_id,
5694 "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
5695 );
5696 if *resolved {
5697 return Ok(());
5698 }
5699 serde_json::to_string(lsp_completion).unwrap().into_bytes()
5700 }
5701 CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
5702 return Ok(());
5703 }
5704 }
5705 };
5706 let request = proto::ResolveCompletionDocumentation {
5707 project_id,
5708 language_server_id: server_id.0 as u64,
5709 lsp_completion,
5710 buffer_id: buffer_id.into(),
5711 };
5712
5713 let response = client
5714 .request(request)
5715 .await
5716 .context("completion documentation resolve proto request")?;
5717 let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
5718
5719 let documentation = if response.documentation.is_empty() {
5720 CompletionDocumentation::Undocumented
5721 } else if response.documentation_is_markdown {
5722 CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
5723 } else if response.documentation.lines().count() <= 1 {
5724 CompletionDocumentation::SingleLine(response.documentation.into())
5725 } else {
5726 CompletionDocumentation::MultiLinePlainText(response.documentation.into())
5727 };
5728
5729 let mut completions = completions.borrow_mut();
5730 let completion = &mut completions[completion_index];
5731 completion.documentation = Some(documentation);
5732 if let CompletionSource::Lsp {
5733 insert_range,
5734 lsp_completion,
5735 resolved,
5736 server_id: completion_server_id,
5737 lsp_defaults: _,
5738 } = &mut completion.source
5739 {
5740 let completion_insert_range = response
5741 .old_insert_start
5742 .and_then(deserialize_anchor)
5743 .zip(response.old_insert_end.and_then(deserialize_anchor));
5744 *insert_range = completion_insert_range.map(|(start, end)| start..end);
5745
5746 if *resolved {
5747 return Ok(());
5748 }
5749 anyhow::ensure!(
5750 server_id == *completion_server_id,
5751 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
5752 );
5753 *lsp_completion = Box::new(resolved_lsp_completion);
5754 *resolved = true;
5755 }
5756
5757 let replace_range = response
5758 .old_replace_start
5759 .and_then(deserialize_anchor)
5760 .zip(response.old_replace_end.and_then(deserialize_anchor));
5761 if let Some((old_replace_start, old_replace_end)) = replace_range {
5762 if !response.new_text.is_empty() {
5763 completion.new_text = response.new_text;
5764 completion.replace_range = old_replace_start..old_replace_end;
5765 }
5766 }
5767
5768 Ok(())
5769 }
5770
5771 pub fn apply_additional_edits_for_completion(
5772 &self,
5773 buffer_handle: Entity<Buffer>,
5774 completions: Rc<RefCell<Box<[Completion]>>>,
5775 completion_index: usize,
5776 push_to_history: bool,
5777 cx: &mut Context<Self>,
5778 ) -> Task<Result<Option<Transaction>>> {
5779 if let Some((client, project_id)) = self.upstream_client() {
5780 let buffer = buffer_handle.read(cx);
5781 let buffer_id = buffer.remote_id();
5782 cx.spawn(async move |_, cx| {
5783 let request = {
5784 let completion = completions.borrow()[completion_index].clone();
5785 proto::ApplyCompletionAdditionalEdits {
5786 project_id,
5787 buffer_id: buffer_id.into(),
5788 completion: Some(Self::serialize_completion(&CoreCompletion {
5789 replace_range: completion.replace_range,
5790 new_text: completion.new_text,
5791 source: completion.source,
5792 })),
5793 }
5794 };
5795
5796 if let Some(transaction) = client.request(request).await?.transaction {
5797 let transaction = language::proto::deserialize_transaction(transaction)?;
5798 buffer_handle
5799 .update(cx, |buffer, _| {
5800 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5801 })?
5802 .await?;
5803 if push_to_history {
5804 buffer_handle.update(cx, |buffer, _| {
5805 buffer.push_transaction(transaction.clone(), Instant::now());
5806 buffer.finalize_last_transaction();
5807 })?;
5808 }
5809 Ok(Some(transaction))
5810 } else {
5811 Ok(None)
5812 }
5813 })
5814 } else {
5815 let Some(server) = buffer_handle.update(cx, |buffer, cx| {
5816 let completion = &completions.borrow()[completion_index];
5817 let server_id = completion.source.server_id()?;
5818 Some(
5819 self.language_server_for_local_buffer(buffer, server_id, cx)?
5820 .1
5821 .clone(),
5822 )
5823 }) else {
5824 return Task::ready(Ok(None));
5825 };
5826 let snapshot = buffer_handle.read(&cx).snapshot();
5827
5828 cx.spawn(async move |this, cx| {
5829 Self::resolve_completion_local(
5830 server.clone(),
5831 &snapshot,
5832 completions.clone(),
5833 completion_index,
5834 )
5835 .await
5836 .context("resolving completion")?;
5837 let completion = completions.borrow()[completion_index].clone();
5838 let additional_text_edits = completion
5839 .source
5840 .lsp_completion(true)
5841 .as_ref()
5842 .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
5843 if let Some(edits) = additional_text_edits {
5844 let edits = this
5845 .update(cx, |this, cx| {
5846 this.as_local_mut().unwrap().edits_from_lsp(
5847 &buffer_handle,
5848 edits,
5849 server.server_id(),
5850 None,
5851 cx,
5852 )
5853 })?
5854 .await?;
5855
5856 buffer_handle.update(cx, |buffer, cx| {
5857 buffer.finalize_last_transaction();
5858 buffer.start_transaction();
5859
5860 for (range, text) in edits {
5861 let primary = &completion.replace_range;
5862 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5863 && primary.end.cmp(&range.start, buffer).is_ge();
5864 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5865 && range.end.cmp(&primary.end, buffer).is_ge();
5866
5867 //Skip additional edits which overlap with the primary completion edit
5868 //https://github.com/zed-industries/zed/pull/1871
5869 if !start_within && !end_within {
5870 buffer.edit([(range, text)], None, cx);
5871 }
5872 }
5873
5874 let transaction = if buffer.end_transaction(cx).is_some() {
5875 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5876 if !push_to_history {
5877 buffer.forget_transaction(transaction.id);
5878 }
5879 Some(transaction)
5880 } else {
5881 None
5882 };
5883 Ok(transaction)
5884 })?
5885 } else {
5886 Ok(None)
5887 }
5888 })
5889 }
5890 }
5891
5892 pub fn pull_diagnostics(
5893 &mut self,
5894 buffer_handle: Entity<Buffer>,
5895 cx: &mut Context<Self>,
5896 ) -> Task<Result<Vec<LspPullDiagnostics>>> {
5897 let buffer = buffer_handle.read(cx);
5898 let buffer_id = buffer.remote_id();
5899
5900 if let Some((client, upstream_project_id)) = self.upstream_client() {
5901 let request_task = client.request(proto::MultiLspQuery {
5902 buffer_id: buffer_id.to_proto(),
5903 version: serialize_version(&buffer_handle.read(cx).version()),
5904 project_id: upstream_project_id,
5905 strategy: Some(proto::multi_lsp_query::Strategy::All(
5906 proto::AllLanguageServers {},
5907 )),
5908 request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
5909 proto::GetDocumentDiagnostics {
5910 project_id: upstream_project_id,
5911 buffer_id: buffer_id.to_proto(),
5912 version: serialize_version(&buffer_handle.read(cx).version()),
5913 },
5914 )),
5915 });
5916 cx.background_spawn(async move {
5917 Ok(request_task
5918 .await?
5919 .responses
5920 .into_iter()
5921 .filter_map(|lsp_response| match lsp_response.response? {
5922 proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
5923 Some(response)
5924 }
5925 unexpected => {
5926 debug_panic!("Unexpected response: {unexpected:?}");
5927 None
5928 }
5929 })
5930 .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
5931 .collect())
5932 })
5933 } else {
5934 let server_ids = buffer_handle.update(cx, |buffer, cx| {
5935 self.language_servers_for_local_buffer(buffer, cx)
5936 .map(|(_, server)| server.server_id())
5937 .collect::<Vec<_>>()
5938 });
5939 let pull_diagnostics = server_ids
5940 .into_iter()
5941 .map(|server_id| {
5942 let result_id = self.result_id(server_id, buffer_id, cx);
5943 self.request_lsp(
5944 buffer_handle.clone(),
5945 LanguageServerToQuery::Other(server_id),
5946 GetDocumentDiagnostics {
5947 previous_result_id: result_id,
5948 },
5949 cx,
5950 )
5951 })
5952 .collect::<Vec<_>>();
5953
5954 cx.background_spawn(async move {
5955 let mut responses = Vec::new();
5956 for diagnostics in join_all(pull_diagnostics).await {
5957 responses.extend(diagnostics?);
5958 }
5959 Ok(responses)
5960 })
5961 }
5962 }
5963
5964 pub fn inlay_hints(
5965 &mut self,
5966 buffer_handle: Entity<Buffer>,
5967 range: Range<Anchor>,
5968 cx: &mut Context<Self>,
5969 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5970 let buffer = buffer_handle.read(cx);
5971 let range_start = range.start;
5972 let range_end = range.end;
5973 let buffer_id = buffer.remote_id().into();
5974 let lsp_request = InlayHints { range };
5975
5976 if let Some((client, project_id)) = self.upstream_client() {
5977 let request = proto::InlayHints {
5978 project_id,
5979 buffer_id,
5980 start: Some(serialize_anchor(&range_start)),
5981 end: Some(serialize_anchor(&range_end)),
5982 version: serialize_version(&buffer_handle.read(cx).version()),
5983 };
5984 cx.spawn(async move |project, cx| {
5985 let response = client
5986 .request(request)
5987 .await
5988 .context("inlay hints proto request")?;
5989 LspCommand::response_from_proto(
5990 lsp_request,
5991 response,
5992 project.upgrade().context("No project")?,
5993 buffer_handle.clone(),
5994 cx.clone(),
5995 )
5996 .await
5997 .context("inlay hints proto response conversion")
5998 })
5999 } else {
6000 let lsp_request_task = self.request_lsp(
6001 buffer_handle.clone(),
6002 LanguageServerToQuery::FirstCapable,
6003 lsp_request,
6004 cx,
6005 );
6006 cx.spawn(async move |_, cx| {
6007 buffer_handle
6008 .update(cx, |buffer, _| {
6009 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6010 })?
6011 .await
6012 .context("waiting for inlay hint request range edits")?;
6013 lsp_request_task.await.context("inlay hints LSP request")
6014 })
6015 }
6016 }
6017
6018 pub fn pull_diagnostics_for_buffer(
6019 &mut self,
6020 buffer: Entity<Buffer>,
6021 cx: &mut Context<Self>,
6022 ) -> Task<anyhow::Result<()>> {
6023 let buffer_id = buffer.read(cx).remote_id();
6024 let diagnostics = self.pull_diagnostics(buffer, cx);
6025 cx.spawn(async move |lsp_store, cx| {
6026 let diagnostics = diagnostics.await.context("pulling diagnostics")?;
6027 lsp_store.update(cx, |lsp_store, cx| {
6028 if lsp_store.as_local().is_none() {
6029 return;
6030 }
6031
6032 for diagnostics_set in diagnostics {
6033 let LspPullDiagnostics::Response {
6034 server_id,
6035 uri,
6036 diagnostics,
6037 } = diagnostics_set
6038 else {
6039 continue;
6040 };
6041
6042 let adapter = lsp_store.language_server_adapter_for_id(server_id);
6043 let disk_based_sources = adapter
6044 .as_ref()
6045 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
6046 .unwrap_or(&[]);
6047 match diagnostics {
6048 PulledDiagnostics::Unchanged { result_id } => {
6049 lsp_store
6050 .merge_diagnostics(
6051 server_id,
6052 lsp::PublishDiagnosticsParams {
6053 uri: uri.clone(),
6054 diagnostics: Vec::new(),
6055 version: None,
6056 },
6057 Some(result_id),
6058 DiagnosticSourceKind::Pulled,
6059 disk_based_sources,
6060 |_, _, _| true,
6061 cx,
6062 )
6063 .log_err();
6064 }
6065 PulledDiagnostics::Changed {
6066 diagnostics,
6067 result_id,
6068 } => {
6069 lsp_store
6070 .merge_diagnostics(
6071 server_id,
6072 lsp::PublishDiagnosticsParams {
6073 uri: uri.clone(),
6074 diagnostics,
6075 version: None,
6076 },
6077 result_id,
6078 DiagnosticSourceKind::Pulled,
6079 disk_based_sources,
6080 |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
6081 DiagnosticSourceKind::Pulled => {
6082 buffer.remote_id() != buffer_id
6083 }
6084 DiagnosticSourceKind::Other
6085 | DiagnosticSourceKind::Pushed => true,
6086 },
6087 cx,
6088 )
6089 .log_err();
6090 }
6091 }
6092 }
6093 })
6094 })
6095 }
6096
6097 pub fn document_colors(
6098 &mut self,
6099 for_server_id: Option<LanguageServerId>,
6100 buffer: Entity<Buffer>,
6101 cx: &mut Context<Self>,
6102 ) -> Option<DocumentColorTask> {
6103 let buffer_mtime = buffer.read(cx).saved_mtime()?;
6104 let buffer_version = buffer.read(cx).version();
6105 let abs_path = File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
6106
6107 let mut received_colors_data = false;
6108 let buffer_lsp_data = self
6109 .lsp_data
6110 .as_ref()
6111 .into_iter()
6112 .filter(|lsp_data| {
6113 if buffer_mtime == lsp_data.mtime {
6114 lsp_data
6115 .last_version_queried
6116 .get(&abs_path)
6117 .is_none_or(|version_queried| {
6118 !buffer_version.changed_since(version_queried)
6119 })
6120 } else {
6121 !buffer_mtime.bad_is_greater_than(lsp_data.mtime)
6122 }
6123 })
6124 .flat_map(|lsp_data| lsp_data.buffer_lsp_data.values())
6125 .filter_map(|buffer_data| buffer_data.get(&abs_path))
6126 .filter_map(|buffer_data| {
6127 let colors = buffer_data.colors.as_ref()?;
6128 received_colors_data = true;
6129 Some(colors)
6130 })
6131 .flatten()
6132 .cloned()
6133 .collect::<HashSet<_>>();
6134
6135 if buffer_lsp_data.is_empty() || for_server_id.is_some() {
6136 if received_colors_data && for_server_id.is_none() {
6137 return None;
6138 }
6139
6140 let mut outdated_lsp_data = false;
6141 if self.lsp_data.is_none()
6142 || self.lsp_data.as_ref().is_some_and(|lsp_data| {
6143 if buffer_mtime == lsp_data.mtime {
6144 lsp_data
6145 .last_version_queried
6146 .get(&abs_path)
6147 .is_none_or(|version_queried| {
6148 buffer_version.changed_since(version_queried)
6149 })
6150 } else {
6151 buffer_mtime.bad_is_greater_than(lsp_data.mtime)
6152 }
6153 })
6154 {
6155 self.lsp_data = Some(LspData {
6156 mtime: buffer_mtime,
6157 buffer_lsp_data: HashMap::default(),
6158 colors_update: HashMap::default(),
6159 last_version_queried: HashMap::default(),
6160 });
6161 outdated_lsp_data = true;
6162 }
6163
6164 {
6165 let lsp_data = self.lsp_data.as_mut()?;
6166 match for_server_id {
6167 Some(for_server_id) if !outdated_lsp_data => {
6168 lsp_data.buffer_lsp_data.remove(&for_server_id);
6169 }
6170 None | Some(_) => {
6171 let existing_task = lsp_data.colors_update.get(&abs_path).cloned();
6172 if !outdated_lsp_data && existing_task.is_some() {
6173 return existing_task;
6174 }
6175 for buffer_data in lsp_data.buffer_lsp_data.values_mut() {
6176 if let Some(buffer_data) = buffer_data.get_mut(&abs_path) {
6177 buffer_data.colors = None;
6178 }
6179 }
6180 }
6181 }
6182 }
6183
6184 let task_abs_path = abs_path.clone();
6185 let new_task = cx
6186 .spawn(async move |lsp_store, cx| {
6187 match fetch_document_colors(
6188 lsp_store.clone(),
6189 buffer,
6190 task_abs_path.clone(),
6191 cx,
6192 )
6193 .await
6194 {
6195 Ok(colors) => Ok(colors),
6196 Err(e) => {
6197 lsp_store
6198 .update(cx, |lsp_store, _| {
6199 if let Some(lsp_data) = lsp_store.lsp_data.as_mut() {
6200 lsp_data.colors_update.remove(&task_abs_path);
6201 }
6202 })
6203 .ok();
6204 Err(Arc::new(e))
6205 }
6206 }
6207 })
6208 .shared();
6209 let lsp_data = self.lsp_data.as_mut()?;
6210 lsp_data
6211 .colors_update
6212 .insert(abs_path.clone(), new_task.clone());
6213 lsp_data
6214 .last_version_queried
6215 .insert(abs_path, buffer_version);
6216 lsp_data.mtime = buffer_mtime;
6217 Some(new_task)
6218 } else {
6219 Some(Task::ready(Ok(buffer_lsp_data)).shared())
6220 }
6221 }
6222
6223 fn fetch_document_colors_for_buffer(
6224 &mut self,
6225 buffer: Entity<Buffer>,
6226 cx: &mut Context<Self>,
6227 ) -> Task<anyhow::Result<Vec<(LanguageServerId, HashSet<DocumentColor>)>>> {
6228 if let Some((client, project_id)) = self.upstream_client() {
6229 let request_task = client.request(proto::MultiLspQuery {
6230 project_id,
6231 buffer_id: buffer.read(cx).remote_id().to_proto(),
6232 version: serialize_version(&buffer.read(cx).version()),
6233 strategy: Some(proto::multi_lsp_query::Strategy::All(
6234 proto::AllLanguageServers {},
6235 )),
6236 request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
6237 GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
6238 )),
6239 });
6240 cx.spawn(async move |project, cx| {
6241 let Some(project) = project.upgrade() else {
6242 return Ok(Vec::new());
6243 };
6244 let colors = join_all(
6245 request_task
6246 .await
6247 .log_err()
6248 .map(|response| response.responses)
6249 .unwrap_or_default()
6250 .into_iter()
6251 .filter_map(|lsp_response| match lsp_response.response? {
6252 proto::lsp_response::Response::GetDocumentColorResponse(response) => {
6253 Some((
6254 LanguageServerId::from_proto(lsp_response.server_id),
6255 response,
6256 ))
6257 }
6258 unexpected => {
6259 debug_panic!("Unexpected response: {unexpected:?}");
6260 None
6261 }
6262 })
6263 .map(|(server_id, color_response)| {
6264 let response = GetDocumentColor {}.response_from_proto(
6265 color_response,
6266 project.clone(),
6267 buffer.clone(),
6268 cx.clone(),
6269 );
6270 async move { (server_id, response.await.log_err().unwrap_or_default()) }
6271 }),
6272 )
6273 .await
6274 .into_iter()
6275 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6276 acc.entry(server_id)
6277 .or_insert_with(HashSet::default)
6278 .extend(colors);
6279 acc
6280 })
6281 .into_iter()
6282 .collect();
6283 Ok(colors)
6284 })
6285 } else {
6286 let document_colors_task =
6287 self.request_multiple_lsp_locally(&buffer, None::<usize>, GetDocumentColor, cx);
6288 cx.spawn(async move |_, _| {
6289 Ok(document_colors_task
6290 .await
6291 .into_iter()
6292 .fold(HashMap::default(), |mut acc, (server_id, colors)| {
6293 acc.entry(server_id)
6294 .or_insert_with(HashSet::default)
6295 .extend(colors);
6296 acc
6297 })
6298 .into_iter()
6299 .collect())
6300 })
6301 }
6302 }
6303
6304 pub fn signature_help<T: ToPointUtf16>(
6305 &mut self,
6306 buffer: &Entity<Buffer>,
6307 position: T,
6308 cx: &mut Context<Self>,
6309 ) -> Task<Vec<SignatureHelp>> {
6310 let position = position.to_point_utf16(buffer.read(cx));
6311
6312 if let Some((client, upstream_project_id)) = self.upstream_client() {
6313 let request_task = client.request(proto::MultiLspQuery {
6314 buffer_id: buffer.read(cx).remote_id().into(),
6315 version: serialize_version(&buffer.read(cx).version()),
6316 project_id: upstream_project_id,
6317 strategy: Some(proto::multi_lsp_query::Strategy::All(
6318 proto::AllLanguageServers {},
6319 )),
6320 request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
6321 GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
6322 )),
6323 });
6324 let buffer = buffer.clone();
6325 cx.spawn(async move |weak_project, cx| {
6326 let Some(project) = weak_project.upgrade() else {
6327 return Vec::new();
6328 };
6329 join_all(
6330 request_task
6331 .await
6332 .log_err()
6333 .map(|response| response.responses)
6334 .unwrap_or_default()
6335 .into_iter()
6336 .filter_map(|lsp_response| match lsp_response.response? {
6337 proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
6338 Some(response)
6339 }
6340 unexpected => {
6341 debug_panic!("Unexpected response: {unexpected:?}");
6342 None
6343 }
6344 })
6345 .map(|signature_response| {
6346 let response = GetSignatureHelp { position }.response_from_proto(
6347 signature_response,
6348 project.clone(),
6349 buffer.clone(),
6350 cx.clone(),
6351 );
6352 async move { response.await.log_err().flatten() }
6353 }),
6354 )
6355 .await
6356 .into_iter()
6357 .flatten()
6358 .collect()
6359 })
6360 } else {
6361 let all_actions_task = self.request_multiple_lsp_locally(
6362 buffer,
6363 Some(position),
6364 GetSignatureHelp { position },
6365 cx,
6366 );
6367 cx.spawn(async move |_, _| {
6368 all_actions_task
6369 .await
6370 .into_iter()
6371 .flat_map(|(_, actions)| actions)
6372 .filter(|help| !help.label.is_empty())
6373 .collect::<Vec<_>>()
6374 })
6375 }
6376 }
6377
6378 pub fn hover(
6379 &mut self,
6380 buffer: &Entity<Buffer>,
6381 position: PointUtf16,
6382 cx: &mut Context<Self>,
6383 ) -> Task<Vec<Hover>> {
6384 if let Some((client, upstream_project_id)) = self.upstream_client() {
6385 let request_task = client.request(proto::MultiLspQuery {
6386 buffer_id: buffer.read(cx).remote_id().into(),
6387 version: serialize_version(&buffer.read(cx).version()),
6388 project_id: upstream_project_id,
6389 strategy: Some(proto::multi_lsp_query::Strategy::All(
6390 proto::AllLanguageServers {},
6391 )),
6392 request: Some(proto::multi_lsp_query::Request::GetHover(
6393 GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
6394 )),
6395 });
6396 let buffer = buffer.clone();
6397 cx.spawn(async move |weak_project, cx| {
6398 let Some(project) = weak_project.upgrade() else {
6399 return Vec::new();
6400 };
6401 join_all(
6402 request_task
6403 .await
6404 .log_err()
6405 .map(|response| response.responses)
6406 .unwrap_or_default()
6407 .into_iter()
6408 .filter_map(|lsp_response| match lsp_response.response? {
6409 proto::lsp_response::Response::GetHoverResponse(response) => {
6410 Some(response)
6411 }
6412 unexpected => {
6413 debug_panic!("Unexpected response: {unexpected:?}");
6414 None
6415 }
6416 })
6417 .map(|hover_response| {
6418 let response = GetHover { position }.response_from_proto(
6419 hover_response,
6420 project.clone(),
6421 buffer.clone(),
6422 cx.clone(),
6423 );
6424 async move {
6425 response
6426 .await
6427 .log_err()
6428 .flatten()
6429 .and_then(remove_empty_hover_blocks)
6430 }
6431 }),
6432 )
6433 .await
6434 .into_iter()
6435 .flatten()
6436 .collect()
6437 })
6438 } else {
6439 let all_actions_task = self.request_multiple_lsp_locally(
6440 buffer,
6441 Some(position),
6442 GetHover { position },
6443 cx,
6444 );
6445 cx.spawn(async move |_, _| {
6446 all_actions_task
6447 .await
6448 .into_iter()
6449 .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
6450 .collect::<Vec<Hover>>()
6451 })
6452 }
6453 }
6454
6455 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
6456 let language_registry = self.languages.clone();
6457
6458 if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
6459 let request = upstream_client.request(proto::GetProjectSymbols {
6460 project_id: *project_id,
6461 query: query.to_string(),
6462 });
6463 cx.foreground_executor().spawn(async move {
6464 let response = request.await?;
6465 let mut symbols = Vec::new();
6466 let core_symbols = response
6467 .symbols
6468 .into_iter()
6469 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
6470 .collect::<Vec<_>>();
6471 populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
6472 .await;
6473 Ok(symbols)
6474 })
6475 } else if let Some(local) = self.as_local() {
6476 struct WorkspaceSymbolsResult {
6477 server_id: LanguageServerId,
6478 lsp_adapter: Arc<CachedLspAdapter>,
6479 worktree: WeakEntity<Worktree>,
6480 worktree_abs_path: Arc<Path>,
6481 lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
6482 }
6483
6484 let mut requests = Vec::new();
6485 let mut requested_servers = BTreeSet::new();
6486 'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
6487 let Some(worktree_handle) = self
6488 .worktree_store
6489 .read(cx)
6490 .worktree_for_id(*worktree_id, cx)
6491 else {
6492 continue;
6493 };
6494 let worktree = worktree_handle.read(cx);
6495 if !worktree.is_visible() {
6496 continue;
6497 }
6498
6499 let mut servers_to_query = server_ids
6500 .difference(&requested_servers)
6501 .cloned()
6502 .collect::<BTreeSet<_>>();
6503 for server_id in &servers_to_query {
6504 let (lsp_adapter, server) = match local.language_servers.get(server_id) {
6505 Some(LanguageServerState::Running {
6506 adapter, server, ..
6507 }) => (adapter.clone(), server),
6508
6509 _ => continue 'next_server,
6510 };
6511 let supports_workspace_symbol_request =
6512 match server.capabilities().workspace_symbol_provider {
6513 Some(OneOf::Left(supported)) => supported,
6514 Some(OneOf::Right(_)) => true,
6515 None => false,
6516 };
6517 if !supports_workspace_symbol_request {
6518 continue 'next_server;
6519 }
6520 let worktree_abs_path = worktree.abs_path().clone();
6521 let worktree_handle = worktree_handle.clone();
6522 let server_id = server.server_id();
6523 requests.push(
6524 server
6525 .request::<lsp::request::WorkspaceSymbolRequest>(
6526 lsp::WorkspaceSymbolParams {
6527 query: query.to_string(),
6528 ..Default::default()
6529 },
6530 )
6531 .map(move |response| {
6532 let lsp_symbols = response.into_response()
6533 .context("workspace symbols request")
6534 .log_err()
6535 .flatten()
6536 .map(|symbol_response| match symbol_response {
6537 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
6538 flat_responses.into_iter().map(|lsp_symbol| {
6539 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
6540 }).collect::<Vec<_>>()
6541 }
6542 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
6543 nested_responses.into_iter().filter_map(|lsp_symbol| {
6544 let location = match lsp_symbol.location {
6545 OneOf::Left(location) => location,
6546 OneOf::Right(_) => {
6547 log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
6548 return None
6549 }
6550 };
6551 Some((lsp_symbol.name, lsp_symbol.kind, location))
6552 }).collect::<Vec<_>>()
6553 }
6554 }).unwrap_or_default();
6555
6556 WorkspaceSymbolsResult {
6557 server_id,
6558 lsp_adapter,
6559 worktree: worktree_handle.downgrade(),
6560 worktree_abs_path,
6561 lsp_symbols,
6562 }
6563 }),
6564 );
6565 }
6566 requested_servers.append(&mut servers_to_query);
6567 }
6568
6569 cx.spawn(async move |this, cx| {
6570 let responses = futures::future::join_all(requests).await;
6571 let this = match this.upgrade() {
6572 Some(this) => this,
6573 None => return Ok(Vec::new()),
6574 };
6575
6576 let mut symbols = Vec::new();
6577 for result in responses {
6578 let core_symbols = this.update(cx, |this, cx| {
6579 result
6580 .lsp_symbols
6581 .into_iter()
6582 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
6583 let abs_path = symbol_location.uri.to_file_path().ok()?;
6584 let source_worktree = result.worktree.upgrade()?;
6585 let source_worktree_id = source_worktree.read(cx).id();
6586
6587 let path;
6588 let worktree;
6589 if let Some((tree, rel_path)) =
6590 this.worktree_store.read(cx).find_worktree(&abs_path, cx)
6591 {
6592 worktree = tree;
6593 path = rel_path;
6594 } else {
6595 worktree = source_worktree.clone();
6596 path = relativize_path(&result.worktree_abs_path, &abs_path);
6597 }
6598
6599 let worktree_id = worktree.read(cx).id();
6600 let project_path = ProjectPath {
6601 worktree_id,
6602 path: path.into(),
6603 };
6604 let signature = this.symbol_signature(&project_path);
6605 Some(CoreSymbol {
6606 source_language_server_id: result.server_id,
6607 language_server_name: result.lsp_adapter.name.clone(),
6608 source_worktree_id,
6609 path: project_path,
6610 kind: symbol_kind,
6611 name: symbol_name,
6612 range: range_from_lsp(symbol_location.range),
6613 signature,
6614 })
6615 })
6616 .collect()
6617 })?;
6618
6619 populate_labels_for_symbols(
6620 core_symbols,
6621 &language_registry,
6622 Some(result.lsp_adapter),
6623 &mut symbols,
6624 )
6625 .await;
6626 }
6627
6628 Ok(symbols)
6629 })
6630 } else {
6631 Task::ready(Err(anyhow!("No upstream client or local language server")))
6632 }
6633 }
6634
6635 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
6636 let mut summary = DiagnosticSummary::default();
6637 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
6638 summary.error_count += path_summary.error_count;
6639 summary.warning_count += path_summary.warning_count;
6640 }
6641 summary
6642 }
6643
6644 pub fn diagnostic_summaries<'a>(
6645 &'a self,
6646 include_ignored: bool,
6647 cx: &'a App,
6648 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6649 self.worktree_store
6650 .read(cx)
6651 .visible_worktrees(cx)
6652 .filter_map(|worktree| {
6653 let worktree = worktree.read(cx);
6654 Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
6655 })
6656 .flat_map(move |(worktree, summaries)| {
6657 let worktree_id = worktree.id();
6658 summaries
6659 .iter()
6660 .filter(move |(path, _)| {
6661 include_ignored
6662 || worktree
6663 .entry_for_path(path.as_ref())
6664 .map_or(false, |entry| !entry.is_ignored)
6665 })
6666 .flat_map(move |(path, summaries)| {
6667 summaries.iter().map(move |(server_id, summary)| {
6668 (
6669 ProjectPath {
6670 worktree_id,
6671 path: path.clone(),
6672 },
6673 *server_id,
6674 *summary,
6675 )
6676 })
6677 })
6678 })
6679 }
6680
6681 pub fn on_buffer_edited(
6682 &mut self,
6683 buffer: Entity<Buffer>,
6684 cx: &mut Context<Self>,
6685 ) -> Option<()> {
6686 let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
6687 Some(
6688 self.as_local()?
6689 .language_servers_for_buffer(buffer, cx)
6690 .map(|i| i.1.clone())
6691 .collect(),
6692 )
6693 })?;
6694
6695 let buffer = buffer.read(cx);
6696 let file = File::from_dyn(buffer.file())?;
6697 let abs_path = file.as_local()?.abs_path(cx);
6698 let uri = lsp::Url::from_file_path(abs_path).unwrap();
6699 let next_snapshot = buffer.text_snapshot();
6700 for language_server in language_servers {
6701 let language_server = language_server.clone();
6702
6703 let buffer_snapshots = self
6704 .as_local_mut()
6705 .unwrap()
6706 .buffer_snapshots
6707 .get_mut(&buffer.remote_id())
6708 .and_then(|m| m.get_mut(&language_server.server_id()))?;
6709 let previous_snapshot = buffer_snapshots.last()?;
6710
6711 let build_incremental_change = || {
6712 buffer
6713 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
6714 .map(|edit| {
6715 let edit_start = edit.new.start.0;
6716 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
6717 let new_text = next_snapshot
6718 .text_for_range(edit.new.start.1..edit.new.end.1)
6719 .collect();
6720 lsp::TextDocumentContentChangeEvent {
6721 range: Some(lsp::Range::new(
6722 point_to_lsp(edit_start),
6723 point_to_lsp(edit_end),
6724 )),
6725 range_length: None,
6726 text: new_text,
6727 }
6728 })
6729 .collect()
6730 };
6731
6732 let document_sync_kind = language_server
6733 .capabilities()
6734 .text_document_sync
6735 .as_ref()
6736 .and_then(|sync| match sync {
6737 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
6738 lsp::TextDocumentSyncCapability::Options(options) => options.change,
6739 });
6740
6741 let content_changes: Vec<_> = match document_sync_kind {
6742 Some(lsp::TextDocumentSyncKind::FULL) => {
6743 vec![lsp::TextDocumentContentChangeEvent {
6744 range: None,
6745 range_length: None,
6746 text: next_snapshot.text(),
6747 }]
6748 }
6749 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
6750 _ => {
6751 #[cfg(any(test, feature = "test-support"))]
6752 {
6753 build_incremental_change()
6754 }
6755
6756 #[cfg(not(any(test, feature = "test-support")))]
6757 {
6758 continue;
6759 }
6760 }
6761 };
6762
6763 let next_version = previous_snapshot.version + 1;
6764 buffer_snapshots.push(LspBufferSnapshot {
6765 version: next_version,
6766 snapshot: next_snapshot.clone(),
6767 });
6768
6769 language_server
6770 .notify::<lsp::notification::DidChangeTextDocument>(
6771 &lsp::DidChangeTextDocumentParams {
6772 text_document: lsp::VersionedTextDocumentIdentifier::new(
6773 uri.clone(),
6774 next_version,
6775 ),
6776 content_changes,
6777 },
6778 )
6779 .ok();
6780 self.pull_workspace_diagnostics(language_server.server_id());
6781 }
6782
6783 None
6784 }
6785
6786 pub fn on_buffer_saved(
6787 &mut self,
6788 buffer: Entity<Buffer>,
6789 cx: &mut Context<Self>,
6790 ) -> Option<()> {
6791 let file = File::from_dyn(buffer.read(cx).file())?;
6792 let worktree_id = file.worktree_id(cx);
6793 let abs_path = file.as_local()?.abs_path(cx);
6794 let text_document = lsp::TextDocumentIdentifier {
6795 uri: file_path_to_lsp_url(&abs_path).log_err()?,
6796 };
6797 let local = self.as_local()?;
6798
6799 for server in local.language_servers_for_worktree(worktree_id) {
6800 if let Some(include_text) = include_text(server.as_ref()) {
6801 let text = if include_text {
6802 Some(buffer.read(cx).text())
6803 } else {
6804 None
6805 };
6806 server
6807 .notify::<lsp::notification::DidSaveTextDocument>(
6808 &lsp::DidSaveTextDocumentParams {
6809 text_document: text_document.clone(),
6810 text,
6811 },
6812 )
6813 .ok();
6814 }
6815 }
6816
6817 let language_servers = buffer.update(cx, |buffer, cx| {
6818 local.language_server_ids_for_buffer(buffer, cx)
6819 });
6820 for language_server_id in language_servers {
6821 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
6822 }
6823
6824 None
6825 }
6826
6827 pub(crate) async fn refresh_workspace_configurations(
6828 this: &WeakEntity<Self>,
6829 fs: Arc<dyn Fs>,
6830 cx: &mut AsyncApp,
6831 ) {
6832 maybe!(async move {
6833 let servers = this
6834 .update(cx, |this, cx| {
6835 let Some(local) = this.as_local() else {
6836 return Vec::default();
6837 };
6838 local
6839 .language_server_ids
6840 .iter()
6841 .flat_map(|((worktree_id, _), server_ids)| {
6842 let worktree = this
6843 .worktree_store
6844 .read(cx)
6845 .worktree_for_id(*worktree_id, cx);
6846 let delegate = worktree.map(|worktree| {
6847 LocalLspAdapterDelegate::new(
6848 local.languages.clone(),
6849 &local.environment,
6850 cx.weak_entity(),
6851 &worktree,
6852 local.http_client.clone(),
6853 local.fs.clone(),
6854 cx,
6855 )
6856 });
6857
6858 server_ids.iter().filter_map(move |server_id| {
6859 let states = local.language_servers.get(server_id)?;
6860
6861 match states {
6862 LanguageServerState::Starting { .. } => None,
6863 LanguageServerState::Running {
6864 adapter, server, ..
6865 } => Some((
6866 adapter.adapter.clone(),
6867 server.clone(),
6868 delegate.clone()? as Arc<dyn LspAdapterDelegate>,
6869 )),
6870 }
6871 })
6872 })
6873 .collect::<Vec<_>>()
6874 })
6875 .ok()?;
6876
6877 let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
6878 for (adapter, server, delegate) in servers {
6879 let settings = LocalLspStore::workspace_configuration_for_adapter(
6880 adapter,
6881 fs.as_ref(),
6882 &delegate,
6883 toolchain_store.clone(),
6884 cx,
6885 )
6886 .await
6887 .ok()?;
6888
6889 server
6890 .notify::<lsp::notification::DidChangeConfiguration>(
6891 &lsp::DidChangeConfigurationParams { settings },
6892 )
6893 .ok();
6894 }
6895 Some(())
6896 })
6897 .await;
6898 }
6899
6900 fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
6901 if let Some(toolchain_store) = self.toolchain_store.as_ref() {
6902 toolchain_store.read(cx).as_language_toolchain_store()
6903 } else {
6904 Arc::new(EmptyToolchainStore)
6905 }
6906 }
6907 fn maintain_workspace_config(
6908 fs: Arc<dyn Fs>,
6909 external_refresh_requests: watch::Receiver<()>,
6910 cx: &mut Context<Self>,
6911 ) -> Task<Result<()>> {
6912 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
6913 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
6914
6915 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
6916 *settings_changed_tx.borrow_mut() = ();
6917 });
6918
6919 let mut joint_future =
6920 futures::stream::select(settings_changed_rx, external_refresh_requests);
6921 cx.spawn(async move |this, cx| {
6922 while let Some(()) = joint_future.next().await {
6923 Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
6924 }
6925
6926 drop(settings_observation);
6927 anyhow::Ok(())
6928 })
6929 }
6930
6931 pub fn language_servers_for_local_buffer<'a>(
6932 &'a self,
6933 buffer: &Buffer,
6934 cx: &mut App,
6935 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6936 let local = self.as_local();
6937 let language_server_ids = local
6938 .map(|local| local.language_server_ids_for_buffer(buffer, cx))
6939 .unwrap_or_default();
6940
6941 language_server_ids
6942 .into_iter()
6943 .filter_map(
6944 move |server_id| match local?.language_servers.get(&server_id)? {
6945 LanguageServerState::Running {
6946 adapter, server, ..
6947 } => Some((adapter, server)),
6948 _ => None,
6949 },
6950 )
6951 }
6952
6953 pub fn language_server_for_local_buffer<'a>(
6954 &'a self,
6955 buffer: &'a Buffer,
6956 server_id: LanguageServerId,
6957 cx: &'a mut App,
6958 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
6959 self.as_local()?
6960 .language_servers_for_buffer(buffer, cx)
6961 .find(|(_, s)| s.server_id() == server_id)
6962 }
6963
6964 fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
6965 self.diagnostic_summaries.remove(&id_to_remove);
6966 if let Some(local) = self.as_local_mut() {
6967 let to_remove = local.remove_worktree(id_to_remove, cx);
6968 for server in to_remove {
6969 self.language_server_statuses.remove(&server);
6970 }
6971 }
6972 }
6973
6974 pub fn shared(
6975 &mut self,
6976 project_id: u64,
6977 downstream_client: AnyProtoClient,
6978 _: &mut Context<Self>,
6979 ) {
6980 self.downstream_client = Some((downstream_client.clone(), project_id));
6981
6982 for (server_id, status) in &self.language_server_statuses {
6983 downstream_client
6984 .send(proto::StartLanguageServer {
6985 project_id,
6986 server: Some(proto::LanguageServer {
6987 id: server_id.0 as u64,
6988 name: status.name.clone(),
6989 worktree_id: None,
6990 }),
6991 })
6992 .log_err();
6993 }
6994 }
6995
6996 pub fn disconnected_from_host(&mut self) {
6997 self.downstream_client.take();
6998 }
6999
7000 pub fn disconnected_from_ssh_remote(&mut self) {
7001 if let LspStoreMode::Remote(RemoteLspStore {
7002 upstream_client, ..
7003 }) = &mut self.mode
7004 {
7005 upstream_client.take();
7006 }
7007 }
7008
7009 pub(crate) fn set_language_server_statuses_from_proto(
7010 &mut self,
7011 language_servers: Vec<proto::LanguageServer>,
7012 ) {
7013 self.language_server_statuses = language_servers
7014 .into_iter()
7015 .map(|server| {
7016 (
7017 LanguageServerId(server.id as usize),
7018 LanguageServerStatus {
7019 name: server.name,
7020 pending_work: Default::default(),
7021 has_pending_diagnostic_updates: false,
7022 progress_tokens: Default::default(),
7023 },
7024 )
7025 })
7026 .collect();
7027 }
7028
7029 fn register_local_language_server(
7030 &mut self,
7031 worktree: Entity<Worktree>,
7032 language_server_name: LanguageServerName,
7033 language_server_id: LanguageServerId,
7034 cx: &mut App,
7035 ) {
7036 let Some(local) = self.as_local_mut() else {
7037 return;
7038 };
7039
7040 let worktree_id = worktree.read(cx).id();
7041 if worktree.read(cx).is_visible() {
7042 let path = ProjectPath {
7043 worktree_id,
7044 path: Arc::from("".as_ref()),
7045 };
7046 let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
7047 local.lsp_tree.update(cx, |language_server_tree, cx| {
7048 for node in language_server_tree.get(
7049 path,
7050 AdapterQuery::Adapter(&language_server_name),
7051 delegate,
7052 cx,
7053 ) {
7054 node.server_id_or_init(|disposition| {
7055 assert_eq!(disposition.server_name, &language_server_name);
7056
7057 language_server_id
7058 });
7059 }
7060 });
7061 }
7062
7063 local
7064 .language_server_ids
7065 .entry((worktree_id, language_server_name))
7066 .or_default()
7067 .insert(language_server_id);
7068 }
7069
7070 #[cfg(test)]
7071 pub fn update_diagnostic_entries(
7072 &mut self,
7073 server_id: LanguageServerId,
7074 abs_path: PathBuf,
7075 result_id: Option<String>,
7076 version: Option<i32>,
7077 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7078 cx: &mut Context<Self>,
7079 ) -> anyhow::Result<()> {
7080 self.merge_diagnostic_entries(
7081 server_id,
7082 abs_path,
7083 result_id,
7084 version,
7085 diagnostics,
7086 |_, _, _| false,
7087 cx,
7088 )
7089 }
7090
7091 pub fn merge_diagnostic_entries(
7092 &mut self,
7093 server_id: LanguageServerId,
7094 abs_path: PathBuf,
7095 result_id: Option<String>,
7096 version: Option<i32>,
7097 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7098 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
7099 cx: &mut Context<Self>,
7100 ) -> anyhow::Result<()> {
7101 let Some((worktree, relative_path)) =
7102 self.worktree_store.read(cx).find_worktree(&abs_path, cx)
7103 else {
7104 log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
7105 return Ok(());
7106 };
7107
7108 let project_path = ProjectPath {
7109 worktree_id: worktree.read(cx).id(),
7110 path: relative_path.into(),
7111 };
7112
7113 if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path, cx) {
7114 let snapshot = buffer_handle.read(cx).snapshot();
7115 let buffer = buffer_handle.read(cx);
7116 let reused_diagnostics = buffer
7117 .get_diagnostics(server_id)
7118 .into_iter()
7119 .flat_map(|diag| {
7120 diag.iter()
7121 .filter(|v| filter(buffer, &v.diagnostic, cx))
7122 .map(|v| {
7123 let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
7124 let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
7125 DiagnosticEntry {
7126 range: start..end,
7127 diagnostic: v.diagnostic.clone(),
7128 }
7129 })
7130 })
7131 .collect::<Vec<_>>();
7132
7133 self.as_local_mut()
7134 .context("cannot merge diagnostics on a remote LspStore")?
7135 .update_buffer_diagnostics(
7136 &buffer_handle,
7137 server_id,
7138 result_id,
7139 version,
7140 diagnostics.clone(),
7141 reused_diagnostics.clone(),
7142 cx,
7143 )?;
7144
7145 diagnostics.extend(reused_diagnostics);
7146 }
7147
7148 let updated = worktree.update(cx, |worktree, cx| {
7149 self.update_worktree_diagnostics(
7150 worktree.id(),
7151 server_id,
7152 project_path.path.clone(),
7153 diagnostics,
7154 cx,
7155 )
7156 })?;
7157 if updated {
7158 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7159 language_server_id: server_id,
7160 path: project_path,
7161 })
7162 }
7163 Ok(())
7164 }
7165
7166 fn update_worktree_diagnostics(
7167 &mut self,
7168 worktree_id: WorktreeId,
7169 server_id: LanguageServerId,
7170 worktree_path: Arc<Path>,
7171 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
7172 _: &mut Context<Worktree>,
7173 ) -> Result<bool> {
7174 let local = match &mut self.mode {
7175 LspStoreMode::Local(local_lsp_store) => local_lsp_store,
7176 _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
7177 };
7178
7179 let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
7180 let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
7181 let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
7182
7183 let old_summary = summaries_by_server_id
7184 .remove(&server_id)
7185 .unwrap_or_default();
7186
7187 let new_summary = DiagnosticSummary::new(&diagnostics);
7188 if new_summary.is_empty() {
7189 if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
7190 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7191 diagnostics_by_server_id.remove(ix);
7192 }
7193 if diagnostics_by_server_id.is_empty() {
7194 diagnostics_for_tree.remove(&worktree_path);
7195 }
7196 }
7197 } else {
7198 summaries_by_server_id.insert(server_id, new_summary);
7199 let diagnostics_by_server_id = diagnostics_for_tree
7200 .entry(worktree_path.clone())
7201 .or_default();
7202 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
7203 Ok(ix) => {
7204 diagnostics_by_server_id[ix] = (server_id, diagnostics);
7205 }
7206 Err(ix) => {
7207 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
7208 }
7209 }
7210 }
7211
7212 if !old_summary.is_empty() || !new_summary.is_empty() {
7213 if let Some((downstream_client, project_id)) = &self.downstream_client {
7214 downstream_client
7215 .send(proto::UpdateDiagnosticSummary {
7216 project_id: *project_id,
7217 worktree_id: worktree_id.to_proto(),
7218 summary: Some(proto::DiagnosticSummary {
7219 path: worktree_path.to_proto(),
7220 language_server_id: server_id.0 as u64,
7221 error_count: new_summary.error_count as u32,
7222 warning_count: new_summary.warning_count as u32,
7223 }),
7224 })
7225 .log_err();
7226 }
7227 }
7228
7229 Ok(!old_summary.is_empty() || !new_summary.is_empty())
7230 }
7231
7232 pub fn open_buffer_for_symbol(
7233 &mut self,
7234 symbol: &Symbol,
7235 cx: &mut Context<Self>,
7236 ) -> Task<Result<Entity<Buffer>>> {
7237 if let Some((client, project_id)) = self.upstream_client() {
7238 let request = client.request(proto::OpenBufferForSymbol {
7239 project_id,
7240 symbol: Some(Self::serialize_symbol(symbol)),
7241 });
7242 cx.spawn(async move |this, cx| {
7243 let response = request.await?;
7244 let buffer_id = BufferId::new(response.buffer_id)?;
7245 this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
7246 .await
7247 })
7248 } else if let Some(local) = self.as_local() {
7249 let Some(language_server_id) = local
7250 .language_server_ids
7251 .get(&(
7252 symbol.source_worktree_id,
7253 symbol.language_server_name.clone(),
7254 ))
7255 .and_then(|ids| {
7256 ids.contains(&symbol.source_language_server_id)
7257 .then_some(symbol.source_language_server_id)
7258 })
7259 else {
7260 return Task::ready(Err(anyhow!(
7261 "language server for worktree and language not found"
7262 )));
7263 };
7264
7265 let worktree_abs_path = if let Some(worktree_abs_path) = self
7266 .worktree_store
7267 .read(cx)
7268 .worktree_for_id(symbol.path.worktree_id, cx)
7269 .map(|worktree| worktree.read(cx).abs_path())
7270 {
7271 worktree_abs_path
7272 } else {
7273 return Task::ready(Err(anyhow!("worktree not found for symbol")));
7274 };
7275
7276 let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
7277 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
7278 uri
7279 } else {
7280 return Task::ready(Err(anyhow!("invalid symbol path")));
7281 };
7282
7283 self.open_local_buffer_via_lsp(
7284 symbol_uri,
7285 language_server_id,
7286 symbol.language_server_name.clone(),
7287 cx,
7288 )
7289 } else {
7290 Task::ready(Err(anyhow!("no upstream client or local store")))
7291 }
7292 }
7293
7294 pub fn open_local_buffer_via_lsp(
7295 &mut self,
7296 mut abs_path: lsp::Url,
7297 language_server_id: LanguageServerId,
7298 language_server_name: LanguageServerName,
7299 cx: &mut Context<Self>,
7300 ) -> Task<Result<Entity<Buffer>>> {
7301 cx.spawn(async move |lsp_store, cx| {
7302 // Escape percent-encoded string.
7303 let current_scheme = abs_path.scheme().to_owned();
7304 let _ = abs_path.set_scheme("file");
7305
7306 let abs_path = abs_path
7307 .to_file_path()
7308 .map_err(|()| anyhow!("can't convert URI to path"))?;
7309 let p = abs_path.clone();
7310 let yarn_worktree = lsp_store
7311 .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
7312 Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
7313 cx.spawn(async move |this, cx| {
7314 let t = this
7315 .update(cx, |this, cx| this.process_path(&p, ¤t_scheme, cx))
7316 .ok()?;
7317 t.await
7318 })
7319 }),
7320 None => Task::ready(None),
7321 })?
7322 .await;
7323 let (worktree_root_target, known_relative_path) =
7324 if let Some((zip_root, relative_path)) = yarn_worktree {
7325 (zip_root, Some(relative_path))
7326 } else {
7327 (Arc::<Path>::from(abs_path.as_path()), None)
7328 };
7329 let (worktree, relative_path) = if let Some(result) =
7330 lsp_store.update(cx, |lsp_store, cx| {
7331 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7332 worktree_store.find_worktree(&worktree_root_target, cx)
7333 })
7334 })? {
7335 let relative_path =
7336 known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
7337 (result.0, relative_path)
7338 } else {
7339 let worktree = lsp_store
7340 .update(cx, |lsp_store, cx| {
7341 lsp_store.worktree_store.update(cx, |worktree_store, cx| {
7342 worktree_store.create_worktree(&worktree_root_target, false, cx)
7343 })
7344 })?
7345 .await?;
7346 if worktree.read_with(cx, |worktree, _| worktree.is_local())? {
7347 lsp_store
7348 .update(cx, |lsp_store, cx| {
7349 lsp_store.register_local_language_server(
7350 worktree.clone(),
7351 language_server_name,
7352 language_server_id,
7353 cx,
7354 )
7355 })
7356 .ok();
7357 }
7358 let worktree_root = worktree.read_with(cx, |worktree, _| worktree.abs_path())?;
7359 let relative_path = if let Some(known_path) = known_relative_path {
7360 known_path
7361 } else {
7362 abs_path.strip_prefix(worktree_root)?.into()
7363 };
7364 (worktree, relative_path)
7365 };
7366 let project_path = ProjectPath {
7367 worktree_id: worktree.read_with(cx, |worktree, _| worktree.id())?,
7368 path: relative_path,
7369 };
7370 lsp_store
7371 .update(cx, |lsp_store, cx| {
7372 lsp_store.buffer_store().update(cx, |buffer_store, cx| {
7373 buffer_store.open_buffer(project_path, cx)
7374 })
7375 })?
7376 .await
7377 })
7378 }
7379
7380 fn request_multiple_lsp_locally<P, R>(
7381 &mut self,
7382 buffer: &Entity<Buffer>,
7383 position: Option<P>,
7384 request: R,
7385 cx: &mut Context<Self>,
7386 ) -> Task<Vec<(LanguageServerId, R::Response)>>
7387 where
7388 P: ToOffset,
7389 R: LspCommand + Clone,
7390 <R::LspRequest as lsp::request::Request>::Result: Send,
7391 <R::LspRequest as lsp::request::Request>::Params: Send,
7392 {
7393 let Some(local) = self.as_local() else {
7394 return Task::ready(Vec::new());
7395 };
7396
7397 let snapshot = buffer.read(cx).snapshot();
7398 let scope = position.and_then(|position| snapshot.language_scope_at(position));
7399
7400 let server_ids = buffer.update(cx, |buffer, cx| {
7401 local
7402 .language_servers_for_buffer(buffer, cx)
7403 .filter(|(adapter, _)| {
7404 scope
7405 .as_ref()
7406 .map(|scope| scope.language_allowed(&adapter.name))
7407 .unwrap_or(true)
7408 })
7409 .map(|(_, server)| server.server_id())
7410 .collect::<Vec<_>>()
7411 });
7412
7413 let mut response_results = server_ids
7414 .into_iter()
7415 .map(|server_id| {
7416 let task = self.request_lsp(
7417 buffer.clone(),
7418 LanguageServerToQuery::Other(server_id),
7419 request.clone(),
7420 cx,
7421 );
7422 async move { (server_id, task.await) }
7423 })
7424 .collect::<FuturesUnordered<_>>();
7425
7426 cx.spawn(async move |_, _| {
7427 let mut responses = Vec::with_capacity(response_results.len());
7428 while let Some((server_id, response_result)) = response_results.next().await {
7429 if let Some(response) = response_result.log_err() {
7430 responses.push((server_id, response));
7431 }
7432 }
7433 responses
7434 })
7435 }
7436
7437 async fn handle_lsp_command<T: LspCommand>(
7438 this: Entity<Self>,
7439 envelope: TypedEnvelope<T::ProtoRequest>,
7440 mut cx: AsyncApp,
7441 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7442 where
7443 <T::LspRequest as lsp::request::Request>::Params: Send,
7444 <T::LspRequest as lsp::request::Request>::Result: Send,
7445 {
7446 let sender_id = envelope.original_sender_id().unwrap_or_default();
7447 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
7448 let buffer_handle = this.update(&mut cx, |this, cx| {
7449 this.buffer_store.read(cx).get_existing(buffer_id)
7450 })??;
7451 let request = T::from_proto(
7452 envelope.payload,
7453 this.clone(),
7454 buffer_handle.clone(),
7455 cx.clone(),
7456 )
7457 .await?;
7458 let response = this
7459 .update(&mut cx, |this, cx| {
7460 this.request_lsp(
7461 buffer_handle.clone(),
7462 LanguageServerToQuery::FirstCapable,
7463 request,
7464 cx,
7465 )
7466 })?
7467 .await?;
7468 this.update(&mut cx, |this, cx| {
7469 Ok(T::response_to_proto(
7470 response,
7471 this,
7472 sender_id,
7473 &buffer_handle.read(cx).version(),
7474 cx,
7475 ))
7476 })?
7477 }
7478
7479 async fn handle_multi_lsp_query(
7480 lsp_store: Entity<Self>,
7481 envelope: TypedEnvelope<proto::MultiLspQuery>,
7482 mut cx: AsyncApp,
7483 ) -> Result<proto::MultiLspQueryResponse> {
7484 let response_from_ssh = lsp_store.read_with(&mut cx, |this, _| {
7485 let (upstream_client, project_id) = this.upstream_client()?;
7486 let mut payload = envelope.payload.clone();
7487 payload.project_id = project_id;
7488
7489 Some(upstream_client.request(payload))
7490 })?;
7491 if let Some(response_from_ssh) = response_from_ssh {
7492 return response_from_ssh.await;
7493 }
7494
7495 let sender_id = envelope.original_sender_id().unwrap_or_default();
7496 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7497 let version = deserialize_version(&envelope.payload.version);
7498 let buffer = lsp_store.update(&mut cx, |this, cx| {
7499 this.buffer_store.read(cx).get_existing(buffer_id)
7500 })??;
7501 buffer
7502 .update(&mut cx, |buffer, _| {
7503 buffer.wait_for_version(version.clone())
7504 })?
7505 .await?;
7506 let buffer_version = buffer.read_with(&mut cx, |buffer, _| buffer.version())?;
7507 match envelope
7508 .payload
7509 .strategy
7510 .context("invalid request without the strategy")?
7511 {
7512 proto::multi_lsp_query::Strategy::All(_) => {
7513 // currently, there's only one multiple language servers query strategy,
7514 // so just ensure it's specified correctly
7515 }
7516 }
7517 match envelope.payload.request {
7518 Some(proto::multi_lsp_query::Request::GetHover(message)) => {
7519 buffer
7520 .update(&mut cx, |buffer, _| {
7521 buffer.wait_for_version(deserialize_version(&message.version))
7522 })?
7523 .await?;
7524 let get_hover =
7525 GetHover::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7526 .await?;
7527 let all_hovers = lsp_store
7528 .update(&mut cx, |this, cx| {
7529 this.request_multiple_lsp_locally(
7530 &buffer,
7531 Some(get_hover.position),
7532 get_hover,
7533 cx,
7534 )
7535 })?
7536 .await
7537 .into_iter()
7538 .filter_map(|(server_id, hover)| {
7539 Some((server_id, remove_empty_hover_blocks(hover?)?))
7540 });
7541 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7542 responses: all_hovers
7543 .map(|(server_id, hover)| proto::LspResponse {
7544 server_id: server_id.to_proto(),
7545 response: Some(proto::lsp_response::Response::GetHoverResponse(
7546 GetHover::response_to_proto(
7547 Some(hover),
7548 project,
7549 sender_id,
7550 &buffer_version,
7551 cx,
7552 ),
7553 )),
7554 })
7555 .collect(),
7556 })
7557 }
7558 Some(proto::multi_lsp_query::Request::GetCodeActions(message)) => {
7559 buffer
7560 .update(&mut cx, |buffer, _| {
7561 buffer.wait_for_version(deserialize_version(&message.version))
7562 })?
7563 .await?;
7564 let get_code_actions = GetCodeActions::from_proto(
7565 message,
7566 lsp_store.clone(),
7567 buffer.clone(),
7568 cx.clone(),
7569 )
7570 .await?;
7571
7572 let all_actions = lsp_store
7573 .update(&mut cx, |project, cx| {
7574 project.request_multiple_lsp_locally(
7575 &buffer,
7576 Some(get_code_actions.range.start),
7577 get_code_actions,
7578 cx,
7579 )
7580 })?
7581 .await
7582 .into_iter();
7583
7584 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7585 responses: all_actions
7586 .map(|(server_id, code_actions)| proto::LspResponse {
7587 server_id: server_id.to_proto(),
7588 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
7589 GetCodeActions::response_to_proto(
7590 code_actions,
7591 project,
7592 sender_id,
7593 &buffer_version,
7594 cx,
7595 ),
7596 )),
7597 })
7598 .collect(),
7599 })
7600 }
7601 Some(proto::multi_lsp_query::Request::GetSignatureHelp(message)) => {
7602 buffer
7603 .update(&mut cx, |buffer, _| {
7604 buffer.wait_for_version(deserialize_version(&message.version))
7605 })?
7606 .await?;
7607 let get_signature_help = GetSignatureHelp::from_proto(
7608 message,
7609 lsp_store.clone(),
7610 buffer.clone(),
7611 cx.clone(),
7612 )
7613 .await?;
7614
7615 let all_signatures = lsp_store
7616 .update(&mut cx, |project, cx| {
7617 project.request_multiple_lsp_locally(
7618 &buffer,
7619 Some(get_signature_help.position),
7620 get_signature_help,
7621 cx,
7622 )
7623 })?
7624 .await
7625 .into_iter();
7626
7627 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7628 responses: all_signatures
7629 .map(|(server_id, signature_help)| proto::LspResponse {
7630 server_id: server_id.to_proto(),
7631 response: Some(
7632 proto::lsp_response::Response::GetSignatureHelpResponse(
7633 GetSignatureHelp::response_to_proto(
7634 signature_help,
7635 project,
7636 sender_id,
7637 &buffer_version,
7638 cx,
7639 ),
7640 ),
7641 ),
7642 })
7643 .collect(),
7644 })
7645 }
7646 Some(proto::multi_lsp_query::Request::GetCodeLens(message)) => {
7647 buffer
7648 .update(&mut cx, |buffer, _| {
7649 buffer.wait_for_version(deserialize_version(&message.version))
7650 })?
7651 .await?;
7652 let get_code_lens =
7653 GetCodeLens::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
7654 .await?;
7655
7656 let code_lens_actions = lsp_store
7657 .update(&mut cx, |project, cx| {
7658 project.request_multiple_lsp_locally(
7659 &buffer,
7660 None::<usize>,
7661 get_code_lens,
7662 cx,
7663 )
7664 })?
7665 .await
7666 .into_iter();
7667
7668 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7669 responses: code_lens_actions
7670 .map(|(server_id, actions)| proto::LspResponse {
7671 server_id: server_id.to_proto(),
7672 response: Some(proto::lsp_response::Response::GetCodeLensResponse(
7673 GetCodeLens::response_to_proto(
7674 actions,
7675 project,
7676 sender_id,
7677 &buffer_version,
7678 cx,
7679 ),
7680 )),
7681 })
7682 .collect(),
7683 })
7684 }
7685 Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(message)) => {
7686 buffer
7687 .update(&mut cx, |buffer, _| {
7688 buffer.wait_for_version(deserialize_version(&message.version))
7689 })?
7690 .await?;
7691 lsp_store
7692 .update(&mut cx, |lsp_store, cx| {
7693 lsp_store.pull_diagnostics_for_buffer(buffer, cx)
7694 })?
7695 .await?;
7696 // `pull_diagnostics_for_buffer` will merge in the new diagnostics and send them to the client.
7697 // The client cannot merge anything into its non-local LspStore, so we do not need to return anything.
7698 Ok(proto::MultiLspQueryResponse {
7699 responses: Vec::new(),
7700 })
7701 }
7702 Some(proto::multi_lsp_query::Request::GetDocumentColor(message)) => {
7703 buffer
7704 .update(&mut cx, |buffer, _| {
7705 buffer.wait_for_version(deserialize_version(&message.version))
7706 })?
7707 .await?;
7708 let get_document_color = GetDocumentColor::from_proto(
7709 message,
7710 lsp_store.clone(),
7711 buffer.clone(),
7712 cx.clone(),
7713 )
7714 .await?;
7715
7716 let all_colors = lsp_store
7717 .update(&mut cx, |project, cx| {
7718 project.request_multiple_lsp_locally(
7719 &buffer,
7720 None::<usize>,
7721 get_document_color,
7722 cx,
7723 )
7724 })?
7725 .await
7726 .into_iter();
7727
7728 lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
7729 responses: all_colors
7730 .map(|(server_id, colors)| proto::LspResponse {
7731 server_id: server_id.to_proto(),
7732 response: Some(
7733 proto::lsp_response::Response::GetDocumentColorResponse(
7734 GetDocumentColor::response_to_proto(
7735 colors,
7736 project,
7737 sender_id,
7738 &buffer_version,
7739 cx,
7740 ),
7741 ),
7742 ),
7743 })
7744 .collect(),
7745 })
7746 }
7747 None => anyhow::bail!("empty multi lsp query request"),
7748 }
7749 }
7750
7751 async fn handle_apply_code_action(
7752 this: Entity<Self>,
7753 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7754 mut cx: AsyncApp,
7755 ) -> Result<proto::ApplyCodeActionResponse> {
7756 let sender_id = envelope.original_sender_id().unwrap_or_default();
7757 let action =
7758 Self::deserialize_code_action(envelope.payload.action.context("invalid action")?)?;
7759 let apply_code_action = this.update(&mut cx, |this, cx| {
7760 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7761 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
7762 anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
7763 })??;
7764
7765 let project_transaction = apply_code_action.await?;
7766 let project_transaction = this.update(&mut cx, |this, cx| {
7767 this.buffer_store.update(cx, |buffer_store, cx| {
7768 buffer_store.serialize_project_transaction_for_peer(
7769 project_transaction,
7770 sender_id,
7771 cx,
7772 )
7773 })
7774 })?;
7775 Ok(proto::ApplyCodeActionResponse {
7776 transaction: Some(project_transaction),
7777 })
7778 }
7779
7780 async fn handle_register_buffer_with_language_servers(
7781 this: Entity<Self>,
7782 envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
7783 mut cx: AsyncApp,
7784 ) -> Result<proto::Ack> {
7785 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7786 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
7787 this.update(&mut cx, |this, cx| {
7788 if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
7789 return upstream_client.send(proto::RegisterBufferWithLanguageServers {
7790 project_id: upstream_project_id,
7791 buffer_id: buffer_id.to_proto(),
7792 });
7793 }
7794
7795 let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
7796 anyhow::bail!("buffer is not open");
7797 };
7798
7799 let handle = this.register_buffer_with_language_servers(&buffer, false, cx);
7800 this.buffer_store().update(cx, |buffer_store, _| {
7801 buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
7802 });
7803
7804 Ok(())
7805 })??;
7806 Ok(proto::Ack {})
7807 }
7808
7809 async fn handle_language_server_id_for_name(
7810 lsp_store: Entity<Self>,
7811 envelope: TypedEnvelope<proto::LanguageServerIdForName>,
7812 mut cx: AsyncApp,
7813 ) -> Result<proto::LanguageServerIdForNameResponse> {
7814 let name = &envelope.payload.name;
7815 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7816 lsp_store
7817 .update(&mut cx, |lsp_store, cx| {
7818 let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
7819 let server_id = buffer.update(cx, |buffer, cx| {
7820 lsp_store
7821 .language_servers_for_local_buffer(buffer, cx)
7822 .find_map(|(adapter, server)| {
7823 if adapter.name.0.as_ref() == name {
7824 Some(server.server_id())
7825 } else {
7826 None
7827 }
7828 })
7829 });
7830 Ok(server_id)
7831 })?
7832 .map(|server_id| proto::LanguageServerIdForNameResponse {
7833 server_id: server_id.map(|id| id.to_proto()),
7834 })
7835 }
7836
7837 async fn handle_rename_project_entry(
7838 this: Entity<Self>,
7839 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7840 mut cx: AsyncApp,
7841 ) -> Result<proto::ProjectEntryResponse> {
7842 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7843 let (worktree_id, worktree, old_path, is_dir) = this
7844 .update(&mut cx, |this, cx| {
7845 this.worktree_store
7846 .read(cx)
7847 .worktree_and_entry_for_id(entry_id, cx)
7848 .map(|(worktree, entry)| {
7849 (
7850 worktree.read(cx).id(),
7851 worktree,
7852 entry.path.clone(),
7853 entry.is_dir(),
7854 )
7855 })
7856 })?
7857 .context("worktree not found")?;
7858 let (old_abs_path, new_abs_path) = {
7859 let root_path = worktree.read_with(&mut cx, |this, _| this.abs_path())?;
7860 let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
7861 (root_path.join(&old_path), root_path.join(&new_path))
7862 };
7863
7864 Self::will_rename_entry(
7865 this.downgrade(),
7866 worktree_id,
7867 &old_abs_path,
7868 &new_abs_path,
7869 is_dir,
7870 cx.clone(),
7871 )
7872 .await;
7873 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
7874 this.read_with(&mut cx, |this, _| {
7875 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
7876 })
7877 .ok();
7878 response
7879 }
7880
7881 async fn handle_update_diagnostic_summary(
7882 this: Entity<Self>,
7883 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7884 mut cx: AsyncApp,
7885 ) -> Result<()> {
7886 this.update(&mut cx, |this, cx| {
7887 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7888 if let Some(message) = envelope.payload.summary {
7889 let project_path = ProjectPath {
7890 worktree_id,
7891 path: Arc::<Path>::from_proto(message.path),
7892 };
7893 let path = project_path.path.clone();
7894 let server_id = LanguageServerId(message.language_server_id as usize);
7895 let summary = DiagnosticSummary {
7896 error_count: message.error_count as usize,
7897 warning_count: message.warning_count as usize,
7898 };
7899
7900 if summary.is_empty() {
7901 if let Some(worktree_summaries) =
7902 this.diagnostic_summaries.get_mut(&worktree_id)
7903 {
7904 if let Some(summaries) = worktree_summaries.get_mut(&path) {
7905 summaries.remove(&server_id);
7906 if summaries.is_empty() {
7907 worktree_summaries.remove(&path);
7908 }
7909 }
7910 }
7911 } else {
7912 this.diagnostic_summaries
7913 .entry(worktree_id)
7914 .or_default()
7915 .entry(path)
7916 .or_default()
7917 .insert(server_id, summary);
7918 }
7919 if let Some((downstream_client, project_id)) = &this.downstream_client {
7920 downstream_client
7921 .send(proto::UpdateDiagnosticSummary {
7922 project_id: *project_id,
7923 worktree_id: worktree_id.to_proto(),
7924 summary: Some(proto::DiagnosticSummary {
7925 path: project_path.path.as_ref().to_proto(),
7926 language_server_id: server_id.0 as u64,
7927 error_count: summary.error_count as u32,
7928 warning_count: summary.warning_count as u32,
7929 }),
7930 })
7931 .log_err();
7932 }
7933 cx.emit(LspStoreEvent::DiagnosticsUpdated {
7934 language_server_id: LanguageServerId(message.language_server_id as usize),
7935 path: project_path,
7936 });
7937 }
7938 Ok(())
7939 })?
7940 }
7941
7942 async fn handle_start_language_server(
7943 this: Entity<Self>,
7944 envelope: TypedEnvelope<proto::StartLanguageServer>,
7945 mut cx: AsyncApp,
7946 ) -> Result<()> {
7947 let server = envelope.payload.server.context("invalid server")?;
7948
7949 this.update(&mut cx, |this, cx| {
7950 let server_id = LanguageServerId(server.id as usize);
7951 this.language_server_statuses.insert(
7952 server_id,
7953 LanguageServerStatus {
7954 name: server.name.clone(),
7955 pending_work: Default::default(),
7956 has_pending_diagnostic_updates: false,
7957 progress_tokens: Default::default(),
7958 },
7959 );
7960 cx.emit(LspStoreEvent::LanguageServerAdded(
7961 server_id,
7962 LanguageServerName(server.name.into()),
7963 server.worktree_id.map(WorktreeId::from_proto),
7964 ));
7965 cx.notify();
7966 })?;
7967 Ok(())
7968 }
7969
7970 async fn handle_update_language_server(
7971 this: Entity<Self>,
7972 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7973 mut cx: AsyncApp,
7974 ) -> Result<()> {
7975 this.update(&mut cx, |this, cx| {
7976 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7977
7978 match envelope.payload.variant.context("invalid variant")? {
7979 proto::update_language_server::Variant::WorkStart(payload) => {
7980 this.on_lsp_work_start(
7981 language_server_id,
7982 payload.token,
7983 LanguageServerProgress {
7984 title: payload.title,
7985 is_disk_based_diagnostics_progress: false,
7986 is_cancellable: payload.is_cancellable.unwrap_or(false),
7987 message: payload.message,
7988 percentage: payload.percentage.map(|p| p as usize),
7989 last_update_at: cx.background_executor().now(),
7990 },
7991 cx,
7992 );
7993 }
7994
7995 proto::update_language_server::Variant::WorkProgress(payload) => {
7996 this.on_lsp_work_progress(
7997 language_server_id,
7998 payload.token,
7999 LanguageServerProgress {
8000 title: None,
8001 is_disk_based_diagnostics_progress: false,
8002 is_cancellable: payload.is_cancellable.unwrap_or(false),
8003 message: payload.message,
8004 percentage: payload.percentage.map(|p| p as usize),
8005 last_update_at: cx.background_executor().now(),
8006 },
8007 cx,
8008 );
8009 }
8010
8011 proto::update_language_server::Variant::WorkEnd(payload) => {
8012 this.on_lsp_work_end(language_server_id, payload.token, cx);
8013 }
8014
8015 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
8016 this.disk_based_diagnostics_started(language_server_id, cx);
8017 }
8018
8019 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
8020 this.disk_based_diagnostics_finished(language_server_id, cx)
8021 }
8022 }
8023
8024 Ok(())
8025 })?
8026 }
8027
8028 async fn handle_language_server_log(
8029 this: Entity<Self>,
8030 envelope: TypedEnvelope<proto::LanguageServerLog>,
8031 mut cx: AsyncApp,
8032 ) -> Result<()> {
8033 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8034 let log_type = envelope
8035 .payload
8036 .log_type
8037 .map(LanguageServerLogType::from_proto)
8038 .context("invalid language server log type")?;
8039
8040 let message = envelope.payload.message;
8041
8042 this.update(&mut cx, |_, cx| {
8043 cx.emit(LspStoreEvent::LanguageServerLog(
8044 language_server_id,
8045 log_type,
8046 message,
8047 ));
8048 })
8049 }
8050
8051 async fn handle_lsp_ext_cancel_flycheck(
8052 lsp_store: Entity<Self>,
8053 envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
8054 mut cx: AsyncApp,
8055 ) -> Result<proto::Ack> {
8056 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8057 lsp_store.read_with(&mut cx, |lsp_store, _| {
8058 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8059 server
8060 .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
8061 .context("handling lsp ext cancel flycheck")
8062 } else {
8063 anyhow::Ok(())
8064 }
8065 })??;
8066
8067 Ok(proto::Ack {})
8068 }
8069
8070 async fn handle_lsp_ext_run_flycheck(
8071 lsp_store: Entity<Self>,
8072 envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
8073 mut cx: AsyncApp,
8074 ) -> Result<proto::Ack> {
8075 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8076 lsp_store.update(&mut cx, |lsp_store, cx| {
8077 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8078 let text_document = if envelope.payload.current_file_only {
8079 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8080 lsp_store
8081 .buffer_store()
8082 .read(cx)
8083 .get(buffer_id)
8084 .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
8085 .map(|path| make_text_document_identifier(&path))
8086 .transpose()?
8087 } else {
8088 None
8089 };
8090 server
8091 .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
8092 &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
8093 )
8094 .context("handling lsp ext run flycheck")
8095 } else {
8096 anyhow::Ok(())
8097 }
8098 })??;
8099
8100 Ok(proto::Ack {})
8101 }
8102
8103 async fn handle_lsp_ext_clear_flycheck(
8104 lsp_store: Entity<Self>,
8105 envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
8106 mut cx: AsyncApp,
8107 ) -> Result<proto::Ack> {
8108 let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8109 lsp_store.read_with(&mut cx, |lsp_store, _| {
8110 if let Some(server) = lsp_store.language_server_for_id(server_id) {
8111 server
8112 .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
8113 .context("handling lsp ext clear flycheck")
8114 } else {
8115 anyhow::Ok(())
8116 }
8117 })??;
8118
8119 Ok(proto::Ack {})
8120 }
8121
8122 pub fn disk_based_diagnostics_started(
8123 &mut self,
8124 language_server_id: LanguageServerId,
8125 cx: &mut Context<Self>,
8126 ) {
8127 if let Some(language_server_status) =
8128 self.language_server_statuses.get_mut(&language_server_id)
8129 {
8130 language_server_status.has_pending_diagnostic_updates = true;
8131 }
8132
8133 cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
8134 cx.emit(LspStoreEvent::LanguageServerUpdate {
8135 language_server_id,
8136 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
8137 Default::default(),
8138 ),
8139 })
8140 }
8141
8142 pub fn disk_based_diagnostics_finished(
8143 &mut self,
8144 language_server_id: LanguageServerId,
8145 cx: &mut Context<Self>,
8146 ) {
8147 if let Some(language_server_status) =
8148 self.language_server_statuses.get_mut(&language_server_id)
8149 {
8150 language_server_status.has_pending_diagnostic_updates = false;
8151 }
8152
8153 cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
8154 cx.emit(LspStoreEvent::LanguageServerUpdate {
8155 language_server_id,
8156 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
8157 Default::default(),
8158 ),
8159 })
8160 }
8161
8162 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
8163 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
8164 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
8165 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
8166 // the language server might take some time to publish diagnostics.
8167 fn simulate_disk_based_diagnostics_events_if_needed(
8168 &mut self,
8169 language_server_id: LanguageServerId,
8170 cx: &mut Context<Self>,
8171 ) {
8172 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
8173
8174 let Some(LanguageServerState::Running {
8175 simulate_disk_based_diagnostics_completion,
8176 adapter,
8177 ..
8178 }) = self
8179 .as_local_mut()
8180 .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
8181 else {
8182 return;
8183 };
8184
8185 if adapter.disk_based_diagnostics_progress_token.is_some() {
8186 return;
8187 }
8188
8189 let prev_task =
8190 simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
8191 cx.background_executor()
8192 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
8193 .await;
8194
8195 this.update(cx, |this, cx| {
8196 this.disk_based_diagnostics_finished(language_server_id, cx);
8197
8198 if let Some(LanguageServerState::Running {
8199 simulate_disk_based_diagnostics_completion,
8200 ..
8201 }) = this.as_local_mut().and_then(|local_store| {
8202 local_store.language_servers.get_mut(&language_server_id)
8203 }) {
8204 *simulate_disk_based_diagnostics_completion = None;
8205 }
8206 })
8207 .ok();
8208 }));
8209
8210 if prev_task.is_none() {
8211 self.disk_based_diagnostics_started(language_server_id, cx);
8212 }
8213 }
8214
8215 pub fn language_server_statuses(
8216 &self,
8217 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
8218 self.language_server_statuses
8219 .iter()
8220 .map(|(key, value)| (*key, value))
8221 }
8222
8223 pub(super) fn did_rename_entry(
8224 &self,
8225 worktree_id: WorktreeId,
8226 old_path: &Path,
8227 new_path: &Path,
8228 is_dir: bool,
8229 ) {
8230 maybe!({
8231 let local_store = self.as_local()?;
8232
8233 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
8234 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
8235
8236 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8237 let Some(filter) = local_store
8238 .language_server_paths_watched_for_rename
8239 .get(&language_server.server_id())
8240 else {
8241 continue;
8242 };
8243
8244 if filter.should_send_did_rename(&old_uri, is_dir) {
8245 language_server
8246 .notify::<DidRenameFiles>(&RenameFilesParams {
8247 files: vec![FileRename {
8248 old_uri: old_uri.clone(),
8249 new_uri: new_uri.clone(),
8250 }],
8251 })
8252 .ok();
8253 }
8254 }
8255 Some(())
8256 });
8257 }
8258
8259 pub(super) fn will_rename_entry(
8260 this: WeakEntity<Self>,
8261 worktree_id: WorktreeId,
8262 old_path: &Path,
8263 new_path: &Path,
8264 is_dir: bool,
8265 cx: AsyncApp,
8266 ) -> Task<()> {
8267 let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
8268 let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
8269 cx.spawn(async move |cx| {
8270 let mut tasks = vec![];
8271 this.update(cx, |this, cx| {
8272 let local_store = this.as_local()?;
8273 let old_uri = old_uri?;
8274 let new_uri = new_uri?;
8275 for language_server in local_store.language_servers_for_worktree(worktree_id) {
8276 let Some(filter) = local_store
8277 .language_server_paths_watched_for_rename
8278 .get(&language_server.server_id())
8279 else {
8280 continue;
8281 };
8282 let Some(adapter) =
8283 this.language_server_adapter_for_id(language_server.server_id())
8284 else {
8285 continue;
8286 };
8287 if filter.should_send_will_rename(&old_uri, is_dir) {
8288 let apply_edit = cx.spawn({
8289 let old_uri = old_uri.clone();
8290 let new_uri = new_uri.clone();
8291 let language_server = language_server.clone();
8292 async move |this, cx| {
8293 let edit = language_server
8294 .request::<WillRenameFiles>(RenameFilesParams {
8295 files: vec![FileRename { old_uri, new_uri }],
8296 })
8297 .await
8298 .into_response()
8299 .context("will rename files")
8300 .log_err()
8301 .flatten()?;
8302
8303 LocalLspStore::deserialize_workspace_edit(
8304 this.upgrade()?,
8305 edit,
8306 false,
8307 adapter.clone(),
8308 language_server.clone(),
8309 cx,
8310 )
8311 .await
8312 .ok();
8313 Some(())
8314 }
8315 });
8316 tasks.push(apply_edit);
8317 }
8318 }
8319 Some(())
8320 })
8321 .ok()
8322 .flatten();
8323 for task in tasks {
8324 // Await on tasks sequentially so that the order of application of edits is deterministic
8325 // (at least with regards to the order of registration of language servers)
8326 task.await;
8327 }
8328 })
8329 }
8330
8331 fn lsp_notify_abs_paths_changed(
8332 &mut self,
8333 server_id: LanguageServerId,
8334 changes: Vec<PathEvent>,
8335 ) {
8336 maybe!({
8337 let server = self.language_server_for_id(server_id)?;
8338 let changes = changes
8339 .into_iter()
8340 .filter_map(|event| {
8341 let typ = match event.kind? {
8342 PathEventKind::Created => lsp::FileChangeType::CREATED,
8343 PathEventKind::Removed => lsp::FileChangeType::DELETED,
8344 PathEventKind::Changed => lsp::FileChangeType::CHANGED,
8345 };
8346 Some(lsp::FileEvent {
8347 uri: file_path_to_lsp_url(&event.path).log_err()?,
8348 typ,
8349 })
8350 })
8351 .collect::<Vec<_>>();
8352 if !changes.is_empty() {
8353 server
8354 .notify::<lsp::notification::DidChangeWatchedFiles>(
8355 &lsp::DidChangeWatchedFilesParams { changes },
8356 )
8357 .ok();
8358 }
8359 Some(())
8360 });
8361 }
8362
8363 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8364 let local_lsp_store = self.as_local()?;
8365 if let Some(LanguageServerState::Running { server, .. }) =
8366 local_lsp_store.language_servers.get(&id)
8367 {
8368 Some(server.clone())
8369 } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
8370 Some(Arc::clone(server))
8371 } else {
8372 None
8373 }
8374 }
8375
8376 fn on_lsp_progress(
8377 &mut self,
8378 progress: lsp::ProgressParams,
8379 language_server_id: LanguageServerId,
8380 disk_based_diagnostics_progress_token: Option<String>,
8381 cx: &mut Context<Self>,
8382 ) {
8383 let token = match progress.token {
8384 lsp::NumberOrString::String(token) => token,
8385 lsp::NumberOrString::Number(token) => {
8386 log::info!("skipping numeric progress token {}", token);
8387 return;
8388 }
8389 };
8390
8391 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
8392 let language_server_status =
8393 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8394 status
8395 } else {
8396 return;
8397 };
8398
8399 if !language_server_status.progress_tokens.contains(&token) {
8400 return;
8401 }
8402
8403 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
8404 .as_ref()
8405 .map_or(false, |disk_based_token| {
8406 token.starts_with(disk_based_token)
8407 });
8408
8409 match progress {
8410 lsp::WorkDoneProgress::Begin(report) => {
8411 if is_disk_based_diagnostics_progress {
8412 self.disk_based_diagnostics_started(language_server_id, cx);
8413 }
8414 self.on_lsp_work_start(
8415 language_server_id,
8416 token.clone(),
8417 LanguageServerProgress {
8418 title: Some(report.title),
8419 is_disk_based_diagnostics_progress,
8420 is_cancellable: report.cancellable.unwrap_or(false),
8421 message: report.message.clone(),
8422 percentage: report.percentage.map(|p| p as usize),
8423 last_update_at: cx.background_executor().now(),
8424 },
8425 cx,
8426 );
8427 }
8428 lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
8429 language_server_id,
8430 token,
8431 LanguageServerProgress {
8432 title: None,
8433 is_disk_based_diagnostics_progress,
8434 is_cancellable: report.cancellable.unwrap_or(false),
8435 message: report.message,
8436 percentage: report.percentage.map(|p| p as usize),
8437 last_update_at: cx.background_executor().now(),
8438 },
8439 cx,
8440 ),
8441 lsp::WorkDoneProgress::End(_) => {
8442 language_server_status.progress_tokens.remove(&token);
8443 self.on_lsp_work_end(language_server_id, token.clone(), cx);
8444 if is_disk_based_diagnostics_progress {
8445 self.disk_based_diagnostics_finished(language_server_id, cx);
8446 }
8447 }
8448 }
8449 }
8450
8451 fn on_lsp_work_start(
8452 &mut self,
8453 language_server_id: LanguageServerId,
8454 token: String,
8455 progress: LanguageServerProgress,
8456 cx: &mut Context<Self>,
8457 ) {
8458 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8459 status.pending_work.insert(token.clone(), progress.clone());
8460 cx.notify();
8461 }
8462 cx.emit(LspStoreEvent::LanguageServerUpdate {
8463 language_server_id,
8464 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
8465 token,
8466 title: progress.title,
8467 message: progress.message,
8468 percentage: progress.percentage.map(|p| p as u32),
8469 is_cancellable: Some(progress.is_cancellable),
8470 }),
8471 })
8472 }
8473
8474 fn on_lsp_work_progress(
8475 &mut self,
8476 language_server_id: LanguageServerId,
8477 token: String,
8478 progress: LanguageServerProgress,
8479 cx: &mut Context<Self>,
8480 ) {
8481 let mut did_update = false;
8482 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8483 match status.pending_work.entry(token.clone()) {
8484 btree_map::Entry::Vacant(entry) => {
8485 entry.insert(progress.clone());
8486 did_update = true;
8487 }
8488 btree_map::Entry::Occupied(mut entry) => {
8489 let entry = entry.get_mut();
8490 if (progress.last_update_at - entry.last_update_at)
8491 >= SERVER_PROGRESS_THROTTLE_TIMEOUT
8492 {
8493 entry.last_update_at = progress.last_update_at;
8494 if progress.message.is_some() {
8495 entry.message = progress.message.clone();
8496 }
8497 if progress.percentage.is_some() {
8498 entry.percentage = progress.percentage;
8499 }
8500 if progress.is_cancellable != entry.is_cancellable {
8501 entry.is_cancellable = progress.is_cancellable;
8502 }
8503 did_update = true;
8504 }
8505 }
8506 }
8507 }
8508
8509 if did_update {
8510 cx.emit(LspStoreEvent::LanguageServerUpdate {
8511 language_server_id,
8512 message: proto::update_language_server::Variant::WorkProgress(
8513 proto::LspWorkProgress {
8514 token,
8515 message: progress.message,
8516 percentage: progress.percentage.map(|p| p as u32),
8517 is_cancellable: Some(progress.is_cancellable),
8518 },
8519 ),
8520 })
8521 }
8522 }
8523
8524 fn on_lsp_work_end(
8525 &mut self,
8526 language_server_id: LanguageServerId,
8527 token: String,
8528 cx: &mut Context<Self>,
8529 ) {
8530 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
8531 if let Some(work) = status.pending_work.remove(&token) {
8532 if !work.is_disk_based_diagnostics_progress {
8533 cx.emit(LspStoreEvent::RefreshInlayHints);
8534 }
8535 }
8536 cx.notify();
8537 }
8538
8539 cx.emit(LspStoreEvent::LanguageServerUpdate {
8540 language_server_id,
8541 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
8542 })
8543 }
8544
8545 pub async fn handle_resolve_completion_documentation(
8546 this: Entity<Self>,
8547 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8548 mut cx: AsyncApp,
8549 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8550 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8551
8552 let completion = this
8553 .read_with(&cx, |this, cx| {
8554 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8555 let server = this
8556 .language_server_for_id(id)
8557 .with_context(|| format!("No language server {id}"))?;
8558
8559 anyhow::Ok(cx.background_spawn(async move {
8560 let can_resolve = server
8561 .capabilities()
8562 .completion_provider
8563 .as_ref()
8564 .and_then(|options| options.resolve_provider)
8565 .unwrap_or(false);
8566 if can_resolve {
8567 server
8568 .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
8569 .await
8570 .into_response()
8571 .context("resolve completion item")
8572 } else {
8573 anyhow::Ok(lsp_completion)
8574 }
8575 }))
8576 })??
8577 .await?;
8578
8579 let mut documentation_is_markdown = false;
8580 let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
8581 let documentation = match completion.documentation {
8582 Some(lsp::Documentation::String(text)) => text,
8583
8584 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8585 documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
8586 value
8587 }
8588
8589 _ => String::new(),
8590 };
8591
8592 // If we have a new buffer_id, that means we're talking to a new client
8593 // and want to check for new text_edits in the completion too.
8594 let mut old_replace_start = None;
8595 let mut old_replace_end = None;
8596 let mut old_insert_start = None;
8597 let mut old_insert_end = None;
8598 let mut new_text = String::default();
8599 if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
8600 let buffer_snapshot = this.update(&mut cx, |this, cx| {
8601 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8602 anyhow::Ok(buffer.read(cx).snapshot())
8603 })??;
8604
8605 if let Some(text_edit) = completion.text_edit.as_ref() {
8606 let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
8607
8608 if let Some(mut edit) = edit {
8609 LineEnding::normalize(&mut edit.new_text);
8610
8611 new_text = edit.new_text;
8612 old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
8613 old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
8614 if let Some(insert_range) = edit.insert_range {
8615 old_insert_start = Some(serialize_anchor(&insert_range.start));
8616 old_insert_end = Some(serialize_anchor(&insert_range.end));
8617 }
8618 }
8619 }
8620 }
8621
8622 Ok(proto::ResolveCompletionDocumentationResponse {
8623 documentation,
8624 documentation_is_markdown,
8625 old_replace_start,
8626 old_replace_end,
8627 new_text,
8628 lsp_completion,
8629 old_insert_start,
8630 old_insert_end,
8631 })
8632 }
8633
8634 async fn handle_on_type_formatting(
8635 this: Entity<Self>,
8636 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8637 mut cx: AsyncApp,
8638 ) -> Result<proto::OnTypeFormattingResponse> {
8639 let on_type_formatting = this.update(&mut cx, |this, cx| {
8640 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8641 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8642 let position = envelope
8643 .payload
8644 .position
8645 .and_then(deserialize_anchor)
8646 .context("invalid position")?;
8647 anyhow::Ok(this.apply_on_type_formatting(
8648 buffer,
8649 position,
8650 envelope.payload.trigger.clone(),
8651 cx,
8652 ))
8653 })??;
8654
8655 let transaction = on_type_formatting
8656 .await?
8657 .as_ref()
8658 .map(language::proto::serialize_transaction);
8659 Ok(proto::OnTypeFormattingResponse { transaction })
8660 }
8661
8662 async fn handle_refresh_inlay_hints(
8663 this: Entity<Self>,
8664 _: TypedEnvelope<proto::RefreshInlayHints>,
8665 mut cx: AsyncApp,
8666 ) -> Result<proto::Ack> {
8667 this.update(&mut cx, |_, cx| {
8668 cx.emit(LspStoreEvent::RefreshInlayHints);
8669 })?;
8670 Ok(proto::Ack {})
8671 }
8672
8673 async fn handle_pull_workspace_diagnostics(
8674 lsp_store: Entity<Self>,
8675 envelope: TypedEnvelope<proto::PullWorkspaceDiagnostics>,
8676 mut cx: AsyncApp,
8677 ) -> Result<proto::Ack> {
8678 let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
8679 lsp_store.update(&mut cx, |lsp_store, _| {
8680 lsp_store.pull_workspace_diagnostics(server_id);
8681 })?;
8682 Ok(proto::Ack {})
8683 }
8684
8685 async fn handle_inlay_hints(
8686 this: Entity<Self>,
8687 envelope: TypedEnvelope<proto::InlayHints>,
8688 mut cx: AsyncApp,
8689 ) -> Result<proto::InlayHintsResponse> {
8690 let sender_id = envelope.original_sender_id().unwrap_or_default();
8691 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8692 let buffer = this.update(&mut cx, |this, cx| {
8693 this.buffer_store.read(cx).get_existing(buffer_id)
8694 })??;
8695 buffer
8696 .update(&mut cx, |buffer, _| {
8697 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8698 })?
8699 .await
8700 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8701
8702 let start = envelope
8703 .payload
8704 .start
8705 .and_then(deserialize_anchor)
8706 .context("missing range start")?;
8707 let end = envelope
8708 .payload
8709 .end
8710 .and_then(deserialize_anchor)
8711 .context("missing range end")?;
8712 let buffer_hints = this
8713 .update(&mut cx, |lsp_store, cx| {
8714 lsp_store.inlay_hints(buffer.clone(), start..end, cx)
8715 })?
8716 .await
8717 .context("inlay hints fetch")?;
8718
8719 this.update(&mut cx, |project, cx| {
8720 InlayHints::response_to_proto(
8721 buffer_hints,
8722 project,
8723 sender_id,
8724 &buffer.read(cx).version(),
8725 cx,
8726 )
8727 })
8728 }
8729
8730 async fn handle_get_color_presentation(
8731 lsp_store: Entity<Self>,
8732 envelope: TypedEnvelope<proto::GetColorPresentation>,
8733 mut cx: AsyncApp,
8734 ) -> Result<proto::GetColorPresentationResponse> {
8735 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8736 let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
8737 lsp_store.buffer_store.read(cx).get_existing(buffer_id)
8738 })??;
8739
8740 let color = envelope
8741 .payload
8742 .color
8743 .context("invalid color resolve request")?;
8744 let start = color
8745 .lsp_range_start
8746 .context("invalid color resolve request")?;
8747 let end = color
8748 .lsp_range_end
8749 .context("invalid color resolve request")?;
8750
8751 let color = DocumentColor {
8752 lsp_range: lsp::Range {
8753 start: point_to_lsp(PointUtf16::new(start.row, start.column)),
8754 end: point_to_lsp(PointUtf16::new(end.row, end.column)),
8755 },
8756 color: lsp::Color {
8757 red: color.red,
8758 green: color.green,
8759 blue: color.blue,
8760 alpha: color.alpha,
8761 },
8762 resolved: false,
8763 color_presentations: Vec::new(),
8764 };
8765 let resolved_color = lsp_store
8766 .update(&mut cx, |lsp_store, cx| {
8767 lsp_store.resolve_color_presentation(
8768 color,
8769 buffer.clone(),
8770 LanguageServerId(envelope.payload.server_id as usize),
8771 cx,
8772 )
8773 })?
8774 .await
8775 .context("resolving color presentation")?;
8776
8777 Ok(proto::GetColorPresentationResponse {
8778 presentations: resolved_color
8779 .color_presentations
8780 .into_iter()
8781 .map(|presentation| proto::ColorPresentation {
8782 label: presentation.label,
8783 text_edit: presentation.text_edit.map(serialize_lsp_edit),
8784 additional_text_edits: presentation
8785 .additional_text_edits
8786 .into_iter()
8787 .map(serialize_lsp_edit)
8788 .collect(),
8789 })
8790 .collect(),
8791 })
8792 }
8793
8794 async fn handle_resolve_inlay_hint(
8795 this: Entity<Self>,
8796 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8797 mut cx: AsyncApp,
8798 ) -> Result<proto::ResolveInlayHintResponse> {
8799 let proto_hint = envelope
8800 .payload
8801 .hint
8802 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8803 let hint = InlayHints::proto_to_project_hint(proto_hint)
8804 .context("resolved proto inlay hint conversion")?;
8805 let buffer = this.update(&mut cx, |this, cx| {
8806 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8807 this.buffer_store.read(cx).get_existing(buffer_id)
8808 })??;
8809 let response_hint = this
8810 .update(&mut cx, |this, cx| {
8811 this.resolve_inlay_hint(
8812 hint,
8813 buffer,
8814 LanguageServerId(envelope.payload.language_server_id as usize),
8815 cx,
8816 )
8817 })?
8818 .await
8819 .context("inlay hints fetch")?;
8820 Ok(proto::ResolveInlayHintResponse {
8821 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8822 })
8823 }
8824
8825 async fn handle_refresh_code_lens(
8826 this: Entity<Self>,
8827 _: TypedEnvelope<proto::RefreshCodeLens>,
8828 mut cx: AsyncApp,
8829 ) -> Result<proto::Ack> {
8830 this.update(&mut cx, |_, cx| {
8831 cx.emit(LspStoreEvent::RefreshCodeLens);
8832 })?;
8833 Ok(proto::Ack {})
8834 }
8835
8836 async fn handle_open_buffer_for_symbol(
8837 this: Entity<Self>,
8838 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8839 mut cx: AsyncApp,
8840 ) -> Result<proto::OpenBufferForSymbolResponse> {
8841 let peer_id = envelope.original_sender_id().unwrap_or_default();
8842 let symbol = envelope.payload.symbol.context("invalid symbol")?;
8843 let symbol = Self::deserialize_symbol(symbol)?;
8844 let symbol = this.read_with(&mut cx, |this, _| {
8845 let signature = this.symbol_signature(&symbol.path);
8846 anyhow::ensure!(signature == symbol.signature, "invalid symbol signature");
8847 Ok(symbol)
8848 })??;
8849 let buffer = this
8850 .update(&mut cx, |this, cx| {
8851 this.open_buffer_for_symbol(
8852 &Symbol {
8853 language_server_name: symbol.language_server_name,
8854 source_worktree_id: symbol.source_worktree_id,
8855 source_language_server_id: symbol.source_language_server_id,
8856 path: symbol.path,
8857 name: symbol.name,
8858 kind: symbol.kind,
8859 range: symbol.range,
8860 signature: symbol.signature,
8861 label: CodeLabel {
8862 text: Default::default(),
8863 runs: Default::default(),
8864 filter_range: Default::default(),
8865 },
8866 },
8867 cx,
8868 )
8869 })?
8870 .await?;
8871
8872 this.update(&mut cx, |this, cx| {
8873 let is_private = buffer
8874 .read(cx)
8875 .file()
8876 .map(|f| f.is_private())
8877 .unwrap_or_default();
8878 if is_private {
8879 Err(anyhow!(rpc::ErrorCode::UnsharedItem))
8880 } else {
8881 this.buffer_store
8882 .update(cx, |buffer_store, cx| {
8883 buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
8884 })
8885 .detach_and_log_err(cx);
8886 let buffer_id = buffer.read(cx).remote_id().to_proto();
8887 Ok(proto::OpenBufferForSymbolResponse { buffer_id })
8888 }
8889 })?
8890 }
8891
8892 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8893 let mut hasher = Sha256::new();
8894 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8895 hasher.update(project_path.path.to_string_lossy().as_bytes());
8896 hasher.update(self.nonce.to_be_bytes());
8897 hasher.finalize().as_slice().try_into().unwrap()
8898 }
8899
8900 pub async fn handle_get_project_symbols(
8901 this: Entity<Self>,
8902 envelope: TypedEnvelope<proto::GetProjectSymbols>,
8903 mut cx: AsyncApp,
8904 ) -> Result<proto::GetProjectSymbolsResponse> {
8905 let symbols = this
8906 .update(&mut cx, |this, cx| {
8907 this.symbols(&envelope.payload.query, cx)
8908 })?
8909 .await?;
8910
8911 Ok(proto::GetProjectSymbolsResponse {
8912 symbols: symbols.iter().map(Self::serialize_symbol).collect(),
8913 })
8914 }
8915
8916 pub async fn handle_restart_language_servers(
8917 this: Entity<Self>,
8918 envelope: TypedEnvelope<proto::RestartLanguageServers>,
8919 mut cx: AsyncApp,
8920 ) -> Result<proto::Ack> {
8921 this.update(&mut cx, |this, cx| {
8922 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
8923 this.restart_language_servers_for_buffers(buffers, cx);
8924 })?;
8925
8926 Ok(proto::Ack {})
8927 }
8928
8929 pub async fn handle_stop_language_servers(
8930 this: Entity<Self>,
8931 envelope: TypedEnvelope<proto::StopLanguageServers>,
8932 mut cx: AsyncApp,
8933 ) -> Result<proto::Ack> {
8934 this.update(&mut cx, |this, cx| {
8935 let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
8936 this.stop_language_servers_for_buffers(buffers, cx);
8937 })?;
8938
8939 Ok(proto::Ack {})
8940 }
8941
8942 pub async fn handle_cancel_language_server_work(
8943 this: Entity<Self>,
8944 envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
8945 mut cx: AsyncApp,
8946 ) -> Result<proto::Ack> {
8947 this.update(&mut cx, |this, cx| {
8948 if let Some(work) = envelope.payload.work {
8949 match work {
8950 proto::cancel_language_server_work::Work::Buffers(buffers) => {
8951 let buffers =
8952 this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
8953 this.cancel_language_server_work_for_buffers(buffers, cx);
8954 }
8955 proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
8956 let server_id = LanguageServerId::from_proto(work.language_server_id);
8957 this.cancel_language_server_work(server_id, work.token, cx);
8958 }
8959 }
8960 }
8961 })?;
8962
8963 Ok(proto::Ack {})
8964 }
8965
8966 fn buffer_ids_to_buffers(
8967 &mut self,
8968 buffer_ids: impl Iterator<Item = u64>,
8969 cx: &mut Context<Self>,
8970 ) -> Vec<Entity<Buffer>> {
8971 buffer_ids
8972 .into_iter()
8973 .flat_map(|buffer_id| {
8974 self.buffer_store
8975 .read(cx)
8976 .get(BufferId::new(buffer_id).log_err()?)
8977 })
8978 .collect::<Vec<_>>()
8979 }
8980
8981 async fn handle_apply_additional_edits_for_completion(
8982 this: Entity<Self>,
8983 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8984 mut cx: AsyncApp,
8985 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8986 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8987 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8988 let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
8989 let completion = Self::deserialize_completion(
8990 envelope.payload.completion.context("invalid completion")?,
8991 )?;
8992 anyhow::Ok((buffer, completion))
8993 })??;
8994
8995 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8996 this.apply_additional_edits_for_completion(
8997 buffer,
8998 Rc::new(RefCell::new(Box::new([Completion {
8999 replace_range: completion.replace_range,
9000 new_text: completion.new_text,
9001 source: completion.source,
9002 documentation: None,
9003 label: CodeLabel {
9004 text: Default::default(),
9005 runs: Default::default(),
9006 filter_range: Default::default(),
9007 },
9008 insert_text_mode: None,
9009 icon_path: None,
9010 confirm: None,
9011 }]))),
9012 0,
9013 false,
9014 cx,
9015 )
9016 })?;
9017
9018 Ok(proto::ApplyCompletionAdditionalEditsResponse {
9019 transaction: apply_additional_edits
9020 .await?
9021 .as_ref()
9022 .map(language::proto::serialize_transaction),
9023 })
9024 }
9025
9026 pub fn last_formatting_failure(&self) -> Option<&str> {
9027 self.last_formatting_failure.as_deref()
9028 }
9029
9030 pub fn reset_last_formatting_failure(&mut self) {
9031 self.last_formatting_failure = None;
9032 }
9033
9034 pub fn environment_for_buffer(
9035 &self,
9036 buffer: &Entity<Buffer>,
9037 cx: &mut Context<Self>,
9038 ) -> Shared<Task<Option<HashMap<String, String>>>> {
9039 if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
9040 environment.update(cx, |env, cx| {
9041 env.get_buffer_environment(&buffer, &self.worktree_store, cx)
9042 })
9043 } else {
9044 Task::ready(None).shared()
9045 }
9046 }
9047
9048 pub fn format(
9049 &mut self,
9050 buffers: HashSet<Entity<Buffer>>,
9051 target: LspFormatTarget,
9052 push_to_history: bool,
9053 trigger: FormatTrigger,
9054 cx: &mut Context<Self>,
9055 ) -> Task<anyhow::Result<ProjectTransaction>> {
9056 let logger = zlog::scoped!("format");
9057 if let Some(_) = self.as_local() {
9058 zlog::trace!(logger => "Formatting locally");
9059 let logger = zlog::scoped!(logger => "local");
9060 let buffers = buffers
9061 .into_iter()
9062 .map(|buffer_handle| {
9063 let buffer = buffer_handle.read(cx);
9064 let buffer_abs_path = File::from_dyn(buffer.file())
9065 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
9066
9067 (buffer_handle, buffer_abs_path, buffer.remote_id())
9068 })
9069 .collect::<Vec<_>>();
9070
9071 cx.spawn(async move |lsp_store, cx| {
9072 let mut formattable_buffers = Vec::with_capacity(buffers.len());
9073
9074 for (handle, abs_path, id) in buffers {
9075 let env = lsp_store
9076 .update(cx, |lsp_store, cx| {
9077 lsp_store.environment_for_buffer(&handle, cx)
9078 })?
9079 .await;
9080
9081 let ranges = match &target {
9082 LspFormatTarget::Buffers => None,
9083 LspFormatTarget::Ranges(ranges) => {
9084 Some(ranges.get(&id).context("No format ranges provided for buffer")?.clone())
9085 }
9086 };
9087
9088 formattable_buffers.push(FormattableBuffer {
9089 handle,
9090 abs_path,
9091 env,
9092 ranges,
9093 });
9094 }
9095 zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
9096
9097 let format_timer = zlog::time!(logger => "Formatting buffers");
9098 let result = LocalLspStore::format_locally(
9099 lsp_store.clone(),
9100 formattable_buffers,
9101 push_to_history,
9102 trigger,
9103 logger,
9104 cx,
9105 )
9106 .await;
9107 format_timer.end();
9108
9109 zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
9110
9111 lsp_store.update(cx, |lsp_store, _| {
9112 lsp_store.update_last_formatting_failure(&result);
9113 })?;
9114
9115 result
9116 })
9117 } else if let Some((client, project_id)) = self.upstream_client() {
9118 zlog::trace!(logger => "Formatting remotely");
9119 let logger = zlog::scoped!(logger => "remote");
9120 // Don't support formatting ranges via remote
9121 match target {
9122 LspFormatTarget::Buffers => {}
9123 LspFormatTarget::Ranges(_) => {
9124 zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
9125 return Task::ready(Ok(ProjectTransaction::default()));
9126 }
9127 }
9128
9129 let buffer_store = self.buffer_store();
9130 cx.spawn(async move |lsp_store, cx| {
9131 zlog::trace!(logger => "Sending remote format request");
9132 let request_timer = zlog::time!(logger => "remote format request");
9133 let result = client
9134 .request(proto::FormatBuffers {
9135 project_id,
9136 trigger: trigger as i32,
9137 buffer_ids: buffers
9138 .iter()
9139 .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id().into()))
9140 .collect::<Result<_>>()?,
9141 })
9142 .await
9143 .and_then(|result| result.transaction.context("missing transaction"));
9144 request_timer.end();
9145
9146 zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
9147
9148 lsp_store.update(cx, |lsp_store, _| {
9149 lsp_store.update_last_formatting_failure(&result);
9150 })?;
9151
9152 let transaction_response = result?;
9153 let _timer = zlog::time!(logger => "deserializing project transaction");
9154 buffer_store
9155 .update(cx, |buffer_store, cx| {
9156 buffer_store.deserialize_project_transaction(
9157 transaction_response,
9158 push_to_history,
9159 cx,
9160 )
9161 })?
9162 .await
9163 })
9164 } else {
9165 zlog::trace!(logger => "Not formatting");
9166 Task::ready(Ok(ProjectTransaction::default()))
9167 }
9168 }
9169
9170 async fn handle_format_buffers(
9171 this: Entity<Self>,
9172 envelope: TypedEnvelope<proto::FormatBuffers>,
9173 mut cx: AsyncApp,
9174 ) -> Result<proto::FormatBuffersResponse> {
9175 let sender_id = envelope.original_sender_id().unwrap_or_default();
9176 let format = this.update(&mut cx, |this, cx| {
9177 let mut buffers = HashSet::default();
9178 for buffer_id in &envelope.payload.buffer_ids {
9179 let buffer_id = BufferId::new(*buffer_id)?;
9180 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9181 }
9182 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
9183 anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
9184 })??;
9185
9186 let project_transaction = format.await?;
9187 let project_transaction = this.update(&mut cx, |this, cx| {
9188 this.buffer_store.update(cx, |buffer_store, cx| {
9189 buffer_store.serialize_project_transaction_for_peer(
9190 project_transaction,
9191 sender_id,
9192 cx,
9193 )
9194 })
9195 })?;
9196 Ok(proto::FormatBuffersResponse {
9197 transaction: Some(project_transaction),
9198 })
9199 }
9200
9201 async fn handle_apply_code_action_kind(
9202 this: Entity<Self>,
9203 envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
9204 mut cx: AsyncApp,
9205 ) -> Result<proto::ApplyCodeActionKindResponse> {
9206 let sender_id = envelope.original_sender_id().unwrap_or_default();
9207 let format = this.update(&mut cx, |this, cx| {
9208 let mut buffers = HashSet::default();
9209 for buffer_id in &envelope.payload.buffer_ids {
9210 let buffer_id = BufferId::new(*buffer_id)?;
9211 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
9212 }
9213 let kind = match envelope.payload.kind.as_str() {
9214 "" => CodeActionKind::EMPTY,
9215 "quickfix" => CodeActionKind::QUICKFIX,
9216 "refactor" => CodeActionKind::REFACTOR,
9217 "refactor.extract" => CodeActionKind::REFACTOR_EXTRACT,
9218 "refactor.inline" => CodeActionKind::REFACTOR_INLINE,
9219 "refactor.rewrite" => CodeActionKind::REFACTOR_REWRITE,
9220 "source" => CodeActionKind::SOURCE,
9221 "source.organizeImports" => CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
9222 "source.fixAll" => CodeActionKind::SOURCE_FIX_ALL,
9223 _ => anyhow::bail!(
9224 "Invalid code action kind {}",
9225 envelope.payload.kind.as_str()
9226 ),
9227 };
9228 anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
9229 })??;
9230
9231 let project_transaction = format.await?;
9232 let project_transaction = this.update(&mut cx, |this, cx| {
9233 this.buffer_store.update(cx, |buffer_store, cx| {
9234 buffer_store.serialize_project_transaction_for_peer(
9235 project_transaction,
9236 sender_id,
9237 cx,
9238 )
9239 })
9240 })?;
9241 Ok(proto::ApplyCodeActionKindResponse {
9242 transaction: Some(project_transaction),
9243 })
9244 }
9245
9246 async fn shutdown_language_server(
9247 server_state: Option<LanguageServerState>,
9248 name: LanguageServerName,
9249 cx: &mut AsyncApp,
9250 ) {
9251 let server = match server_state {
9252 Some(LanguageServerState::Starting { startup, .. }) => {
9253 let mut timer = cx
9254 .background_executor()
9255 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
9256 .fuse();
9257
9258 select! {
9259 server = startup.fuse() => server,
9260 _ = timer => {
9261 log::info!(
9262 "timeout waiting for language server {} to finish launching before stopping",
9263 name
9264 );
9265 None
9266 },
9267 }
9268 }
9269
9270 Some(LanguageServerState::Running { server, .. }) => Some(server),
9271
9272 None => None,
9273 };
9274
9275 if let Some(server) = server {
9276 if let Some(shutdown) = server.shutdown() {
9277 shutdown.await;
9278 }
9279 }
9280 }
9281
9282 // Returns a list of all of the worktrees which no longer have a language server and the root path
9283 // for the stopped server
9284 fn stop_local_language_server(
9285 &mut self,
9286 server_id: LanguageServerId,
9287 name: LanguageServerName,
9288 cx: &mut Context<Self>,
9289 ) -> Task<Vec<WorktreeId>> {
9290 let local = match &mut self.mode {
9291 LspStoreMode::Local(local) => local,
9292 _ => {
9293 return Task::ready(Vec::new());
9294 }
9295 };
9296
9297 let mut orphaned_worktrees = vec![];
9298 // Remove this server ID from all entries in the given worktree.
9299 local.language_server_ids.retain(|(worktree, _), ids| {
9300 if !ids.remove(&server_id) {
9301 return true;
9302 }
9303
9304 if ids.is_empty() {
9305 orphaned_worktrees.push(*worktree);
9306 false
9307 } else {
9308 true
9309 }
9310 });
9311 let _ = self.language_server_statuses.remove(&server_id);
9312 log::info!("stopping language server {name}");
9313 self.buffer_store.update(cx, |buffer_store, cx| {
9314 for buffer in buffer_store.buffers() {
9315 buffer.update(cx, |buffer, cx| {
9316 buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
9317 buffer.set_completion_triggers(server_id, Default::default(), cx);
9318 });
9319 }
9320 });
9321
9322 for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
9323 summaries.retain(|path, summaries_by_server_id| {
9324 if summaries_by_server_id.remove(&server_id).is_some() {
9325 if let Some((client, project_id)) = self.downstream_client.clone() {
9326 client
9327 .send(proto::UpdateDiagnosticSummary {
9328 project_id,
9329 worktree_id: worktree_id.to_proto(),
9330 summary: Some(proto::DiagnosticSummary {
9331 path: path.as_ref().to_proto(),
9332 language_server_id: server_id.0 as u64,
9333 error_count: 0,
9334 warning_count: 0,
9335 }),
9336 })
9337 .log_err();
9338 }
9339 !summaries_by_server_id.is_empty()
9340 } else {
9341 true
9342 }
9343 });
9344 }
9345
9346 let local = self.as_local_mut().unwrap();
9347 for diagnostics in local.diagnostics.values_mut() {
9348 diagnostics.retain(|_, diagnostics_by_server_id| {
9349 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
9350 diagnostics_by_server_id.remove(ix);
9351 !diagnostics_by_server_id.is_empty()
9352 } else {
9353 true
9354 }
9355 });
9356 }
9357 local.language_server_watched_paths.remove(&server_id);
9358 let server_state = local.language_servers.remove(&server_id);
9359 cx.notify();
9360 self.cleanup_lsp_data(server_id);
9361 cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
9362 cx.spawn(async move |_, cx| {
9363 Self::shutdown_language_server(server_state, name, cx).await;
9364 orphaned_worktrees
9365 })
9366 }
9367
9368 pub fn restart_language_servers_for_buffers(
9369 &mut self,
9370 buffers: Vec<Entity<Buffer>>,
9371 cx: &mut Context<Self>,
9372 ) {
9373 if let Some((client, project_id)) = self.upstream_client() {
9374 let request = client.request(proto::RestartLanguageServers {
9375 project_id,
9376 buffer_ids: buffers
9377 .into_iter()
9378 .map(|b| b.read(cx).remote_id().to_proto())
9379 .collect(),
9380 });
9381 cx.background_spawn(request).detach_and_log_err(cx);
9382 } else {
9383 let stop_task = self.stop_local_language_servers_for_buffers(&buffers, cx);
9384 cx.spawn(async move |this, cx| {
9385 stop_task.await;
9386 this.update(cx, |this, cx| {
9387 for buffer in buffers {
9388 this.register_buffer_with_language_servers(&buffer, true, cx);
9389 }
9390 })
9391 .ok()
9392 })
9393 .detach();
9394 }
9395 }
9396
9397 pub fn stop_language_servers_for_buffers(
9398 &mut self,
9399 buffers: Vec<Entity<Buffer>>,
9400 cx: &mut Context<Self>,
9401 ) {
9402 if let Some((client, project_id)) = self.upstream_client() {
9403 let request = client.request(proto::StopLanguageServers {
9404 project_id,
9405 buffer_ids: buffers
9406 .into_iter()
9407 .map(|b| b.read(cx).remote_id().to_proto())
9408 .collect(),
9409 });
9410 cx.background_spawn(request).detach_and_log_err(cx);
9411 } else {
9412 self.stop_local_language_servers_for_buffers(&buffers, cx)
9413 .detach();
9414 }
9415 }
9416
9417 fn stop_local_language_servers_for_buffers(
9418 &mut self,
9419 buffers: &[Entity<Buffer>],
9420 cx: &mut Context<Self>,
9421 ) -> Task<()> {
9422 let Some(local) = self.as_local_mut() else {
9423 return Task::ready(());
9424 };
9425 let language_servers_to_stop = buffers
9426 .iter()
9427 .flat_map(|buffer| {
9428 buffer.update(cx, |buffer, cx| {
9429 local.language_server_ids_for_buffer(buffer, cx)
9430 })
9431 })
9432 .collect::<BTreeSet<_>>();
9433 local.lsp_tree.update(cx, |this, _| {
9434 this.remove_nodes(&language_servers_to_stop);
9435 });
9436 let tasks = language_servers_to_stop
9437 .into_iter()
9438 .map(|server| {
9439 let name = self
9440 .language_server_statuses
9441 .get(&server)
9442 .map(|state| state.name.as_str().into())
9443 .unwrap_or_else(|| LanguageServerName::from("Unknown"));
9444 self.stop_local_language_server(server, name, cx)
9445 })
9446 .collect::<Vec<_>>();
9447
9448 cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
9449 }
9450
9451 fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
9452 let (worktree, relative_path) =
9453 self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
9454
9455 let project_path = ProjectPath {
9456 worktree_id: worktree.read(cx).id(),
9457 path: relative_path.into(),
9458 };
9459
9460 Some(
9461 self.buffer_store()
9462 .read(cx)
9463 .get_by_path(&project_path, cx)?
9464 .read(cx),
9465 )
9466 }
9467
9468 pub fn update_diagnostics(
9469 &mut self,
9470 language_server_id: LanguageServerId,
9471 params: lsp::PublishDiagnosticsParams,
9472 result_id: Option<String>,
9473 source_kind: DiagnosticSourceKind,
9474 disk_based_sources: &[String],
9475 cx: &mut Context<Self>,
9476 ) -> Result<()> {
9477 self.merge_diagnostics(
9478 language_server_id,
9479 params,
9480 result_id,
9481 source_kind,
9482 disk_based_sources,
9483 |_, _, _| false,
9484 cx,
9485 )
9486 }
9487
9488 pub fn merge_diagnostics(
9489 &mut self,
9490 language_server_id: LanguageServerId,
9491 mut params: lsp::PublishDiagnosticsParams,
9492 result_id: Option<String>,
9493 source_kind: DiagnosticSourceKind,
9494 disk_based_sources: &[String],
9495 filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
9496 cx: &mut Context<Self>,
9497 ) -> Result<()> {
9498 anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
9499 let abs_path = params
9500 .uri
9501 .to_file_path()
9502 .map_err(|()| anyhow!("URI is not a file"))?;
9503 let mut diagnostics = Vec::default();
9504 let mut primary_diagnostic_group_ids = HashMap::default();
9505 let mut sources_by_group_id = HashMap::default();
9506 let mut supporting_diagnostics = HashMap::default();
9507
9508 let adapter = self.language_server_adapter_for_id(language_server_id);
9509
9510 // Ensure that primary diagnostics are always the most severe
9511 params.diagnostics.sort_by_key(|item| item.severity);
9512
9513 for diagnostic in ¶ms.diagnostics {
9514 let source = diagnostic.source.as_ref();
9515 let range = range_from_lsp(diagnostic.range);
9516 let is_supporting = diagnostic
9517 .related_information
9518 .as_ref()
9519 .map_or(false, |infos| {
9520 infos.iter().any(|info| {
9521 primary_diagnostic_group_ids.contains_key(&(
9522 source,
9523 diagnostic.code.clone(),
9524 range_from_lsp(info.location.range),
9525 ))
9526 })
9527 });
9528
9529 let is_unnecessary = diagnostic
9530 .tags
9531 .as_ref()
9532 .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
9533
9534 let underline = self
9535 .language_server_adapter_for_id(language_server_id)
9536 .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
9537
9538 if is_supporting {
9539 supporting_diagnostics.insert(
9540 (source, diagnostic.code.clone(), range),
9541 (diagnostic.severity, is_unnecessary),
9542 );
9543 } else {
9544 let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
9545 let is_disk_based =
9546 source.map_or(false, |source| disk_based_sources.contains(source));
9547
9548 sources_by_group_id.insert(group_id, source);
9549 primary_diagnostic_group_ids
9550 .insert((source, diagnostic.code.clone(), range.clone()), group_id);
9551
9552 diagnostics.push(DiagnosticEntry {
9553 range,
9554 diagnostic: Diagnostic {
9555 source: diagnostic.source.clone(),
9556 source_kind,
9557 code: diagnostic.code.clone(),
9558 code_description: diagnostic
9559 .code_description
9560 .as_ref()
9561 .map(|d| d.href.clone()),
9562 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
9563 markdown: adapter.as_ref().and_then(|adapter| {
9564 adapter.diagnostic_message_to_markdown(&diagnostic.message)
9565 }),
9566 message: diagnostic.message.trim().to_string(),
9567 group_id,
9568 is_primary: true,
9569 is_disk_based,
9570 is_unnecessary,
9571 underline,
9572 data: diagnostic.data.clone(),
9573 },
9574 });
9575 if let Some(infos) = &diagnostic.related_information {
9576 for info in infos {
9577 if info.location.uri == params.uri && !info.message.is_empty() {
9578 let range = range_from_lsp(info.location.range);
9579 diagnostics.push(DiagnosticEntry {
9580 range,
9581 diagnostic: Diagnostic {
9582 source: diagnostic.source.clone(),
9583 source_kind,
9584 code: diagnostic.code.clone(),
9585 code_description: diagnostic
9586 .code_description
9587 .as_ref()
9588 .map(|c| c.href.clone()),
9589 severity: DiagnosticSeverity::INFORMATION,
9590 markdown: adapter.as_ref().and_then(|adapter| {
9591 adapter.diagnostic_message_to_markdown(&info.message)
9592 }),
9593 message: info.message.trim().to_string(),
9594 group_id,
9595 is_primary: false,
9596 is_disk_based,
9597 is_unnecessary: false,
9598 underline,
9599 data: diagnostic.data.clone(),
9600 },
9601 });
9602 }
9603 }
9604 }
9605 }
9606 }
9607
9608 for entry in &mut diagnostics {
9609 let diagnostic = &mut entry.diagnostic;
9610 if !diagnostic.is_primary {
9611 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
9612 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
9613 source,
9614 diagnostic.code.clone(),
9615 entry.range.clone(),
9616 )) {
9617 if let Some(severity) = severity {
9618 diagnostic.severity = severity;
9619 }
9620 diagnostic.is_unnecessary = is_unnecessary;
9621 }
9622 }
9623 }
9624
9625 self.merge_diagnostic_entries(
9626 language_server_id,
9627 abs_path,
9628 result_id,
9629 params.version,
9630 diagnostics,
9631 filter,
9632 cx,
9633 )?;
9634 Ok(())
9635 }
9636
9637 fn insert_newly_running_language_server(
9638 &mut self,
9639 adapter: Arc<CachedLspAdapter>,
9640 language_server: Arc<LanguageServer>,
9641 server_id: LanguageServerId,
9642 key: (WorktreeId, LanguageServerName),
9643 workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
9644 cx: &mut Context<Self>,
9645 ) {
9646 let Some(local) = self.as_local_mut() else {
9647 return;
9648 };
9649 // If the language server for this key doesn't match the server id, don't store the
9650 // server. Which will cause it to be dropped, killing the process
9651 if local
9652 .language_server_ids
9653 .get(&key)
9654 .map(|ids| !ids.contains(&server_id))
9655 .unwrap_or(false)
9656 {
9657 return;
9658 }
9659
9660 // Update language_servers collection with Running variant of LanguageServerState
9661 // indicating that the server is up and running and ready
9662 let workspace_folders = workspace_folders.lock().clone();
9663 language_server.set_workspace_folders(workspace_folders);
9664
9665 local.language_servers.insert(
9666 server_id,
9667 LanguageServerState::Running {
9668 workspace_refresh_task: lsp_workspace_diagnostics_refresh(
9669 language_server.clone(),
9670 cx,
9671 ),
9672 adapter: adapter.clone(),
9673 server: language_server.clone(),
9674 simulate_disk_based_diagnostics_completion: None,
9675 },
9676 );
9677 if let Some(file_ops_caps) = language_server
9678 .capabilities()
9679 .workspace
9680 .as_ref()
9681 .and_then(|ws| ws.file_operations.as_ref())
9682 {
9683 let did_rename_caps = file_ops_caps.did_rename.as_ref();
9684 let will_rename_caps = file_ops_caps.will_rename.as_ref();
9685 if did_rename_caps.or(will_rename_caps).is_some() {
9686 let watcher = RenamePathsWatchedForServer::default()
9687 .with_did_rename_patterns(did_rename_caps)
9688 .with_will_rename_patterns(will_rename_caps);
9689 local
9690 .language_server_paths_watched_for_rename
9691 .insert(server_id, watcher);
9692 }
9693 }
9694
9695 self.language_server_statuses.insert(
9696 server_id,
9697 LanguageServerStatus {
9698 name: language_server.name().to_string(),
9699 pending_work: Default::default(),
9700 has_pending_diagnostic_updates: false,
9701 progress_tokens: Default::default(),
9702 },
9703 );
9704
9705 cx.emit(LspStoreEvent::LanguageServerAdded(
9706 server_id,
9707 language_server.name(),
9708 Some(key.0),
9709 ));
9710 cx.emit(LspStoreEvent::RefreshInlayHints);
9711
9712 if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
9713 downstream_client
9714 .send(proto::StartLanguageServer {
9715 project_id: *project_id,
9716 server: Some(proto::LanguageServer {
9717 id: server_id.0 as u64,
9718 name: language_server.name().to_string(),
9719 worktree_id: Some(key.0.to_proto()),
9720 }),
9721 })
9722 .log_err();
9723 }
9724
9725 // Tell the language server about every open buffer in the worktree that matches the language.
9726 self.buffer_store.clone().update(cx, |buffer_store, cx| {
9727 for buffer_handle in buffer_store.buffers() {
9728 let buffer = buffer_handle.read(cx);
9729 let file = match File::from_dyn(buffer.file()) {
9730 Some(file) => file,
9731 None => continue,
9732 };
9733 let language = match buffer.language() {
9734 Some(language) => language,
9735 None => continue,
9736 };
9737
9738 if file.worktree.read(cx).id() != key.0
9739 || !self
9740 .languages
9741 .lsp_adapters(&language.name())
9742 .iter()
9743 .any(|a| a.name == key.1)
9744 {
9745 continue;
9746 }
9747 // didOpen
9748 let file = match file.as_local() {
9749 Some(file) => file,
9750 None => continue,
9751 };
9752
9753 let local = self.as_local_mut().unwrap();
9754
9755 if local.registered_buffers.contains_key(&buffer.remote_id()) {
9756 let versions = local
9757 .buffer_snapshots
9758 .entry(buffer.remote_id())
9759 .or_default()
9760 .entry(server_id)
9761 .and_modify(|_| {
9762 assert!(
9763 false,
9764 "There should not be an existing snapshot for a newly inserted buffer"
9765 )
9766 })
9767 .or_insert_with(|| {
9768 vec![LspBufferSnapshot {
9769 version: 0,
9770 snapshot: buffer.text_snapshot(),
9771 }]
9772 });
9773
9774 let snapshot = versions.last().unwrap();
9775 let version = snapshot.version;
9776 let initial_snapshot = &snapshot.snapshot;
9777 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
9778 language_server.register_buffer(
9779 uri,
9780 adapter.language_id(&language.name()),
9781 version,
9782 initial_snapshot.text(),
9783 );
9784 }
9785 buffer_handle.update(cx, |buffer, cx| {
9786 buffer.set_completion_triggers(
9787 server_id,
9788 language_server
9789 .capabilities()
9790 .completion_provider
9791 .as_ref()
9792 .and_then(|provider| {
9793 provider
9794 .trigger_characters
9795 .as_ref()
9796 .map(|characters| characters.iter().cloned().collect())
9797 })
9798 .unwrap_or_default(),
9799 cx,
9800 )
9801 });
9802 }
9803 });
9804
9805 cx.notify();
9806 }
9807
9808 pub fn language_servers_running_disk_based_diagnostics(
9809 &self,
9810 ) -> impl Iterator<Item = LanguageServerId> + '_ {
9811 self.language_server_statuses
9812 .iter()
9813 .filter_map(|(id, status)| {
9814 if status.has_pending_diagnostic_updates {
9815 Some(*id)
9816 } else {
9817 None
9818 }
9819 })
9820 }
9821
9822 pub(crate) fn cancel_language_server_work_for_buffers(
9823 &mut self,
9824 buffers: impl IntoIterator<Item = Entity<Buffer>>,
9825 cx: &mut Context<Self>,
9826 ) {
9827 if let Some((client, project_id)) = self.upstream_client() {
9828 let request = client.request(proto::CancelLanguageServerWork {
9829 project_id,
9830 work: Some(proto::cancel_language_server_work::Work::Buffers(
9831 proto::cancel_language_server_work::Buffers {
9832 buffer_ids: buffers
9833 .into_iter()
9834 .map(|b| b.read(cx).remote_id().to_proto())
9835 .collect(),
9836 },
9837 )),
9838 });
9839 cx.background_spawn(request).detach_and_log_err(cx);
9840 } else if let Some(local) = self.as_local() {
9841 let servers = buffers
9842 .into_iter()
9843 .flat_map(|buffer| {
9844 buffer.update(cx, |buffer, cx| {
9845 local.language_server_ids_for_buffer(buffer, cx).into_iter()
9846 })
9847 })
9848 .collect::<HashSet<_>>();
9849 for server_id in servers {
9850 self.cancel_language_server_work(server_id, None, cx);
9851 }
9852 }
9853 }
9854
9855 pub(crate) fn cancel_language_server_work(
9856 &mut self,
9857 server_id: LanguageServerId,
9858 token_to_cancel: Option<String>,
9859 cx: &mut Context<Self>,
9860 ) {
9861 if let Some(local) = self.as_local() {
9862 let status = self.language_server_statuses.get(&server_id);
9863 let server = local.language_servers.get(&server_id);
9864 if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
9865 {
9866 for (token, progress) in &status.pending_work {
9867 if let Some(token_to_cancel) = token_to_cancel.as_ref() {
9868 if token != token_to_cancel {
9869 continue;
9870 }
9871 }
9872 if progress.is_cancellable {
9873 server
9874 .notify::<lsp::notification::WorkDoneProgressCancel>(
9875 &WorkDoneProgressCancelParams {
9876 token: lsp::NumberOrString::String(token.clone()),
9877 },
9878 )
9879 .ok();
9880 }
9881 }
9882 }
9883 } else if let Some((client, project_id)) = self.upstream_client() {
9884 let request = client.request(proto::CancelLanguageServerWork {
9885 project_id,
9886 work: Some(
9887 proto::cancel_language_server_work::Work::LanguageServerWork(
9888 proto::cancel_language_server_work::LanguageServerWork {
9889 language_server_id: server_id.to_proto(),
9890 token: token_to_cancel,
9891 },
9892 ),
9893 ),
9894 });
9895 cx.background_spawn(request).detach_and_log_err(cx);
9896 }
9897 }
9898
9899 fn register_supplementary_language_server(
9900 &mut self,
9901 id: LanguageServerId,
9902 name: LanguageServerName,
9903 server: Arc<LanguageServer>,
9904 cx: &mut Context<Self>,
9905 ) {
9906 if let Some(local) = self.as_local_mut() {
9907 local
9908 .supplementary_language_servers
9909 .insert(id, (name.clone(), server));
9910 cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
9911 }
9912 }
9913
9914 fn unregister_supplementary_language_server(
9915 &mut self,
9916 id: LanguageServerId,
9917 cx: &mut Context<Self>,
9918 ) {
9919 if let Some(local) = self.as_local_mut() {
9920 local.supplementary_language_servers.remove(&id);
9921 cx.emit(LspStoreEvent::LanguageServerRemoved(id));
9922 }
9923 }
9924
9925 pub(crate) fn supplementary_language_servers(
9926 &self,
9927 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
9928 self.as_local().into_iter().flat_map(|local| {
9929 local
9930 .supplementary_language_servers
9931 .iter()
9932 .map(|(id, (name, _))| (*id, name.clone()))
9933 })
9934 }
9935
9936 pub fn language_server_adapter_for_id(
9937 &self,
9938 id: LanguageServerId,
9939 ) -> Option<Arc<CachedLspAdapter>> {
9940 self.as_local()
9941 .and_then(|local| local.language_servers.get(&id))
9942 .and_then(|language_server_state| match language_server_state {
9943 LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
9944 _ => None,
9945 })
9946 }
9947
9948 pub(super) fn update_local_worktree_language_servers(
9949 &mut self,
9950 worktree_handle: &Entity<Worktree>,
9951 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
9952 cx: &mut Context<Self>,
9953 ) {
9954 if changes.is_empty() {
9955 return;
9956 }
9957
9958 let Some(local) = self.as_local() else { return };
9959
9960 local.prettier_store.update(cx, |prettier_store, cx| {
9961 prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
9962 });
9963
9964 let worktree_id = worktree_handle.read(cx).id();
9965 let mut language_server_ids = local
9966 .language_server_ids
9967 .iter()
9968 .flat_map(|((server_worktree, _), server_ids)| {
9969 server_ids
9970 .iter()
9971 .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
9972 })
9973 .collect::<Vec<_>>();
9974 language_server_ids.sort();
9975 language_server_ids.dedup();
9976
9977 let abs_path = worktree_handle.read(cx).abs_path();
9978 for server_id in &language_server_ids {
9979 if let Some(LanguageServerState::Running { server, .. }) =
9980 local.language_servers.get(server_id)
9981 {
9982 if let Some(watched_paths) = local
9983 .language_server_watched_paths
9984 .get(server_id)
9985 .and_then(|paths| paths.worktree_paths.get(&worktree_id))
9986 {
9987 let params = lsp::DidChangeWatchedFilesParams {
9988 changes: changes
9989 .iter()
9990 .filter_map(|(path, _, change)| {
9991 if !watched_paths.is_match(path) {
9992 return None;
9993 }
9994 let typ = match change {
9995 PathChange::Loaded => return None,
9996 PathChange::Added => lsp::FileChangeType::CREATED,
9997 PathChange::Removed => lsp::FileChangeType::DELETED,
9998 PathChange::Updated => lsp::FileChangeType::CHANGED,
9999 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
10000 };
10001 Some(lsp::FileEvent {
10002 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
10003 typ,
10004 })
10005 })
10006 .collect(),
10007 };
10008 if !params.changes.is_empty() {
10009 server
10010 .notify::<lsp::notification::DidChangeWatchedFiles>(¶ms)
10011 .ok();
10012 }
10013 }
10014 }
10015 }
10016 }
10017
10018 pub fn wait_for_remote_buffer(
10019 &mut self,
10020 id: BufferId,
10021 cx: &mut Context<Self>,
10022 ) -> Task<Result<Entity<Buffer>>> {
10023 self.buffer_store.update(cx, |buffer_store, cx| {
10024 buffer_store.wait_for_remote_buffer(id, cx)
10025 })
10026 }
10027
10028 fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10029 proto::Symbol {
10030 language_server_name: symbol.language_server_name.0.to_string(),
10031 source_worktree_id: symbol.source_worktree_id.to_proto(),
10032 language_server_id: symbol.source_language_server_id.to_proto(),
10033 worktree_id: symbol.path.worktree_id.to_proto(),
10034 path: symbol.path.path.as_ref().to_proto(),
10035 name: symbol.name.clone(),
10036 kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
10037 start: Some(proto::PointUtf16 {
10038 row: symbol.range.start.0.row,
10039 column: symbol.range.start.0.column,
10040 }),
10041 end: Some(proto::PointUtf16 {
10042 row: symbol.range.end.0.row,
10043 column: symbol.range.end.0.column,
10044 }),
10045 signature: symbol.signature.to_vec(),
10046 }
10047 }
10048
10049 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
10050 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
10051 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
10052 let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
10053 let path = ProjectPath {
10054 worktree_id,
10055 path: Arc::<Path>::from_proto(serialized_symbol.path),
10056 };
10057
10058 let start = serialized_symbol.start.context("invalid start")?;
10059 let end = serialized_symbol.end.context("invalid end")?;
10060 Ok(CoreSymbol {
10061 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
10062 source_worktree_id,
10063 source_language_server_id: LanguageServerId::from_proto(
10064 serialized_symbol.language_server_id,
10065 ),
10066 path,
10067 name: serialized_symbol.name,
10068 range: Unclipped(PointUtf16::new(start.row, start.column))
10069 ..Unclipped(PointUtf16::new(end.row, end.column)),
10070 kind,
10071 signature: serialized_symbol
10072 .signature
10073 .try_into()
10074 .map_err(|_| anyhow!("invalid signature"))?,
10075 })
10076 }
10077
10078 pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10079 let mut serialized_completion = proto::Completion {
10080 old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
10081 old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
10082 new_text: completion.new_text.clone(),
10083 ..proto::Completion::default()
10084 };
10085 match &completion.source {
10086 CompletionSource::Lsp {
10087 insert_range,
10088 server_id,
10089 lsp_completion,
10090 lsp_defaults,
10091 resolved,
10092 } => {
10093 let (old_insert_start, old_insert_end) = insert_range
10094 .as_ref()
10095 .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
10096 .unzip();
10097
10098 serialized_completion.old_insert_start = old_insert_start;
10099 serialized_completion.old_insert_end = old_insert_end;
10100 serialized_completion.source = proto::completion::Source::Lsp as i32;
10101 serialized_completion.server_id = server_id.0 as u64;
10102 serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
10103 serialized_completion.lsp_defaults = lsp_defaults
10104 .as_deref()
10105 .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
10106 serialized_completion.resolved = *resolved;
10107 }
10108 CompletionSource::BufferWord {
10109 word_range,
10110 resolved,
10111 } => {
10112 serialized_completion.source = proto::completion::Source::BufferWord as i32;
10113 serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
10114 serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
10115 serialized_completion.resolved = *resolved;
10116 }
10117 CompletionSource::Custom => {
10118 serialized_completion.source = proto::completion::Source::Custom as i32;
10119 serialized_completion.resolved = true;
10120 }
10121 }
10122
10123 serialized_completion
10124 }
10125
10126 pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10127 let old_replace_start = completion
10128 .old_replace_start
10129 .and_then(deserialize_anchor)
10130 .context("invalid old start")?;
10131 let old_replace_end = completion
10132 .old_replace_end
10133 .and_then(deserialize_anchor)
10134 .context("invalid old end")?;
10135 let insert_range = {
10136 match completion.old_insert_start.zip(completion.old_insert_end) {
10137 Some((start, end)) => {
10138 let start = deserialize_anchor(start).context("invalid insert old start")?;
10139 let end = deserialize_anchor(end).context("invalid insert old end")?;
10140 Some(start..end)
10141 }
10142 None => None,
10143 }
10144 };
10145 Ok(CoreCompletion {
10146 replace_range: old_replace_start..old_replace_end,
10147 new_text: completion.new_text,
10148 source: match proto::completion::Source::from_i32(completion.source) {
10149 Some(proto::completion::Source::Custom) => CompletionSource::Custom,
10150 Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
10151 insert_range,
10152 server_id: LanguageServerId::from_proto(completion.server_id),
10153 lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
10154 lsp_defaults: completion
10155 .lsp_defaults
10156 .as_deref()
10157 .map(serde_json::from_slice)
10158 .transpose()?,
10159 resolved: completion.resolved,
10160 },
10161 Some(proto::completion::Source::BufferWord) => {
10162 let word_range = completion
10163 .buffer_word_start
10164 .and_then(deserialize_anchor)
10165 .context("invalid buffer word start")?
10166 ..completion
10167 .buffer_word_end
10168 .and_then(deserialize_anchor)
10169 .context("invalid buffer word end")?;
10170 CompletionSource::BufferWord {
10171 word_range,
10172 resolved: completion.resolved,
10173 }
10174 }
10175 _ => anyhow::bail!("Unexpected completion source {}", completion.source),
10176 },
10177 })
10178 }
10179
10180 pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10181 let (kind, lsp_action) = match &action.lsp_action {
10182 LspAction::Action(code_action) => (
10183 proto::code_action::Kind::Action as i32,
10184 serde_json::to_vec(code_action).unwrap(),
10185 ),
10186 LspAction::Command(command) => (
10187 proto::code_action::Kind::Command as i32,
10188 serde_json::to_vec(command).unwrap(),
10189 ),
10190 LspAction::CodeLens(code_lens) => (
10191 proto::code_action::Kind::CodeLens as i32,
10192 serde_json::to_vec(code_lens).unwrap(),
10193 ),
10194 };
10195
10196 proto::CodeAction {
10197 server_id: action.server_id.0 as u64,
10198 start: Some(serialize_anchor(&action.range.start)),
10199 end: Some(serialize_anchor(&action.range.end)),
10200 lsp_action,
10201 kind,
10202 resolved: action.resolved,
10203 }
10204 }
10205
10206 pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10207 let start = action
10208 .start
10209 .and_then(deserialize_anchor)
10210 .context("invalid start")?;
10211 let end = action
10212 .end
10213 .and_then(deserialize_anchor)
10214 .context("invalid end")?;
10215 let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
10216 Some(proto::code_action::Kind::Action) => {
10217 LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
10218 }
10219 Some(proto::code_action::Kind::Command) => {
10220 LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
10221 }
10222 Some(proto::code_action::Kind::CodeLens) => {
10223 LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
10224 }
10225 None => anyhow::bail!("Unknown action kind {}", action.kind),
10226 };
10227 Ok(CodeAction {
10228 server_id: LanguageServerId(action.server_id as usize),
10229 range: start..end,
10230 resolved: action.resolved,
10231 lsp_action,
10232 })
10233 }
10234
10235 fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
10236 match &formatting_result {
10237 Ok(_) => self.last_formatting_failure = None,
10238 Err(error) => {
10239 let error_string = format!("{error:#}");
10240 log::error!("Formatting failed: {error_string}");
10241 self.last_formatting_failure
10242 .replace(error_string.lines().join(" "));
10243 }
10244 }
10245 }
10246
10247 fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
10248 if let Some(lsp_data) = &mut self.lsp_data {
10249 lsp_data.buffer_lsp_data.remove(&for_server);
10250 }
10251 if let Some(local) = self.as_local_mut() {
10252 local.buffer_pull_diagnostics_result_ids.remove(&for_server);
10253 }
10254 }
10255
10256 pub fn result_id(
10257 &self,
10258 server_id: LanguageServerId,
10259 buffer_id: BufferId,
10260 cx: &App,
10261 ) -> Option<String> {
10262 let abs_path = self
10263 .buffer_store
10264 .read(cx)
10265 .get(buffer_id)
10266 .and_then(|b| File::from_dyn(b.read(cx).file()))
10267 .map(|f| f.abs_path(cx))?;
10268 self.as_local()?
10269 .buffer_pull_diagnostics_result_ids
10270 .get(&server_id)?
10271 .get(&abs_path)?
10272 .clone()
10273 }
10274
10275 pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
10276 let Some(local) = self.as_local() else {
10277 return HashMap::default();
10278 };
10279 local
10280 .buffer_pull_diagnostics_result_ids
10281 .get(&server_id)
10282 .into_iter()
10283 .flatten()
10284 .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
10285 .collect()
10286 }
10287
10288 pub fn pull_workspace_diagnostics(&mut self, server_id: LanguageServerId) {
10289 if let Some(LanguageServerState::Running {
10290 workspace_refresh_task: Some((tx, _)),
10291 ..
10292 }) = self
10293 .as_local_mut()
10294 .and_then(|local| local.language_servers.get_mut(&server_id))
10295 {
10296 tx.try_send(()).ok();
10297 }
10298 }
10299
10300 pub fn pull_workspace_diagnostics_for_buffer(&mut self, buffer_id: BufferId, cx: &mut App) {
10301 let Some(buffer) = self.buffer_store().read(cx).get_existing(buffer_id).ok() else {
10302 return;
10303 };
10304 let Some(local) = self.as_local_mut() else {
10305 return;
10306 };
10307
10308 for server_id in buffer.update(cx, |buffer, cx| {
10309 local.language_server_ids_for_buffer(buffer, cx)
10310 }) {
10311 if let Some(LanguageServerState::Running {
10312 workspace_refresh_task: Some((tx, _)),
10313 ..
10314 }) = local.language_servers.get_mut(&server_id)
10315 {
10316 tx.try_send(()).ok();
10317 }
10318 }
10319 }
10320}
10321
10322async fn fetch_document_colors(
10323 lsp_store: WeakEntity<LspStore>,
10324 buffer: Entity<Buffer>,
10325 task_abs_path: PathBuf,
10326 cx: &mut AsyncApp,
10327) -> anyhow::Result<HashSet<DocumentColor>> {
10328 cx.background_executor()
10329 .timer(Duration::from_millis(50))
10330 .await;
10331 let Some(buffer_mtime) = buffer.update(cx, |buffer, _| buffer.saved_mtime())? else {
10332 return Ok(HashSet::default());
10333 };
10334 let fetched_colors = lsp_store
10335 .update(cx, |lsp_store, cx| {
10336 lsp_store.fetch_document_colors_for_buffer(buffer, cx)
10337 })?
10338 .await
10339 .with_context(|| {
10340 format!("Fetching document colors for buffer with path {task_abs_path:?}")
10341 })?;
10342
10343 lsp_store.update(cx, |lsp_store, _| {
10344 let lsp_data = lsp_store.lsp_data.as_mut().with_context(|| {
10345 format!(
10346 "Document lsp data got updated between fetch and update for path {task_abs_path:?}"
10347 )
10348 })?;
10349 let mut lsp_colors = HashSet::default();
10350 anyhow::ensure!(
10351 lsp_data.mtime == buffer_mtime,
10352 "Buffer lsp data got updated between fetch and update for path {task_abs_path:?}"
10353 );
10354 for (server_id, colors) in fetched_colors {
10355 let colors_lsp_data = &mut lsp_data
10356 .buffer_lsp_data
10357 .entry(server_id)
10358 .or_default()
10359 .entry(task_abs_path.clone())
10360 .or_default()
10361 .colors;
10362 *colors_lsp_data = Some(colors.clone());
10363 lsp_colors.extend(colors);
10364 }
10365 Ok(lsp_colors)
10366 })?
10367}
10368
10369fn lsp_workspace_diagnostics_refresh(
10370 server: Arc<LanguageServer>,
10371 cx: &mut Context<'_, LspStore>,
10372) -> Option<(mpsc::Sender<()>, Task<()>)> {
10373 let identifier = match server.capabilities().diagnostic_provider? {
10374 lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {
10375 if !diagnostic_options.workspace_diagnostics {
10376 return None;
10377 }
10378 diagnostic_options.identifier
10379 }
10380 lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {
10381 let diagnostic_options = registration_options.diagnostic_options;
10382 if !diagnostic_options.workspace_diagnostics {
10383 return None;
10384 }
10385 diagnostic_options.identifier
10386 }
10387 };
10388
10389 let (mut tx, mut rx) = mpsc::channel(1);
10390 tx.try_send(()).ok();
10391
10392 let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {
10393 let mut attempts = 0;
10394 let max_attempts = 50;
10395
10396 loop {
10397 let Some(()) = rx.recv().await else {
10398 return;
10399 };
10400
10401 'request: loop {
10402 if attempts > max_attempts {
10403 log::error!(
10404 "Failed to pull workspace diagnostics {max_attempts} times, aborting"
10405 );
10406 return;
10407 }
10408 let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);
10409 cx.background_executor()
10410 .timer(Duration::from_millis(backoff_millis))
10411 .await;
10412 attempts += 1;
10413
10414 let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
10415 lsp_store
10416 .all_result_ids(server.server_id())
10417 .into_iter()
10418 .filter_map(|(abs_path, result_id)| {
10419 let uri = file_path_to_lsp_url(&abs_path).ok()?;
10420 Some(lsp::PreviousResultId {
10421 uri,
10422 value: result_id,
10423 })
10424 })
10425 .collect()
10426 }) else {
10427 return;
10428 };
10429
10430 let response_result = server
10431 .request::<lsp::WorkspaceDiagnosticRequest>(lsp::WorkspaceDiagnosticParams {
10432 previous_result_ids,
10433 identifier: identifier.clone(),
10434 work_done_progress_params: Default::default(),
10435 partial_result_params: Default::default(),
10436 })
10437 .await;
10438 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh
10439 // > If a server closes a workspace diagnostic pull request the client should re-trigger the request.
10440 match response_result {
10441 ConnectionResult::Timeout => {
10442 log::error!("Timeout during workspace diagnostics pull");
10443 continue 'request;
10444 }
10445 ConnectionResult::ConnectionReset => {
10446 log::error!("Server closed a workspace diagnostics pull request");
10447 continue 'request;
10448 }
10449 ConnectionResult::Result(Err(e)) => {
10450 log::error!("Error during workspace diagnostics pull: {e:#}");
10451 break 'request;
10452 }
10453 ConnectionResult::Result(Ok(pulled_diagnostics)) => {
10454 attempts = 0;
10455 if lsp_store
10456 .update(cx, |lsp_store, cx| {
10457 let workspace_diagnostics =
10458 GetDocumentDiagnostics::deserialize_workspace_diagnostics_report(pulled_diagnostics, server.server_id());
10459 for workspace_diagnostics in workspace_diagnostics {
10460 let LspPullDiagnostics::Response {
10461 server_id,
10462 uri,
10463 diagnostics,
10464 } = workspace_diagnostics.diagnostics
10465 else {
10466 continue;
10467 };
10468
10469 let adapter = lsp_store.language_server_adapter_for_id(server_id);
10470 let disk_based_sources = adapter
10471 .as_ref()
10472 .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
10473 .unwrap_or(&[]);
10474
10475 match diagnostics {
10476 PulledDiagnostics::Unchanged { result_id } => {
10477 lsp_store
10478 .merge_diagnostics(
10479 server_id,
10480 lsp::PublishDiagnosticsParams {
10481 uri: uri.clone(),
10482 diagnostics: Vec::new(),
10483 version: None,
10484 },
10485 Some(result_id),
10486 DiagnosticSourceKind::Pulled,
10487 disk_based_sources,
10488 |_, _, _| true,
10489 cx,
10490 )
10491 .log_err();
10492 }
10493 PulledDiagnostics::Changed {
10494 diagnostics,
10495 result_id,
10496 } => {
10497 lsp_store
10498 .merge_diagnostics(
10499 server_id,
10500 lsp::PublishDiagnosticsParams {
10501 uri: uri.clone(),
10502 diagnostics,
10503 version: workspace_diagnostics.version,
10504 },
10505 result_id,
10506 DiagnosticSourceKind::Pulled,
10507 disk_based_sources,
10508 |buffer, old_diagnostic, cx| match old_diagnostic.source_kind {
10509 DiagnosticSourceKind::Pulled => {
10510 let buffer_url = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx))
10511 .and_then(|abs_path| file_path_to_lsp_url(&abs_path).ok());
10512 buffer_url.is_none_or(|buffer_url| buffer_url != uri)
10513 },
10514 DiagnosticSourceKind::Other
10515 | DiagnosticSourceKind::Pushed => true,
10516 },
10517 cx,
10518 )
10519 .log_err();
10520 }
10521 }
10522 }
10523 })
10524 .is_err()
10525 {
10526 return;
10527 }
10528 break 'request;
10529 }
10530 }
10531 }
10532 }
10533 });
10534
10535 Some((tx, workspace_query_language_server))
10536}
10537
10538fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
10539 let CompletionSource::BufferWord {
10540 word_range,
10541 resolved,
10542 } = &mut completion.source
10543 else {
10544 return;
10545 };
10546 if *resolved {
10547 return;
10548 }
10549
10550 if completion.new_text
10551 != snapshot
10552 .text_for_range(word_range.clone())
10553 .collect::<String>()
10554 {
10555 return;
10556 }
10557
10558 let mut offset = 0;
10559 for chunk in snapshot.chunks(word_range.clone(), true) {
10560 let end_offset = offset + chunk.text.len();
10561 if let Some(highlight_id) = chunk.syntax_highlight_id {
10562 completion
10563 .label
10564 .runs
10565 .push((offset..end_offset, highlight_id));
10566 }
10567 offset = end_offset;
10568 }
10569 *resolved = true;
10570}
10571
10572impl EventEmitter<LspStoreEvent> for LspStore {}
10573
10574fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10575 hover
10576 .contents
10577 .retain(|hover_block| !hover_block.text.trim().is_empty());
10578 if hover.contents.is_empty() {
10579 None
10580 } else {
10581 Some(hover)
10582 }
10583}
10584
10585async fn populate_labels_for_completions(
10586 new_completions: Vec<CoreCompletion>,
10587 language: Option<Arc<Language>>,
10588 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10589) -> Vec<Completion> {
10590 let lsp_completions = new_completions
10591 .iter()
10592 .filter_map(|new_completion| {
10593 if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
10594 Some(lsp_completion.into_owned())
10595 } else {
10596 None
10597 }
10598 })
10599 .collect::<Vec<_>>();
10600
10601 let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10602 lsp_adapter
10603 .labels_for_completions(&lsp_completions, language)
10604 .await
10605 .log_err()
10606 .unwrap_or_default()
10607 } else {
10608 Vec::new()
10609 }
10610 .into_iter()
10611 .fuse();
10612
10613 let mut completions = Vec::new();
10614 for completion in new_completions {
10615 match completion.source.lsp_completion(true) {
10616 Some(lsp_completion) => {
10617 let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
10618 Some(docs.into())
10619 } else {
10620 None
10621 };
10622
10623 let mut label = labels.next().flatten().unwrap_or_else(|| {
10624 CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
10625 });
10626 ensure_uniform_list_compatible_label(&mut label);
10627 completions.push(Completion {
10628 label,
10629 documentation,
10630 replace_range: completion.replace_range,
10631 new_text: completion.new_text,
10632 insert_text_mode: lsp_completion.insert_text_mode,
10633 source: completion.source,
10634 icon_path: None,
10635 confirm: None,
10636 });
10637 }
10638 None => {
10639 let mut label = CodeLabel::plain(completion.new_text.clone(), None);
10640 ensure_uniform_list_compatible_label(&mut label);
10641 completions.push(Completion {
10642 label,
10643 documentation: None,
10644 replace_range: completion.replace_range,
10645 new_text: completion.new_text,
10646 source: completion.source,
10647 insert_text_mode: None,
10648 icon_path: None,
10649 confirm: None,
10650 });
10651 }
10652 }
10653 }
10654 completions
10655}
10656
10657#[derive(Debug)]
10658pub enum LanguageServerToQuery {
10659 /// Query language servers in order of users preference, up until one capable of handling the request is found.
10660 FirstCapable,
10661 /// Query a specific language server.
10662 Other(LanguageServerId),
10663}
10664
10665#[derive(Default)]
10666struct RenamePathsWatchedForServer {
10667 did_rename: Vec<RenameActionPredicate>,
10668 will_rename: Vec<RenameActionPredicate>,
10669}
10670
10671impl RenamePathsWatchedForServer {
10672 fn with_did_rename_patterns(
10673 mut self,
10674 did_rename: Option<&FileOperationRegistrationOptions>,
10675 ) -> Self {
10676 if let Some(did_rename) = did_rename {
10677 self.did_rename = did_rename
10678 .filters
10679 .iter()
10680 .filter_map(|filter| filter.try_into().log_err())
10681 .collect();
10682 }
10683 self
10684 }
10685 fn with_will_rename_patterns(
10686 mut self,
10687 will_rename: Option<&FileOperationRegistrationOptions>,
10688 ) -> Self {
10689 if let Some(will_rename) = will_rename {
10690 self.will_rename = will_rename
10691 .filters
10692 .iter()
10693 .filter_map(|filter| filter.try_into().log_err())
10694 .collect();
10695 }
10696 self
10697 }
10698
10699 fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
10700 self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
10701 }
10702 fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
10703 self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
10704 }
10705}
10706
10707impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
10708 type Error = globset::Error;
10709 fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
10710 Ok(Self {
10711 kind: ops.pattern.matches.clone(),
10712 glob: GlobBuilder::new(&ops.pattern.glob)
10713 .case_insensitive(
10714 ops.pattern
10715 .options
10716 .as_ref()
10717 .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
10718 )
10719 .build()?
10720 .compile_matcher(),
10721 })
10722 }
10723}
10724struct RenameActionPredicate {
10725 glob: GlobMatcher,
10726 kind: Option<FileOperationPatternKind>,
10727}
10728
10729impl RenameActionPredicate {
10730 // Returns true if language server should be notified
10731 fn eval(&self, path: &str, is_dir: bool) -> bool {
10732 self.kind.as_ref().map_or(true, |kind| {
10733 let expected_kind = if is_dir {
10734 FileOperationPatternKind::Folder
10735 } else {
10736 FileOperationPatternKind::File
10737 };
10738 kind == &expected_kind
10739 }) && self.glob.is_match(path)
10740 }
10741}
10742
10743#[derive(Default)]
10744struct LanguageServerWatchedPaths {
10745 worktree_paths: HashMap<WorktreeId, GlobSet>,
10746 abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
10747}
10748
10749#[derive(Default)]
10750struct LanguageServerWatchedPathsBuilder {
10751 worktree_paths: HashMap<WorktreeId, GlobSet>,
10752 abs_paths: HashMap<Arc<Path>, GlobSet>,
10753}
10754
10755impl LanguageServerWatchedPathsBuilder {
10756 fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
10757 self.worktree_paths.insert(worktree_id, glob_set);
10758 }
10759 fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
10760 self.abs_paths.insert(path, glob_set);
10761 }
10762 fn build(
10763 self,
10764 fs: Arc<dyn Fs>,
10765 language_server_id: LanguageServerId,
10766 cx: &mut Context<LspStore>,
10767 ) -> LanguageServerWatchedPaths {
10768 let project = cx.weak_entity();
10769
10770 const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
10771 let abs_paths = self
10772 .abs_paths
10773 .into_iter()
10774 .map(|(abs_path, globset)| {
10775 let task = cx.spawn({
10776 let abs_path = abs_path.clone();
10777 let fs = fs.clone();
10778
10779 let lsp_store = project.clone();
10780 async move |_, cx| {
10781 maybe!(async move {
10782 let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
10783 while let Some(update) = push_updates.0.next().await {
10784 let action = lsp_store
10785 .update(cx, |this, _| {
10786 let Some(local) = this.as_local() else {
10787 return ControlFlow::Break(());
10788 };
10789 let Some(watcher) = local
10790 .language_server_watched_paths
10791 .get(&language_server_id)
10792 else {
10793 return ControlFlow::Break(());
10794 };
10795 let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
10796 "Watched abs path is not registered with a watcher",
10797 );
10798 let matching_entries = update
10799 .into_iter()
10800 .filter(|event| globs.is_match(&event.path))
10801 .collect::<Vec<_>>();
10802 this.lsp_notify_abs_paths_changed(
10803 language_server_id,
10804 matching_entries,
10805 );
10806 ControlFlow::Continue(())
10807 })
10808 .ok()?;
10809
10810 if action.is_break() {
10811 break;
10812 }
10813 }
10814 Some(())
10815 })
10816 .await;
10817 }
10818 });
10819 (abs_path, (globset, task))
10820 })
10821 .collect();
10822 LanguageServerWatchedPaths {
10823 worktree_paths: self.worktree_paths,
10824 abs_paths,
10825 }
10826 }
10827}
10828
10829struct LspBufferSnapshot {
10830 version: i32,
10831 snapshot: TextBufferSnapshot,
10832}
10833
10834/// A prompt requested by LSP server.
10835#[derive(Clone, Debug)]
10836pub struct LanguageServerPromptRequest {
10837 pub level: PromptLevel,
10838 pub message: String,
10839 pub actions: Vec<MessageActionItem>,
10840 pub lsp_name: String,
10841 pub(crate) response_channel: Sender<MessageActionItem>,
10842}
10843
10844impl LanguageServerPromptRequest {
10845 pub async fn respond(self, index: usize) -> Option<()> {
10846 if let Some(response) = self.actions.into_iter().nth(index) {
10847 self.response_channel.send(response).await.ok()
10848 } else {
10849 None
10850 }
10851 }
10852}
10853impl PartialEq for LanguageServerPromptRequest {
10854 fn eq(&self, other: &Self) -> bool {
10855 self.message == other.message && self.actions == other.actions
10856 }
10857}
10858
10859#[derive(Clone, Debug, PartialEq)]
10860pub enum LanguageServerLogType {
10861 Log(MessageType),
10862 Trace(Option<String>),
10863}
10864
10865impl LanguageServerLogType {
10866 pub fn to_proto(&self) -> proto::language_server_log::LogType {
10867 match self {
10868 Self::Log(log_type) => {
10869 let message_type = match *log_type {
10870 MessageType::ERROR => 1,
10871 MessageType::WARNING => 2,
10872 MessageType::INFO => 3,
10873 MessageType::LOG => 4,
10874 other => {
10875 log::warn!("Unknown lsp log message type: {:?}", other);
10876 4
10877 }
10878 };
10879 proto::language_server_log::LogType::LogMessageType(message_type)
10880 }
10881 Self::Trace(message) => {
10882 proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
10883 message: message.clone(),
10884 })
10885 }
10886 }
10887 }
10888
10889 pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
10890 match log_type {
10891 proto::language_server_log::LogType::LogMessageType(message_type) => {
10892 Self::Log(match message_type {
10893 1 => MessageType::ERROR,
10894 2 => MessageType::WARNING,
10895 3 => MessageType::INFO,
10896 4 => MessageType::LOG,
10897 _ => MessageType::LOG,
10898 })
10899 }
10900 proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
10901 }
10902 }
10903}
10904
10905pub enum LanguageServerState {
10906 Starting {
10907 startup: Task<Option<Arc<LanguageServer>>>,
10908 /// List of language servers that will be added to the workspace once it's initialization completes.
10909 pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
10910 },
10911
10912 Running {
10913 adapter: Arc<CachedLspAdapter>,
10914 server: Arc<LanguageServer>,
10915 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
10916 workspace_refresh_task: Option<(mpsc::Sender<()>, Task<()>)>,
10917 },
10918}
10919
10920impl LanguageServerState {
10921 fn add_workspace_folder(&self, uri: Url) {
10922 match self {
10923 LanguageServerState::Starting {
10924 pending_workspace_folders,
10925 ..
10926 } => {
10927 pending_workspace_folders.lock().insert(uri);
10928 }
10929 LanguageServerState::Running { server, .. } => {
10930 server.add_workspace_folder(uri);
10931 }
10932 }
10933 }
10934 fn _remove_workspace_folder(&self, uri: Url) {
10935 match self {
10936 LanguageServerState::Starting {
10937 pending_workspace_folders,
10938 ..
10939 } => {
10940 pending_workspace_folders.lock().remove(&uri);
10941 }
10942 LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
10943 }
10944 }
10945}
10946
10947impl std::fmt::Debug for LanguageServerState {
10948 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10949 match self {
10950 LanguageServerState::Starting { .. } => {
10951 f.debug_struct("LanguageServerState::Starting").finish()
10952 }
10953 LanguageServerState::Running { .. } => {
10954 f.debug_struct("LanguageServerState::Running").finish()
10955 }
10956 }
10957 }
10958}
10959
10960#[derive(Clone, Debug, Serialize)]
10961pub struct LanguageServerProgress {
10962 pub is_disk_based_diagnostics_progress: bool,
10963 pub is_cancellable: bool,
10964 pub title: Option<String>,
10965 pub message: Option<String>,
10966 pub percentage: Option<usize>,
10967 #[serde(skip_serializing)]
10968 pub last_update_at: Instant,
10969}
10970
10971#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
10972pub struct DiagnosticSummary {
10973 pub error_count: usize,
10974 pub warning_count: usize,
10975}
10976
10977impl DiagnosticSummary {
10978 pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
10979 let mut this = Self {
10980 error_count: 0,
10981 warning_count: 0,
10982 };
10983
10984 for entry in diagnostics {
10985 if entry.diagnostic.is_primary {
10986 match entry.diagnostic.severity {
10987 DiagnosticSeverity::ERROR => this.error_count += 1,
10988 DiagnosticSeverity::WARNING => this.warning_count += 1,
10989 _ => {}
10990 }
10991 }
10992 }
10993
10994 this
10995 }
10996
10997 pub fn is_empty(&self) -> bool {
10998 self.error_count == 0 && self.warning_count == 0
10999 }
11000
11001 pub fn to_proto(
11002 &self,
11003 language_server_id: LanguageServerId,
11004 path: &Path,
11005 ) -> proto::DiagnosticSummary {
11006 proto::DiagnosticSummary {
11007 path: path.to_proto(),
11008 language_server_id: language_server_id.0 as u64,
11009 error_count: self.error_count as u32,
11010 warning_count: self.warning_count as u32,
11011 }
11012 }
11013}
11014
11015#[derive(Clone, Debug)]
11016pub enum CompletionDocumentation {
11017 /// There is no documentation for this completion.
11018 Undocumented,
11019 /// A single line of documentation.
11020 SingleLine(SharedString),
11021 /// Multiple lines of plain text documentation.
11022 MultiLinePlainText(SharedString),
11023 /// Markdown documentation.
11024 MultiLineMarkdown(SharedString),
11025 /// Both single line and multiple lines of plain text documentation.
11026 SingleLineAndMultiLinePlainText {
11027 single_line: SharedString,
11028 plain_text: Option<SharedString>,
11029 },
11030}
11031
11032impl From<lsp::Documentation> for CompletionDocumentation {
11033 fn from(docs: lsp::Documentation) -> Self {
11034 match docs {
11035 lsp::Documentation::String(text) => {
11036 if text.lines().count() <= 1 {
11037 CompletionDocumentation::SingleLine(text.into())
11038 } else {
11039 CompletionDocumentation::MultiLinePlainText(text.into())
11040 }
11041 }
11042
11043 lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
11044 lsp::MarkupKind::PlainText => {
11045 if value.lines().count() <= 1 {
11046 CompletionDocumentation::SingleLine(value.into())
11047 } else {
11048 CompletionDocumentation::MultiLinePlainText(value.into())
11049 }
11050 }
11051
11052 lsp::MarkupKind::Markdown => {
11053 CompletionDocumentation::MultiLineMarkdown(value.into())
11054 }
11055 },
11056 }
11057 }
11058}
11059
11060fn glob_literal_prefix(glob: &Path) -> PathBuf {
11061 glob.components()
11062 .take_while(|component| match component {
11063 path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
11064 _ => true,
11065 })
11066 .collect()
11067}
11068
11069pub struct SshLspAdapter {
11070 name: LanguageServerName,
11071 binary: LanguageServerBinary,
11072 initialization_options: Option<String>,
11073 code_action_kinds: Option<Vec<CodeActionKind>>,
11074}
11075
11076impl SshLspAdapter {
11077 pub fn new(
11078 name: LanguageServerName,
11079 binary: LanguageServerBinary,
11080 initialization_options: Option<String>,
11081 code_action_kinds: Option<String>,
11082 ) -> Self {
11083 Self {
11084 name,
11085 binary,
11086 initialization_options,
11087 code_action_kinds: code_action_kinds
11088 .as_ref()
11089 .and_then(|c| serde_json::from_str(c).ok()),
11090 }
11091 }
11092}
11093
11094#[async_trait(?Send)]
11095impl LspAdapter for SshLspAdapter {
11096 fn name(&self) -> LanguageServerName {
11097 self.name.clone()
11098 }
11099
11100 async fn initialization_options(
11101 self: Arc<Self>,
11102 _: &dyn Fs,
11103 _: &Arc<dyn LspAdapterDelegate>,
11104 ) -> Result<Option<serde_json::Value>> {
11105 let Some(options) = &self.initialization_options else {
11106 return Ok(None);
11107 };
11108 let result = serde_json::from_str(options)?;
11109 Ok(result)
11110 }
11111
11112 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
11113 self.code_action_kinds.clone()
11114 }
11115
11116 async fn check_if_user_installed(
11117 &self,
11118 _: &dyn LspAdapterDelegate,
11119 _: Arc<dyn LanguageToolchainStore>,
11120 _: &AsyncApp,
11121 ) -> Option<LanguageServerBinary> {
11122 Some(self.binary.clone())
11123 }
11124
11125 async fn cached_server_binary(
11126 &self,
11127 _: PathBuf,
11128 _: &dyn LspAdapterDelegate,
11129 ) -> Option<LanguageServerBinary> {
11130 None
11131 }
11132
11133 async fn fetch_latest_server_version(
11134 &self,
11135 _: &dyn LspAdapterDelegate,
11136 ) -> Result<Box<dyn 'static + Send + Any>> {
11137 anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
11138 }
11139
11140 async fn fetch_server_binary(
11141 &self,
11142 _: Box<dyn 'static + Send + Any>,
11143 _: PathBuf,
11144 _: &dyn LspAdapterDelegate,
11145 ) -> Result<LanguageServerBinary> {
11146 anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
11147 }
11148}
11149
11150pub fn language_server_settings<'a>(
11151 delegate: &'a dyn LspAdapterDelegate,
11152 language: &LanguageServerName,
11153 cx: &'a App,
11154) -> Option<&'a LspSettings> {
11155 language_server_settings_for(
11156 SettingsLocation {
11157 worktree_id: delegate.worktree_id(),
11158 path: delegate.worktree_root_path(),
11159 },
11160 language,
11161 cx,
11162 )
11163}
11164
11165pub(crate) fn language_server_settings_for<'a>(
11166 location: SettingsLocation<'a>,
11167 language: &LanguageServerName,
11168 cx: &'a App,
11169) -> Option<&'a LspSettings> {
11170 ProjectSettings::get(Some(location), cx).lsp.get(language)
11171}
11172
11173pub struct LocalLspAdapterDelegate {
11174 lsp_store: WeakEntity<LspStore>,
11175 worktree: worktree::Snapshot,
11176 fs: Arc<dyn Fs>,
11177 http_client: Arc<dyn HttpClient>,
11178 language_registry: Arc<LanguageRegistry>,
11179 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
11180}
11181
11182impl LocalLspAdapterDelegate {
11183 pub fn new(
11184 language_registry: Arc<LanguageRegistry>,
11185 environment: &Entity<ProjectEnvironment>,
11186 lsp_store: WeakEntity<LspStore>,
11187 worktree: &Entity<Worktree>,
11188 http_client: Arc<dyn HttpClient>,
11189 fs: Arc<dyn Fs>,
11190 cx: &mut App,
11191 ) -> Arc<Self> {
11192 let load_shell_env_task = environment.update(cx, |env, cx| {
11193 env.get_worktree_environment(worktree.clone(), cx)
11194 });
11195
11196 Arc::new(Self {
11197 lsp_store,
11198 worktree: worktree.read(cx).snapshot(),
11199 fs,
11200 http_client,
11201 language_registry,
11202 load_shell_env_task,
11203 })
11204 }
11205
11206 fn from_local_lsp(
11207 local: &LocalLspStore,
11208 worktree: &Entity<Worktree>,
11209 cx: &mut App,
11210 ) -> Arc<Self> {
11211 Self::new(
11212 local.languages.clone(),
11213 &local.environment,
11214 local.weak.clone(),
11215 worktree,
11216 local.http_client.clone(),
11217 local.fs.clone(),
11218 cx,
11219 )
11220 }
11221}
11222
11223#[async_trait]
11224impl LspAdapterDelegate for LocalLspAdapterDelegate {
11225 fn show_notification(&self, message: &str, cx: &mut App) {
11226 self.lsp_store
11227 .update(cx, |_, cx| {
11228 cx.emit(LspStoreEvent::Notification(message.to_owned()))
11229 })
11230 .ok();
11231 }
11232
11233 fn http_client(&self) -> Arc<dyn HttpClient> {
11234 self.http_client.clone()
11235 }
11236
11237 fn worktree_id(&self) -> WorktreeId {
11238 self.worktree.id()
11239 }
11240
11241 fn worktree_root_path(&self) -> &Path {
11242 self.worktree.abs_path().as_ref()
11243 }
11244
11245 async fn shell_env(&self) -> HashMap<String, String> {
11246 let task = self.load_shell_env_task.clone();
11247 task.await.unwrap_or_default()
11248 }
11249
11250 async fn npm_package_installed_version(
11251 &self,
11252 package_name: &str,
11253 ) -> Result<Option<(PathBuf, String)>> {
11254 let local_package_directory = self.worktree_root_path();
11255 let node_modules_directory = local_package_directory.join("node_modules");
11256
11257 if let Some(version) =
11258 read_package_installed_version(node_modules_directory.clone(), package_name).await?
11259 {
11260 return Ok(Some((node_modules_directory, version)));
11261 }
11262 let Some(npm) = self.which("npm".as_ref()).await else {
11263 log::warn!(
11264 "Failed to find npm executable for {:?}",
11265 local_package_directory
11266 );
11267 return Ok(None);
11268 };
11269
11270 let env = self.shell_env().await;
11271 let output = util::command::new_smol_command(&npm)
11272 .args(["root", "-g"])
11273 .envs(env)
11274 .current_dir(local_package_directory)
11275 .output()
11276 .await?;
11277 let global_node_modules =
11278 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
11279
11280 if let Some(version) =
11281 read_package_installed_version(global_node_modules.clone(), package_name).await?
11282 {
11283 return Ok(Some((global_node_modules, version)));
11284 }
11285 return Ok(None);
11286 }
11287
11288 #[cfg(not(target_os = "windows"))]
11289 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11290 let worktree_abs_path = self.worktree.abs_path();
11291 let shell_path = self.shell_env().await.get("PATH").cloned();
11292 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
11293 }
11294
11295 #[cfg(target_os = "windows")]
11296 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11297 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11298 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11299 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11300 which::which(command).ok()
11301 }
11302
11303 async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
11304 let working_dir = self.worktree_root_path();
11305 let output = util::command::new_smol_command(&command.path)
11306 .args(command.arguments)
11307 .envs(command.env.clone().unwrap_or_default())
11308 .current_dir(working_dir)
11309 .output()
11310 .await?;
11311
11312 anyhow::ensure!(
11313 output.status.success(),
11314 "{}, stdout: {:?}, stderr: {:?}",
11315 output.status,
11316 String::from_utf8_lossy(&output.stdout),
11317 String::from_utf8_lossy(&output.stderr)
11318 );
11319 Ok(())
11320 }
11321
11322 fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
11323 self.language_registry
11324 .update_lsp_status(server_name, LanguageServerStatusUpdate::Binary(status));
11325 }
11326
11327 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
11328 self.language_registry
11329 .all_lsp_adapters()
11330 .into_iter()
11331 .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
11332 .collect()
11333 }
11334
11335 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
11336 let dir = self.language_registry.language_server_download_dir(name)?;
11337
11338 if !dir.exists() {
11339 smol::fs::create_dir_all(&dir)
11340 .await
11341 .context("failed to create container directory")
11342 .log_err()?;
11343 }
11344
11345 Some(dir)
11346 }
11347
11348 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11349 let entry = self
11350 .worktree
11351 .entry_for_path(&path)
11352 .with_context(|| format!("no worktree entry for path {path:?}"))?;
11353 let abs_path = self
11354 .worktree
11355 .absolutize(&entry.path)
11356 .with_context(|| format!("cannot absolutize path {path:?}"))?;
11357
11358 self.fs.load(&abs_path).await
11359 }
11360}
11361
11362async fn populate_labels_for_symbols(
11363 symbols: Vec<CoreSymbol>,
11364 language_registry: &Arc<LanguageRegistry>,
11365 lsp_adapter: Option<Arc<CachedLspAdapter>>,
11366 output: &mut Vec<Symbol>,
11367) {
11368 #[allow(clippy::mutable_key_type)]
11369 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
11370
11371 let mut unknown_paths = BTreeSet::new();
11372 for symbol in symbols {
11373 let language = language_registry
11374 .language_for_file_path(&symbol.path.path)
11375 .await
11376 .ok()
11377 .or_else(|| {
11378 unknown_paths.insert(symbol.path.path.clone());
11379 None
11380 });
11381 symbols_by_language
11382 .entry(language)
11383 .or_default()
11384 .push(symbol);
11385 }
11386
11387 for unknown_path in unknown_paths {
11388 log::info!(
11389 "no language found for symbol path {}",
11390 unknown_path.display()
11391 );
11392 }
11393
11394 let mut label_params = Vec::new();
11395 for (language, mut symbols) in symbols_by_language {
11396 label_params.clear();
11397 label_params.extend(
11398 symbols
11399 .iter_mut()
11400 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
11401 );
11402
11403 let mut labels = Vec::new();
11404 if let Some(language) = language {
11405 let lsp_adapter = lsp_adapter.clone().or_else(|| {
11406 language_registry
11407 .lsp_adapters(&language.name())
11408 .first()
11409 .cloned()
11410 });
11411 if let Some(lsp_adapter) = lsp_adapter {
11412 labels = lsp_adapter
11413 .labels_for_symbols(&label_params, &language)
11414 .await
11415 .log_err()
11416 .unwrap_or_default();
11417 }
11418 }
11419
11420 for ((symbol, (name, _)), label) in symbols
11421 .into_iter()
11422 .zip(label_params.drain(..))
11423 .zip(labels.into_iter().chain(iter::repeat(None)))
11424 {
11425 output.push(Symbol {
11426 language_server_name: symbol.language_server_name,
11427 source_worktree_id: symbol.source_worktree_id,
11428 source_language_server_id: symbol.source_language_server_id,
11429 path: symbol.path,
11430 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
11431 name,
11432 kind: symbol.kind,
11433 range: symbol.range,
11434 signature: symbol.signature,
11435 });
11436 }
11437 }
11438}
11439
11440fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
11441 match server.capabilities().text_document_sync.as_ref()? {
11442 lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
11443 lsp::TextDocumentSyncKind::NONE => None,
11444 lsp::TextDocumentSyncKind::FULL => Some(true),
11445 lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
11446 _ => None,
11447 },
11448 lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
11449 lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
11450 if *supported {
11451 Some(true)
11452 } else {
11453 None
11454 }
11455 }
11456 lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
11457 Some(save_options.include_text.unwrap_or(false))
11458 }
11459 },
11460 }
11461}
11462
11463/// Completion items are displayed in a `UniformList`.
11464/// Usually, those items are single-line strings, but in LSP responses,
11465/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
11466/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
11467/// 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,
11468/// breaking the completions menu presentation.
11469///
11470/// 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.
11471fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
11472 let mut new_text = String::with_capacity(label.text.len());
11473 let mut offset_map = vec![0; label.text.len() + 1];
11474 let mut last_char_was_space = false;
11475 let mut new_idx = 0;
11476 let mut chars = label.text.char_indices().fuse();
11477 let mut newlines_removed = false;
11478
11479 while let Some((idx, c)) = chars.next() {
11480 offset_map[idx] = new_idx;
11481
11482 match c {
11483 '\n' if last_char_was_space => {
11484 newlines_removed = true;
11485 }
11486 '\t' | ' ' if last_char_was_space => {}
11487 '\n' if !last_char_was_space => {
11488 new_text.push(' ');
11489 new_idx += 1;
11490 last_char_was_space = true;
11491 newlines_removed = true;
11492 }
11493 ' ' | '\t' => {
11494 new_text.push(' ');
11495 new_idx += 1;
11496 last_char_was_space = true;
11497 }
11498 _ => {
11499 new_text.push(c);
11500 new_idx += c.len_utf8();
11501 last_char_was_space = false;
11502 }
11503 }
11504 }
11505 offset_map[label.text.len()] = new_idx;
11506
11507 // Only modify the label if newlines were removed.
11508 if !newlines_removed {
11509 return;
11510 }
11511
11512 let last_index = new_idx;
11513 let mut run_ranges_errors = Vec::new();
11514 label.runs.retain_mut(|(range, _)| {
11515 match offset_map.get(range.start) {
11516 Some(&start) => range.start = start,
11517 None => {
11518 run_ranges_errors.push(range.clone());
11519 return false;
11520 }
11521 }
11522
11523 match offset_map.get(range.end) {
11524 Some(&end) => range.end = end,
11525 None => {
11526 run_ranges_errors.push(range.clone());
11527 range.end = last_index;
11528 }
11529 }
11530 true
11531 });
11532 if !run_ranges_errors.is_empty() {
11533 log::error!(
11534 "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
11535 label.text
11536 );
11537 }
11538
11539 let mut wrong_filter_range = None;
11540 if label.filter_range == (0..label.text.len()) {
11541 label.filter_range = 0..new_text.len();
11542 } else {
11543 let mut original_filter_range = Some(label.filter_range.clone());
11544 match offset_map.get(label.filter_range.start) {
11545 Some(&start) => label.filter_range.start = start,
11546 None => {
11547 wrong_filter_range = original_filter_range.take();
11548 label.filter_range.start = last_index;
11549 }
11550 }
11551
11552 match offset_map.get(label.filter_range.end) {
11553 Some(&end) => label.filter_range.end = end,
11554 None => {
11555 wrong_filter_range = original_filter_range.take();
11556 label.filter_range.end = last_index;
11557 }
11558 }
11559 }
11560 if let Some(wrong_filter_range) = wrong_filter_range {
11561 log::error!(
11562 "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
11563 label.text
11564 );
11565 }
11566
11567 label.text = new_text;
11568}
11569
11570#[cfg(test)]
11571mod tests {
11572 use language::HighlightId;
11573
11574 use super::*;
11575
11576 #[test]
11577 fn test_glob_literal_prefix() {
11578 assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
11579 assert_eq!(
11580 glob_literal_prefix(Path::new("node_modules/**/*.js")),
11581 Path::new("node_modules")
11582 );
11583 assert_eq!(
11584 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
11585 Path::new("foo")
11586 );
11587 assert_eq!(
11588 glob_literal_prefix(Path::new("foo/bar/baz.js")),
11589 Path::new("foo/bar/baz.js")
11590 );
11591
11592 #[cfg(target_os = "windows")]
11593 {
11594 assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
11595 assert_eq!(
11596 glob_literal_prefix(Path::new("node_modules\\**/*.js")),
11597 Path::new("node_modules")
11598 );
11599 assert_eq!(
11600 glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
11601 Path::new("foo")
11602 );
11603 assert_eq!(
11604 glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
11605 Path::new("foo/bar/baz.js")
11606 );
11607 }
11608 }
11609
11610 #[test]
11611 fn test_multi_len_chars_normalization() {
11612 let mut label = CodeLabel {
11613 text: "myElˇ (parameter) myElˇ: {\n foo: string;\n}".to_string(),
11614 runs: vec![(0..6, HighlightId(1))],
11615 filter_range: 0..6,
11616 };
11617 ensure_uniform_list_compatible_label(&mut label);
11618 assert_eq!(
11619 label,
11620 CodeLabel {
11621 text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
11622 runs: vec![(0..6, HighlightId(1))],
11623 filter_range: 0..6,
11624 }
11625 );
11626 }
11627}