lsp_store.rs

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