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