lsp_store.rs

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