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