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