project.rs

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