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