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