lsp_store.rs

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