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