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