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.background_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                            LinkedEditingRange::check_server_capabilities(server.capabilities())
 5073                        })
 5074                        .filter(|(adapter, _)| {
 5075                            scope
 5076                                .as_ref()
 5077                                .map(|scope| scope.language_allowed(&adapter.name))
 5078                                .unwrap_or(true)
 5079                        })
 5080                        .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
 5081                        .next()
 5082                })
 5083            })
 5084            .or_else(|| {
 5085                self.upstream_client()
 5086                    .is_some()
 5087                    .then_some(LanguageServerToQuery::FirstCapable)
 5088            })
 5089            .filter(|_| {
 5090                maybe!({
 5091                    let language = buffer.read(cx).language_at(position)?;
 5092                    Some(
 5093                        language_settings(Some(language.name()), buffer.read(cx).file(), cx)
 5094                            .linked_edits,
 5095                    )
 5096                }) == Some(true)
 5097            })
 5098        else {
 5099            return Task::ready(Ok(vec![]));
 5100        };
 5101
 5102        self.request_lsp(
 5103            buffer.clone(),
 5104            server_id,
 5105            LinkedEditingRange { position },
 5106            cx,
 5107        )
 5108    }
 5109
 5110    fn apply_on_type_formatting(
 5111        &mut self,
 5112        buffer: Entity<Buffer>,
 5113        position: Anchor,
 5114        trigger: String,
 5115        cx: &mut Context<Self>,
 5116    ) -> Task<Result<Option<Transaction>>> {
 5117        if let Some((client, project_id)) = self.upstream_client() {
 5118            let request = proto::OnTypeFormatting {
 5119                project_id,
 5120                buffer_id: buffer.read(cx).remote_id().into(),
 5121                position: Some(serialize_anchor(&position)),
 5122                trigger,
 5123                version: serialize_version(&buffer.read(cx).version()),
 5124            };
 5125            cx.background_spawn(async move {
 5126                client
 5127                    .request(request)
 5128                    .await?
 5129                    .transaction
 5130                    .map(language::proto::deserialize_transaction)
 5131                    .transpose()
 5132            })
 5133        } else if let Some(local) = self.as_local_mut() {
 5134            let buffer_id = buffer.read(cx).remote_id();
 5135            local.buffers_being_formatted.insert(buffer_id);
 5136            cx.spawn(async move |this, cx| {
 5137                let _cleanup = defer({
 5138                    let this = this.clone();
 5139                    let mut cx = cx.clone();
 5140                    move || {
 5141                        this.update(&mut cx, |this, _| {
 5142                            if let Some(local) = this.as_local_mut() {
 5143                                local.buffers_being_formatted.remove(&buffer_id);
 5144                            }
 5145                        })
 5146                        .ok();
 5147                    }
 5148                });
 5149
 5150                buffer
 5151                    .update(cx, |buffer, _| {
 5152                        buffer.wait_for_edits(Some(position.timestamp))
 5153                    })?
 5154                    .await?;
 5155                this.update(cx, |this, cx| {
 5156                    let position = position.to_point_utf16(buffer.read(cx));
 5157                    this.on_type_format(buffer, position, trigger, false, cx)
 5158                })?
 5159                .await
 5160            })
 5161        } else {
 5162            Task::ready(Err(anyhow!("No upstream client or local language server")))
 5163        }
 5164    }
 5165
 5166    pub fn on_type_format<T: ToPointUtf16>(
 5167        &mut self,
 5168        buffer: Entity<Buffer>,
 5169        position: T,
 5170        trigger: String,
 5171        push_to_history: bool,
 5172        cx: &mut Context<Self>,
 5173    ) -> Task<Result<Option<Transaction>>> {
 5174        let position = position.to_point_utf16(buffer.read(cx));
 5175        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 5176    }
 5177
 5178    fn on_type_format_impl(
 5179        &mut self,
 5180        buffer: Entity<Buffer>,
 5181        position: PointUtf16,
 5182        trigger: String,
 5183        push_to_history: bool,
 5184        cx: &mut Context<Self>,
 5185    ) -> Task<Result<Option<Transaction>>> {
 5186        let options = buffer.update(cx, |buffer, cx| {
 5187            lsp_command::lsp_formatting_options(
 5188                language_settings(
 5189                    buffer.language_at(position).map(|l| l.name()),
 5190                    buffer.file(),
 5191                    cx,
 5192                )
 5193                .as_ref(),
 5194            )
 5195        });
 5196
 5197        cx.spawn(async move |this, cx| {
 5198            if let Some(waiter) =
 5199                buffer.update(cx, |buffer, _| buffer.wait_for_autoindent_applied())?
 5200            {
 5201                waiter.await?;
 5202            }
 5203            cx.update(|cx| {
 5204                this.update(cx, |this, cx| {
 5205                    this.request_lsp(
 5206                        buffer.clone(),
 5207                        LanguageServerToQuery::FirstCapable,
 5208                        OnTypeFormatting {
 5209                            position,
 5210                            trigger,
 5211                            options,
 5212                            push_to_history,
 5213                        },
 5214                        cx,
 5215                    )
 5216                })
 5217            })??
 5218            .await
 5219        })
 5220    }
 5221
 5222    pub fn definitions(
 5223        &mut self,
 5224        buffer_handle: &Entity<Buffer>,
 5225        position: PointUtf16,
 5226        cx: &mut Context<Self>,
 5227    ) -> Task<Result<Vec<LocationLink>>> {
 5228        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5229            let request_task = upstream_client.request(proto::MultiLspQuery {
 5230                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5231                version: serialize_version(&buffer_handle.read(cx).version()),
 5232                project_id,
 5233                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5234                    proto::AllLanguageServers {},
 5235                )),
 5236                request: Some(proto::multi_lsp_query::Request::GetDefinition(
 5237                    GetDefinitions { position }.to_proto(project_id, buffer_handle.read(cx)),
 5238                )),
 5239            });
 5240            let buffer = buffer_handle.clone();
 5241            cx.spawn(async move |weak_project, cx| {
 5242                let Some(project) = weak_project.upgrade() else {
 5243                    return Ok(Vec::new());
 5244                };
 5245                let responses = request_task.await?.responses;
 5246                let actions = join_all(
 5247                    responses
 5248                        .into_iter()
 5249                        .filter_map(|lsp_response| match lsp_response.response? {
 5250                            proto::lsp_response::Response::GetDefinitionResponse(response) => {
 5251                                Some(response)
 5252                            }
 5253                            unexpected => {
 5254                                debug_panic!("Unexpected response: {unexpected:?}");
 5255                                None
 5256                            }
 5257                        })
 5258                        .map(|definitions_response| {
 5259                            GetDefinitions { position }.response_from_proto(
 5260                                definitions_response,
 5261                                project.clone(),
 5262                                buffer.clone(),
 5263                                cx.clone(),
 5264                            )
 5265                        }),
 5266                )
 5267                .await;
 5268
 5269                Ok(actions
 5270                    .into_iter()
 5271                    .collect::<Result<Vec<Vec<_>>>>()?
 5272                    .into_iter()
 5273                    .flatten()
 5274                    .dedup()
 5275                    .collect())
 5276            })
 5277        } else {
 5278            let definitions_task = self.request_multiple_lsp_locally(
 5279                buffer_handle,
 5280                Some(position),
 5281                GetDefinitions { position },
 5282                cx,
 5283            );
 5284            cx.background_spawn(async move {
 5285                Ok(definitions_task
 5286                    .await
 5287                    .into_iter()
 5288                    .flat_map(|(_, definitions)| definitions)
 5289                    .dedup()
 5290                    .collect())
 5291            })
 5292        }
 5293    }
 5294
 5295    pub fn declarations(
 5296        &mut self,
 5297        buffer_handle: &Entity<Buffer>,
 5298        position: PointUtf16,
 5299        cx: &mut Context<Self>,
 5300    ) -> Task<Result<Vec<LocationLink>>> {
 5301        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5302            let request_task = upstream_client.request(proto::MultiLspQuery {
 5303                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5304                version: serialize_version(&buffer_handle.read(cx).version()),
 5305                project_id,
 5306                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5307                    proto::AllLanguageServers {},
 5308                )),
 5309                request: Some(proto::multi_lsp_query::Request::GetDeclaration(
 5310                    GetDeclarations { position }.to_proto(project_id, buffer_handle.read(cx)),
 5311                )),
 5312            });
 5313            let buffer = buffer_handle.clone();
 5314            cx.spawn(async move |weak_project, cx| {
 5315                let Some(project) = weak_project.upgrade() else {
 5316                    return Ok(Vec::new());
 5317                };
 5318                let responses = request_task.await?.responses;
 5319                let actions = join_all(
 5320                    responses
 5321                        .into_iter()
 5322                        .filter_map(|lsp_response| match lsp_response.response? {
 5323                            proto::lsp_response::Response::GetDeclarationResponse(response) => {
 5324                                Some(response)
 5325                            }
 5326                            unexpected => {
 5327                                debug_panic!("Unexpected response: {unexpected:?}");
 5328                                None
 5329                            }
 5330                        })
 5331                        .map(|declarations_response| {
 5332                            GetDeclarations { position }.response_from_proto(
 5333                                declarations_response,
 5334                                project.clone(),
 5335                                buffer.clone(),
 5336                                cx.clone(),
 5337                            )
 5338                        }),
 5339                )
 5340                .await;
 5341
 5342                Ok(actions
 5343                    .into_iter()
 5344                    .collect::<Result<Vec<Vec<_>>>>()?
 5345                    .into_iter()
 5346                    .flatten()
 5347                    .dedup()
 5348                    .collect())
 5349            })
 5350        } else {
 5351            let declarations_task = self.request_multiple_lsp_locally(
 5352                buffer_handle,
 5353                Some(position),
 5354                GetDeclarations { position },
 5355                cx,
 5356            );
 5357            cx.background_spawn(async move {
 5358                Ok(declarations_task
 5359                    .await
 5360                    .into_iter()
 5361                    .flat_map(|(_, declarations)| declarations)
 5362                    .dedup()
 5363                    .collect())
 5364            })
 5365        }
 5366    }
 5367
 5368    pub fn type_definitions(
 5369        &mut self,
 5370        buffer_handle: &Entity<Buffer>,
 5371        position: PointUtf16,
 5372        cx: &mut Context<Self>,
 5373    ) -> Task<Result<Vec<LocationLink>>> {
 5374        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5375            let request_task = upstream_client.request(proto::MultiLspQuery {
 5376                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5377                version: serialize_version(&buffer_handle.read(cx).version()),
 5378                project_id,
 5379                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5380                    proto::AllLanguageServers {},
 5381                )),
 5382                request: Some(proto::multi_lsp_query::Request::GetTypeDefinition(
 5383                    GetTypeDefinitions { position }.to_proto(project_id, buffer_handle.read(cx)),
 5384                )),
 5385            });
 5386            let buffer = buffer_handle.clone();
 5387            cx.spawn(async move |weak_project, cx| {
 5388                let Some(project) = weak_project.upgrade() else {
 5389                    return Ok(Vec::new());
 5390                };
 5391                let responses = request_task.await?.responses;
 5392                let actions = join_all(
 5393                    responses
 5394                        .into_iter()
 5395                        .filter_map(|lsp_response| match lsp_response.response? {
 5396                            proto::lsp_response::Response::GetTypeDefinitionResponse(response) => {
 5397                                Some(response)
 5398                            }
 5399                            unexpected => {
 5400                                debug_panic!("Unexpected response: {unexpected:?}");
 5401                                None
 5402                            }
 5403                        })
 5404                        .map(|type_definitions_response| {
 5405                            GetTypeDefinitions { position }.response_from_proto(
 5406                                type_definitions_response,
 5407                                project.clone(),
 5408                                buffer.clone(),
 5409                                cx.clone(),
 5410                            )
 5411                        }),
 5412                )
 5413                .await;
 5414
 5415                Ok(actions
 5416                    .into_iter()
 5417                    .collect::<Result<Vec<Vec<_>>>>()?
 5418                    .into_iter()
 5419                    .flatten()
 5420                    .dedup()
 5421                    .collect())
 5422            })
 5423        } else {
 5424            let type_definitions_task = self.request_multiple_lsp_locally(
 5425                buffer_handle,
 5426                Some(position),
 5427                GetTypeDefinitions { position },
 5428                cx,
 5429            );
 5430            cx.background_spawn(async move {
 5431                Ok(type_definitions_task
 5432                    .await
 5433                    .into_iter()
 5434                    .flat_map(|(_, type_definitions)| type_definitions)
 5435                    .dedup()
 5436                    .collect())
 5437            })
 5438        }
 5439    }
 5440
 5441    pub fn implementations(
 5442        &mut self,
 5443        buffer_handle: &Entity<Buffer>,
 5444        position: PointUtf16,
 5445        cx: &mut Context<Self>,
 5446    ) -> Task<Result<Vec<LocationLink>>> {
 5447        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5448            let request_task = upstream_client.request(proto::MultiLspQuery {
 5449                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5450                version: serialize_version(&buffer_handle.read(cx).version()),
 5451                project_id,
 5452                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5453                    proto::AllLanguageServers {},
 5454                )),
 5455                request: Some(proto::multi_lsp_query::Request::GetImplementation(
 5456                    GetImplementations { position }.to_proto(project_id, buffer_handle.read(cx)),
 5457                )),
 5458            });
 5459            let buffer = buffer_handle.clone();
 5460            cx.spawn(async move |weak_project, cx| {
 5461                let Some(project) = weak_project.upgrade() else {
 5462                    return Ok(Vec::new());
 5463                };
 5464                let responses = request_task.await?.responses;
 5465                let actions = join_all(
 5466                    responses
 5467                        .into_iter()
 5468                        .filter_map(|lsp_response| match lsp_response.response? {
 5469                            proto::lsp_response::Response::GetImplementationResponse(response) => {
 5470                                Some(response)
 5471                            }
 5472                            unexpected => {
 5473                                debug_panic!("Unexpected response: {unexpected:?}");
 5474                                None
 5475                            }
 5476                        })
 5477                        .map(|implementations_response| {
 5478                            GetImplementations { position }.response_from_proto(
 5479                                implementations_response,
 5480                                project.clone(),
 5481                                buffer.clone(),
 5482                                cx.clone(),
 5483                            )
 5484                        }),
 5485                )
 5486                .await;
 5487
 5488                Ok(actions
 5489                    .into_iter()
 5490                    .collect::<Result<Vec<Vec<_>>>>()?
 5491                    .into_iter()
 5492                    .flatten()
 5493                    .dedup()
 5494                    .collect())
 5495            })
 5496        } else {
 5497            let implementations_task = self.request_multiple_lsp_locally(
 5498                buffer_handle,
 5499                Some(position),
 5500                GetImplementations { position },
 5501                cx,
 5502            );
 5503            cx.background_spawn(async move {
 5504                Ok(implementations_task
 5505                    .await
 5506                    .into_iter()
 5507                    .flat_map(|(_, implementations)| implementations)
 5508                    .dedup()
 5509                    .collect())
 5510            })
 5511        }
 5512    }
 5513
 5514    pub fn references(
 5515        &mut self,
 5516        buffer_handle: &Entity<Buffer>,
 5517        position: PointUtf16,
 5518        cx: &mut Context<Self>,
 5519    ) -> Task<Result<Vec<Location>>> {
 5520        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5521            let request_task = upstream_client.request(proto::MultiLspQuery {
 5522                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5523                version: serialize_version(&buffer_handle.read(cx).version()),
 5524                project_id,
 5525                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5526                    proto::AllLanguageServers {},
 5527                )),
 5528                request: Some(proto::multi_lsp_query::Request::GetReferences(
 5529                    GetReferences { position }.to_proto(project_id, buffer_handle.read(cx)),
 5530                )),
 5531            });
 5532            let buffer = buffer_handle.clone();
 5533            cx.spawn(async move |weak_project, cx| {
 5534                let Some(project) = weak_project.upgrade() else {
 5535                    return Ok(Vec::new());
 5536                };
 5537                let responses = request_task.await?.responses;
 5538                let actions = join_all(
 5539                    responses
 5540                        .into_iter()
 5541                        .filter_map(|lsp_response| match lsp_response.response? {
 5542                            proto::lsp_response::Response::GetReferencesResponse(response) => {
 5543                                Some(response)
 5544                            }
 5545                            unexpected => {
 5546                                debug_panic!("Unexpected response: {unexpected:?}");
 5547                                None
 5548                            }
 5549                        })
 5550                        .map(|references_response| {
 5551                            GetReferences { position }.response_from_proto(
 5552                                references_response,
 5553                                project.clone(),
 5554                                buffer.clone(),
 5555                                cx.clone(),
 5556                            )
 5557                        }),
 5558                )
 5559                .await;
 5560
 5561                Ok(actions
 5562                    .into_iter()
 5563                    .collect::<Result<Vec<Vec<_>>>>()?
 5564                    .into_iter()
 5565                    .flatten()
 5566                    .dedup()
 5567                    .collect())
 5568            })
 5569        } else {
 5570            let references_task = self.request_multiple_lsp_locally(
 5571                buffer_handle,
 5572                Some(position),
 5573                GetReferences { position },
 5574                cx,
 5575            );
 5576            cx.background_spawn(async move {
 5577                Ok(references_task
 5578                    .await
 5579                    .into_iter()
 5580                    .flat_map(|(_, references)| references)
 5581                    .dedup()
 5582                    .collect())
 5583            })
 5584        }
 5585    }
 5586
 5587    pub fn code_actions(
 5588        &mut self,
 5589        buffer_handle: &Entity<Buffer>,
 5590        range: Range<Anchor>,
 5591        kinds: Option<Vec<CodeActionKind>>,
 5592        cx: &mut Context<Self>,
 5593    ) -> Task<Result<Vec<CodeAction>>> {
 5594        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5595            let request_task = upstream_client.request(proto::MultiLspQuery {
 5596                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5597                version: serialize_version(&buffer_handle.read(cx).version()),
 5598                project_id,
 5599                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5600                    proto::AllLanguageServers {},
 5601                )),
 5602                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 5603                    GetCodeActions {
 5604                        range: range.clone(),
 5605                        kinds: kinds.clone(),
 5606                    }
 5607                    .to_proto(project_id, buffer_handle.read(cx)),
 5608                )),
 5609            });
 5610            let buffer = buffer_handle.clone();
 5611            cx.spawn(async move |weak_project, cx| {
 5612                let Some(project) = weak_project.upgrade() else {
 5613                    return Ok(Vec::new());
 5614                };
 5615                let responses = request_task.await?.responses;
 5616                let actions = join_all(
 5617                    responses
 5618                        .into_iter()
 5619                        .filter_map(|lsp_response| match lsp_response.response? {
 5620                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 5621                                Some(response)
 5622                            }
 5623                            unexpected => {
 5624                                debug_panic!("Unexpected response: {unexpected:?}");
 5625                                None
 5626                            }
 5627                        })
 5628                        .map(|code_actions_response| {
 5629                            GetCodeActions {
 5630                                range: range.clone(),
 5631                                kinds: kinds.clone(),
 5632                            }
 5633                            .response_from_proto(
 5634                                code_actions_response,
 5635                                project.clone(),
 5636                                buffer.clone(),
 5637                                cx.clone(),
 5638                            )
 5639                        }),
 5640                )
 5641                .await;
 5642
 5643                Ok(actions
 5644                    .into_iter()
 5645                    .collect::<Result<Vec<Vec<_>>>>()?
 5646                    .into_iter()
 5647                    .flatten()
 5648                    .collect())
 5649            })
 5650        } else {
 5651            let all_actions_task = self.request_multiple_lsp_locally(
 5652                buffer_handle,
 5653                Some(range.start),
 5654                GetCodeActions {
 5655                    range: range.clone(),
 5656                    kinds: kinds.clone(),
 5657                },
 5658                cx,
 5659            );
 5660            cx.background_spawn(async move {
 5661                Ok(all_actions_task
 5662                    .await
 5663                    .into_iter()
 5664                    .flat_map(|(_, actions)| actions)
 5665                    .collect())
 5666            })
 5667        }
 5668    }
 5669
 5670    pub fn code_lens_actions(
 5671        &mut self,
 5672        buffer: &Entity<Buffer>,
 5673        cx: &mut Context<Self>,
 5674    ) -> CodeLensTask {
 5675        let version_queried_for = buffer.read(cx).version();
 5676        let buffer_id = buffer.read(cx).remote_id();
 5677
 5678        if let Some(cached_data) = self.lsp_code_lens.get(&buffer_id) {
 5679            if !version_queried_for.changed_since(&cached_data.lens_for_version) {
 5680                let has_different_servers = self.as_local().is_some_and(|local| {
 5681                    local
 5682                        .buffers_opened_in_servers
 5683                        .get(&buffer_id)
 5684                        .cloned()
 5685                        .unwrap_or_default()
 5686                        != cached_data.lens.keys().copied().collect()
 5687                });
 5688                if !has_different_servers {
 5689                    return Task::ready(Ok(cached_data.lens.values().flatten().cloned().collect()))
 5690                        .shared();
 5691                }
 5692            }
 5693        }
 5694
 5695        let lsp_data = self.lsp_code_lens.entry(buffer_id).or_default();
 5696        if let Some((updating_for, running_update)) = &lsp_data.update {
 5697            if !version_queried_for.changed_since(&updating_for) {
 5698                return running_update.clone();
 5699            }
 5700        }
 5701        let buffer = buffer.clone();
 5702        let query_version_queried_for = version_queried_for.clone();
 5703        let new_task = cx
 5704            .spawn(async move |lsp_store, cx| {
 5705                cx.background_executor()
 5706                    .timer(Duration::from_millis(30))
 5707                    .await;
 5708                let fetched_lens = lsp_store
 5709                    .update(cx, |lsp_store, cx| lsp_store.fetch_code_lens(&buffer, cx))
 5710                    .map_err(Arc::new)?
 5711                    .await
 5712                    .context("fetching code lens")
 5713                    .map_err(Arc::new);
 5714                let fetched_lens = match fetched_lens {
 5715                    Ok(fetched_lens) => fetched_lens,
 5716                    Err(e) => {
 5717                        lsp_store
 5718                            .update(cx, |lsp_store, _| {
 5719                                lsp_store.lsp_code_lens.entry(buffer_id).or_default().update = None;
 5720                            })
 5721                            .ok();
 5722                        return Err(e);
 5723                    }
 5724                };
 5725
 5726                lsp_store
 5727                    .update(cx, |lsp_store, _| {
 5728                        let lsp_data = lsp_store.lsp_code_lens.entry(buffer_id).or_default();
 5729                        if lsp_data.lens_for_version == query_version_queried_for {
 5730                            lsp_data.lens.extend(fetched_lens.clone());
 5731                        } else if !lsp_data
 5732                            .lens_for_version
 5733                            .changed_since(&query_version_queried_for)
 5734                        {
 5735                            lsp_data.lens_for_version = query_version_queried_for;
 5736                            lsp_data.lens = fetched_lens.clone();
 5737                        }
 5738                        lsp_data.update = None;
 5739                        lsp_data.lens.values().flatten().cloned().collect()
 5740                    })
 5741                    .map_err(Arc::new)
 5742            })
 5743            .shared();
 5744        lsp_data.update = Some((version_queried_for, new_task.clone()));
 5745        new_task
 5746    }
 5747
 5748    fn fetch_code_lens(
 5749        &mut self,
 5750        buffer: &Entity<Buffer>,
 5751        cx: &mut Context<Self>,
 5752    ) -> Task<Result<HashMap<LanguageServerId, Vec<CodeAction>>>> {
 5753        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5754            let request_task = upstream_client.request(proto::MultiLspQuery {
 5755                buffer_id: buffer.read(cx).remote_id().into(),
 5756                version: serialize_version(&buffer.read(cx).version()),
 5757                project_id,
 5758                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5759                    proto::AllLanguageServers {},
 5760                )),
 5761                request: Some(proto::multi_lsp_query::Request::GetCodeLens(
 5762                    GetCodeLens.to_proto(project_id, buffer.read(cx)),
 5763                )),
 5764            });
 5765            let buffer = buffer.clone();
 5766            cx.spawn(async move |weak_lsp_store, cx| {
 5767                let Some(lsp_store) = weak_lsp_store.upgrade() else {
 5768                    return Ok(HashMap::default());
 5769                };
 5770                let responses = request_task.await?.responses;
 5771                let code_lens_actions = join_all(
 5772                    responses
 5773                        .into_iter()
 5774                        .filter_map(|lsp_response| {
 5775                            let response = match lsp_response.response? {
 5776                                proto::lsp_response::Response::GetCodeLensResponse(response) => {
 5777                                    Some(response)
 5778                                }
 5779                                unexpected => {
 5780                                    debug_panic!("Unexpected response: {unexpected:?}");
 5781                                    None
 5782                                }
 5783                            }?;
 5784                            let server_id = LanguageServerId::from_proto(lsp_response.server_id);
 5785                            Some((server_id, response))
 5786                        })
 5787                        .map(|(server_id, code_lens_response)| {
 5788                            let lsp_store = lsp_store.clone();
 5789                            let buffer = buffer.clone();
 5790                            let cx = cx.clone();
 5791                            async move {
 5792                                (
 5793                                    server_id,
 5794                                    GetCodeLens
 5795                                        .response_from_proto(
 5796                                            code_lens_response,
 5797                                            lsp_store,
 5798                                            buffer,
 5799                                            cx,
 5800                                        )
 5801                                        .await,
 5802                                )
 5803                            }
 5804                        }),
 5805                )
 5806                .await;
 5807
 5808                let mut has_errors = false;
 5809                let code_lens_actions = code_lens_actions
 5810                    .into_iter()
 5811                    .filter_map(|(server_id, code_lens)| match code_lens {
 5812                        Ok(code_lens) => Some((server_id, code_lens)),
 5813                        Err(e) => {
 5814                            has_errors = true;
 5815                            log::error!("{e:#}");
 5816                            None
 5817                        }
 5818                    })
 5819                    .collect::<HashMap<_, _>>();
 5820                anyhow::ensure!(
 5821                    !has_errors || !code_lens_actions.is_empty(),
 5822                    "Failed to fetch code lens"
 5823                );
 5824                Ok(code_lens_actions)
 5825            })
 5826        } else {
 5827            let code_lens_actions_task =
 5828                self.request_multiple_lsp_locally(buffer, None::<usize>, GetCodeLens, cx);
 5829            cx.background_spawn(
 5830                async move { Ok(code_lens_actions_task.await.into_iter().collect()) },
 5831            )
 5832        }
 5833    }
 5834
 5835    #[inline(never)]
 5836    pub fn completions(
 5837        &self,
 5838        buffer: &Entity<Buffer>,
 5839        position: PointUtf16,
 5840        context: CompletionContext,
 5841        cx: &mut Context<Self>,
 5842    ) -> Task<Result<Vec<CompletionResponse>>> {
 5843        let language_registry = self.languages.clone();
 5844
 5845        if let Some((upstream_client, project_id)) = self.upstream_client() {
 5846            let task = self.send_lsp_proto_request(
 5847                buffer.clone(),
 5848                upstream_client,
 5849                project_id,
 5850                GetCompletions { position, context },
 5851                cx,
 5852            );
 5853            let language = buffer.read(cx).language().cloned();
 5854
 5855            // In the future, we should provide project guests with the names of LSP adapters,
 5856            // so that they can use the correct LSP adapter when computing labels. For now,
 5857            // guests just use the first LSP adapter associated with the buffer's language.
 5858            let lsp_adapter = language.as_ref().and_then(|language| {
 5859                language_registry
 5860                    .lsp_adapters(&language.name())
 5861                    .first()
 5862                    .cloned()
 5863            });
 5864
 5865            cx.foreground_executor().spawn(async move {
 5866                let completion_response = task.await?;
 5867                let completions = populate_labels_for_completions(
 5868                    completion_response.completions,
 5869                    language,
 5870                    lsp_adapter,
 5871                )
 5872                .await;
 5873                Ok(vec![CompletionResponse {
 5874                    completions,
 5875                    is_incomplete: completion_response.is_incomplete,
 5876                }])
 5877            })
 5878        } else if let Some(local) = self.as_local() {
 5879            let snapshot = buffer.read(cx).snapshot();
 5880            let offset = position.to_offset(&snapshot);
 5881            let scope = snapshot.language_scope_at(offset);
 5882            let language = snapshot.language().cloned();
 5883            let completion_settings = language_settings(
 5884                language.as_ref().map(|language| language.name()),
 5885                buffer.read(cx).file(),
 5886                cx,
 5887            )
 5888            .completions;
 5889            if !completion_settings.lsp {
 5890                return Task::ready(Ok(Vec::new()));
 5891            }
 5892
 5893            let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
 5894                local
 5895                    .language_servers_for_buffer(buffer, cx)
 5896                    .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5897                    .filter(|(adapter, _)| {
 5898                        scope
 5899                            .as_ref()
 5900                            .map(|scope| scope.language_allowed(&adapter.name))
 5901                            .unwrap_or(true)
 5902                    })
 5903                    .map(|(_, server)| server.server_id())
 5904                    .collect()
 5905            });
 5906
 5907            let buffer = buffer.clone();
 5908            let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
 5909            let lsp_timeout = if lsp_timeout > 0 {
 5910                Some(Duration::from_millis(lsp_timeout))
 5911            } else {
 5912                None
 5913            };
 5914            cx.spawn(async move |this,  cx| {
 5915                let mut tasks = Vec::with_capacity(server_ids.len());
 5916                this.update(cx, |lsp_store, cx| {
 5917                    for server_id in server_ids {
 5918                        let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
 5919                        let lsp_timeout = lsp_timeout
 5920                            .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
 5921                        let mut timeout = cx.background_spawn(async move {
 5922                            match lsp_timeout {
 5923                                Some(lsp_timeout) => {
 5924                                    lsp_timeout.await;
 5925                                    true
 5926                                },
 5927                                None => false,
 5928                            }
 5929                        }).fuse();
 5930                        let mut lsp_request = lsp_store.request_lsp(
 5931                            buffer.clone(),
 5932                            LanguageServerToQuery::Other(server_id),
 5933                            GetCompletions {
 5934                                position,
 5935                                context: context.clone(),
 5936                            },
 5937                            cx,
 5938                        ).fuse();
 5939                        let new_task = cx.background_spawn(async move {
 5940                            select_biased! {
 5941                                response = lsp_request => anyhow::Ok(Some(response?)),
 5942                                timeout_happened = timeout => {
 5943                                    if timeout_happened {
 5944                                        log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
 5945                                        Ok(None)
 5946                                    } else {
 5947                                        let completions = lsp_request.await?;
 5948                                        Ok(Some(completions))
 5949                                    }
 5950                                },
 5951                            }
 5952                        });
 5953                        tasks.push((lsp_adapter, new_task));
 5954                    }
 5955                })?;
 5956
 5957                let futures = tasks.into_iter().map(async |(lsp_adapter, task)| {
 5958                    let completion_response = task.await.ok()??;
 5959                    let completions = populate_labels_for_completions(
 5960                            completion_response.completions,
 5961                            language.clone(),
 5962                            lsp_adapter,
 5963                        )
 5964                        .await;
 5965                    Some(CompletionResponse {
 5966                        completions,
 5967                        is_incomplete: completion_response.is_incomplete,
 5968                    })
 5969                });
 5970
 5971                let responses: Vec<Option<CompletionResponse>> = join_all(futures).await;
 5972
 5973                Ok(responses.into_iter().flatten().collect())
 5974            })
 5975        } else {
 5976            Task::ready(Err(anyhow!("No upstream client or local language server")))
 5977        }
 5978    }
 5979
 5980    pub fn resolve_completions(
 5981        &self,
 5982        buffer: Entity<Buffer>,
 5983        completion_indices: Vec<usize>,
 5984        completions: Rc<RefCell<Box<[Completion]>>>,
 5985        cx: &mut Context<Self>,
 5986    ) -> Task<Result<bool>> {
 5987        let client = self.upstream_client();
 5988
 5989        let buffer_id = buffer.read(cx).remote_id();
 5990        let buffer_snapshot = buffer.read(cx).snapshot();
 5991
 5992        cx.spawn(async move |this, cx| {
 5993            let mut did_resolve = false;
 5994            if let Some((client, project_id)) = client {
 5995                for completion_index in completion_indices {
 5996                    let server_id = {
 5997                        let completion = &completions.borrow()[completion_index];
 5998                        completion.source.server_id()
 5999                    };
 6000                    if let Some(server_id) = server_id {
 6001                        if Self::resolve_completion_remote(
 6002                            project_id,
 6003                            server_id,
 6004                            buffer_id,
 6005                            completions.clone(),
 6006                            completion_index,
 6007                            client.clone(),
 6008                        )
 6009                        .await
 6010                        .log_err()
 6011                        .is_some()
 6012                        {
 6013                            did_resolve = true;
 6014                        }
 6015                    } else {
 6016                        resolve_word_completion(
 6017                            &buffer_snapshot,
 6018                            &mut completions.borrow_mut()[completion_index],
 6019                        );
 6020                    }
 6021                }
 6022            } else {
 6023                for completion_index in completion_indices {
 6024                    let server_id = {
 6025                        let completion = &completions.borrow()[completion_index];
 6026                        completion.source.server_id()
 6027                    };
 6028                    if let Some(server_id) = server_id {
 6029                        let server_and_adapter = this
 6030                            .read_with(cx, |lsp_store, _| {
 6031                                let server = lsp_store.language_server_for_id(server_id)?;
 6032                                let adapter =
 6033                                    lsp_store.language_server_adapter_for_id(server.server_id())?;
 6034                                Some((server, adapter))
 6035                            })
 6036                            .ok()
 6037                            .flatten();
 6038                        let Some((server, adapter)) = server_and_adapter else {
 6039                            continue;
 6040                        };
 6041
 6042                        let resolved = Self::resolve_completion_local(
 6043                            server,
 6044                            completions.clone(),
 6045                            completion_index,
 6046                        )
 6047                        .await
 6048                        .log_err()
 6049                        .is_some();
 6050                        if resolved {
 6051                            Self::regenerate_completion_labels(
 6052                                adapter,
 6053                                &buffer_snapshot,
 6054                                completions.clone(),
 6055                                completion_index,
 6056                            )
 6057                            .await
 6058                            .log_err();
 6059                            did_resolve = true;
 6060                        }
 6061                    } else {
 6062                        resolve_word_completion(
 6063                            &buffer_snapshot,
 6064                            &mut completions.borrow_mut()[completion_index],
 6065                        );
 6066                    }
 6067                }
 6068            }
 6069
 6070            Ok(did_resolve)
 6071        })
 6072    }
 6073
 6074    async fn resolve_completion_local(
 6075        server: Arc<lsp::LanguageServer>,
 6076        completions: Rc<RefCell<Box<[Completion]>>>,
 6077        completion_index: usize,
 6078    ) -> Result<()> {
 6079        let server_id = server.server_id();
 6080        let can_resolve = server
 6081            .capabilities()
 6082            .completion_provider
 6083            .as_ref()
 6084            .and_then(|options| options.resolve_provider)
 6085            .unwrap_or(false);
 6086        if !can_resolve {
 6087            return Ok(());
 6088        }
 6089
 6090        let request = {
 6091            let completion = &completions.borrow()[completion_index];
 6092            match &completion.source {
 6093                CompletionSource::Lsp {
 6094                    lsp_completion,
 6095                    resolved,
 6096                    server_id: completion_server_id,
 6097                    ..
 6098                } => {
 6099                    if *resolved {
 6100                        return Ok(());
 6101                    }
 6102                    anyhow::ensure!(
 6103                        server_id == *completion_server_id,
 6104                        "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
 6105                    );
 6106                    server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
 6107                }
 6108                CompletionSource::BufferWord { .. }
 6109                | CompletionSource::Dap { .. }
 6110                | CompletionSource::Custom => {
 6111                    return Ok(());
 6112                }
 6113            }
 6114        };
 6115        let resolved_completion = request
 6116            .await
 6117            .into_response()
 6118            .context("resolve completion")?;
 6119
 6120        // We must not use any data such as sortText, filterText, insertText and textEdit to edit `Completion` since they are not suppose change during resolve.
 6121        // Refer: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
 6122
 6123        let mut completions = completions.borrow_mut();
 6124        let completion = &mut completions[completion_index];
 6125        if let CompletionSource::Lsp {
 6126            lsp_completion,
 6127            resolved,
 6128            server_id: completion_server_id,
 6129            ..
 6130        } = &mut completion.source
 6131        {
 6132            if *resolved {
 6133                return Ok(());
 6134            }
 6135            anyhow::ensure!(
 6136                server_id == *completion_server_id,
 6137                "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
 6138            );
 6139            *lsp_completion = Box::new(resolved_completion);
 6140            *resolved = true;
 6141        }
 6142        Ok(())
 6143    }
 6144
 6145    async fn regenerate_completion_labels(
 6146        adapter: Arc<CachedLspAdapter>,
 6147        snapshot: &BufferSnapshot,
 6148        completions: Rc<RefCell<Box<[Completion]>>>,
 6149        completion_index: usize,
 6150    ) -> Result<()> {
 6151        let completion_item = completions.borrow()[completion_index]
 6152            .source
 6153            .lsp_completion(true)
 6154            .map(Cow::into_owned);
 6155        if let Some(lsp_documentation) = completion_item
 6156            .as_ref()
 6157            .and_then(|completion_item| completion_item.documentation.clone())
 6158        {
 6159            let mut completions = completions.borrow_mut();
 6160            let completion = &mut completions[completion_index];
 6161            completion.documentation = Some(lsp_documentation.into());
 6162        } else {
 6163            let mut completions = completions.borrow_mut();
 6164            let completion = &mut completions[completion_index];
 6165            completion.documentation = Some(CompletionDocumentation::Undocumented);
 6166        }
 6167
 6168        let mut new_label = match completion_item {
 6169            Some(completion_item) => {
 6170                // 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
 6171                // So we have to update the label here anyway...
 6172                let language = snapshot.language();
 6173                match language {
 6174                    Some(language) => {
 6175                        adapter
 6176                            .labels_for_completions(
 6177                                std::slice::from_ref(&completion_item),
 6178                                language,
 6179                            )
 6180                            .await?
 6181                    }
 6182                    None => Vec::new(),
 6183                }
 6184                .pop()
 6185                .flatten()
 6186                .unwrap_or_else(|| {
 6187                    CodeLabel::fallback_for_completion(
 6188                        &completion_item,
 6189                        language.map(|language| language.as_ref()),
 6190                    )
 6191                })
 6192            }
 6193            None => CodeLabel::plain(
 6194                completions.borrow()[completion_index].new_text.clone(),
 6195                None,
 6196            ),
 6197        };
 6198        ensure_uniform_list_compatible_label(&mut new_label);
 6199
 6200        let mut completions = completions.borrow_mut();
 6201        let completion = &mut completions[completion_index];
 6202        if completion.label.filter_text() == new_label.filter_text() {
 6203            completion.label = new_label;
 6204        } else {
 6205            log::error!(
 6206                "Resolved completion changed display label from {} to {}. \
 6207                 Refusing to apply this because it changes the fuzzy match text from {} to {}",
 6208                completion.label.text(),
 6209                new_label.text(),
 6210                completion.label.filter_text(),
 6211                new_label.filter_text()
 6212            );
 6213        }
 6214
 6215        Ok(())
 6216    }
 6217
 6218    async fn resolve_completion_remote(
 6219        project_id: u64,
 6220        server_id: LanguageServerId,
 6221        buffer_id: BufferId,
 6222        completions: Rc<RefCell<Box<[Completion]>>>,
 6223        completion_index: usize,
 6224        client: AnyProtoClient,
 6225    ) -> Result<()> {
 6226        let lsp_completion = {
 6227            let completion = &completions.borrow()[completion_index];
 6228            match &completion.source {
 6229                CompletionSource::Lsp {
 6230                    lsp_completion,
 6231                    resolved,
 6232                    server_id: completion_server_id,
 6233                    ..
 6234                } => {
 6235                    anyhow::ensure!(
 6236                        server_id == *completion_server_id,
 6237                        "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
 6238                    );
 6239                    if *resolved {
 6240                        return Ok(());
 6241                    }
 6242                    serde_json::to_string(lsp_completion).unwrap().into_bytes()
 6243                }
 6244                CompletionSource::Custom
 6245                | CompletionSource::Dap { .. }
 6246                | CompletionSource::BufferWord { .. } => {
 6247                    return Ok(());
 6248                }
 6249            }
 6250        };
 6251        let request = proto::ResolveCompletionDocumentation {
 6252            project_id,
 6253            language_server_id: server_id.0 as u64,
 6254            lsp_completion,
 6255            buffer_id: buffer_id.into(),
 6256        };
 6257
 6258        let response = client
 6259            .request(request)
 6260            .await
 6261            .context("completion documentation resolve proto request")?;
 6262        let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
 6263
 6264        let documentation = if response.documentation.is_empty() {
 6265            CompletionDocumentation::Undocumented
 6266        } else if response.documentation_is_markdown {
 6267            CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
 6268        } else if response.documentation.lines().count() <= 1 {
 6269            CompletionDocumentation::SingleLine(response.documentation.into())
 6270        } else {
 6271            CompletionDocumentation::MultiLinePlainText(response.documentation.into())
 6272        };
 6273
 6274        let mut completions = completions.borrow_mut();
 6275        let completion = &mut completions[completion_index];
 6276        completion.documentation = Some(documentation);
 6277        if let CompletionSource::Lsp {
 6278            insert_range,
 6279            lsp_completion,
 6280            resolved,
 6281            server_id: completion_server_id,
 6282            lsp_defaults: _,
 6283        } = &mut completion.source
 6284        {
 6285            let completion_insert_range = response
 6286                .old_insert_start
 6287                .and_then(deserialize_anchor)
 6288                .zip(response.old_insert_end.and_then(deserialize_anchor));
 6289            *insert_range = completion_insert_range.map(|(start, end)| start..end);
 6290
 6291            if *resolved {
 6292                return Ok(());
 6293            }
 6294            anyhow::ensure!(
 6295                server_id == *completion_server_id,
 6296                "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
 6297            );
 6298            *lsp_completion = Box::new(resolved_lsp_completion);
 6299            *resolved = true;
 6300        }
 6301
 6302        let replace_range = response
 6303            .old_replace_start
 6304            .and_then(deserialize_anchor)
 6305            .zip(response.old_replace_end.and_then(deserialize_anchor));
 6306        if let Some((old_replace_start, old_replace_end)) = replace_range {
 6307            if !response.new_text.is_empty() {
 6308                completion.new_text = response.new_text;
 6309                completion.replace_range = old_replace_start..old_replace_end;
 6310            }
 6311        }
 6312
 6313        Ok(())
 6314    }
 6315
 6316    pub fn apply_additional_edits_for_completion(
 6317        &self,
 6318        buffer_handle: Entity<Buffer>,
 6319        completions: Rc<RefCell<Box<[Completion]>>>,
 6320        completion_index: usize,
 6321        push_to_history: bool,
 6322        cx: &mut Context<Self>,
 6323    ) -> Task<Result<Option<Transaction>>> {
 6324        if let Some((client, project_id)) = self.upstream_client() {
 6325            let buffer = buffer_handle.read(cx);
 6326            let buffer_id = buffer.remote_id();
 6327            cx.spawn(async move |_, cx| {
 6328                let request = {
 6329                    let completion = completions.borrow()[completion_index].clone();
 6330                    proto::ApplyCompletionAdditionalEdits {
 6331                        project_id,
 6332                        buffer_id: buffer_id.into(),
 6333                        completion: Some(Self::serialize_completion(&CoreCompletion {
 6334                            replace_range: completion.replace_range,
 6335                            new_text: completion.new_text,
 6336                            source: completion.source,
 6337                        })),
 6338                    }
 6339                };
 6340
 6341                if let Some(transaction) = client.request(request).await?.transaction {
 6342                    let transaction = language::proto::deserialize_transaction(transaction)?;
 6343                    buffer_handle
 6344                        .update(cx, |buffer, _| {
 6345                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 6346                        })?
 6347                        .await?;
 6348                    if push_to_history {
 6349                        buffer_handle.update(cx, |buffer, _| {
 6350                            buffer.push_transaction(transaction.clone(), Instant::now());
 6351                            buffer.finalize_last_transaction();
 6352                        })?;
 6353                    }
 6354                    Ok(Some(transaction))
 6355                } else {
 6356                    Ok(None)
 6357                }
 6358            })
 6359        } else {
 6360            let Some(server) = buffer_handle.update(cx, |buffer, cx| {
 6361                let completion = &completions.borrow()[completion_index];
 6362                let server_id = completion.source.server_id()?;
 6363                Some(
 6364                    self.language_server_for_local_buffer(buffer, server_id, cx)?
 6365                        .1
 6366                        .clone(),
 6367                )
 6368            }) else {
 6369                return Task::ready(Ok(None));
 6370            };
 6371
 6372            cx.spawn(async move |this, cx| {
 6373                Self::resolve_completion_local(
 6374                    server.clone(),
 6375                    completions.clone(),
 6376                    completion_index,
 6377                )
 6378                .await
 6379                .context("resolving completion")?;
 6380                let completion = completions.borrow()[completion_index].clone();
 6381                let additional_text_edits = completion
 6382                    .source
 6383                    .lsp_completion(true)
 6384                    .as_ref()
 6385                    .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
 6386                if let Some(edits) = additional_text_edits {
 6387                    let edits = this
 6388                        .update(cx, |this, cx| {
 6389                            this.as_local_mut().unwrap().edits_from_lsp(
 6390                                &buffer_handle,
 6391                                edits,
 6392                                server.server_id(),
 6393                                None,
 6394                                cx,
 6395                            )
 6396                        })?
 6397                        .await?;
 6398
 6399                    buffer_handle.update(cx, |buffer, cx| {
 6400                        buffer.finalize_last_transaction();
 6401                        buffer.start_transaction();
 6402
 6403                        for (range, text) in edits {
 6404                            let primary = &completion.replace_range;
 6405                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 6406                                && primary.end.cmp(&range.start, buffer).is_ge();
 6407                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 6408                                && range.end.cmp(&primary.end, buffer).is_ge();
 6409
 6410                            //Skip additional edits which overlap with the primary completion edit
 6411                            //https://github.com/zed-industries/zed/pull/1871
 6412                            if !start_within && !end_within {
 6413                                buffer.edit([(range, text)], None, cx);
 6414                            }
 6415                        }
 6416
 6417                        let transaction = if buffer.end_transaction(cx).is_some() {
 6418                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6419                            if !push_to_history {
 6420                                buffer.forget_transaction(transaction.id);
 6421                            }
 6422                            Some(transaction)
 6423                        } else {
 6424                            None
 6425                        };
 6426                        Ok(transaction)
 6427                    })?
 6428                } else {
 6429                    Ok(None)
 6430                }
 6431            })
 6432        }
 6433    }
 6434
 6435    pub fn pull_diagnostics(
 6436        &mut self,
 6437        buffer_handle: Entity<Buffer>,
 6438        cx: &mut Context<Self>,
 6439    ) -> Task<Result<Vec<LspPullDiagnostics>>> {
 6440        let buffer = buffer_handle.read(cx);
 6441        let buffer_id = buffer.remote_id();
 6442
 6443        if let Some((client, upstream_project_id)) = self.upstream_client() {
 6444            let request_task = client.request(proto::MultiLspQuery {
 6445                buffer_id: buffer_id.to_proto(),
 6446                version: serialize_version(&buffer_handle.read(cx).version()),
 6447                project_id: upstream_project_id,
 6448                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6449                    proto::AllLanguageServers {},
 6450                )),
 6451                request: Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(
 6452                    proto::GetDocumentDiagnostics {
 6453                        project_id: upstream_project_id,
 6454                        buffer_id: buffer_id.to_proto(),
 6455                        version: serialize_version(&buffer_handle.read(cx).version()),
 6456                    },
 6457                )),
 6458            });
 6459            cx.background_spawn(async move {
 6460                Ok(request_task
 6461                    .await?
 6462                    .responses
 6463                    .into_iter()
 6464                    .filter_map(|lsp_response| match lsp_response.response? {
 6465                        proto::lsp_response::Response::GetDocumentDiagnosticsResponse(response) => {
 6466                            Some(response)
 6467                        }
 6468                        unexpected => {
 6469                            debug_panic!("Unexpected response: {unexpected:?}");
 6470                            None
 6471                        }
 6472                    })
 6473                    .flat_map(GetDocumentDiagnostics::diagnostics_from_proto)
 6474                    .collect())
 6475            })
 6476        } else {
 6477            let server_ids = buffer_handle.update(cx, |buffer, cx| {
 6478                self.language_servers_for_local_buffer(buffer, cx)
 6479                    .map(|(_, server)| server.server_id())
 6480                    .collect::<Vec<_>>()
 6481            });
 6482            let pull_diagnostics = server_ids
 6483                .into_iter()
 6484                .map(|server_id| {
 6485                    let result_id = self.result_id(server_id, buffer_id, cx);
 6486                    self.request_lsp(
 6487                        buffer_handle.clone(),
 6488                        LanguageServerToQuery::Other(server_id),
 6489                        GetDocumentDiagnostics {
 6490                            previous_result_id: result_id,
 6491                        },
 6492                        cx,
 6493                    )
 6494                })
 6495                .collect::<Vec<_>>();
 6496
 6497            cx.background_spawn(async move {
 6498                let mut responses = Vec::new();
 6499                for diagnostics in join_all(pull_diagnostics).await {
 6500                    responses.extend(diagnostics?);
 6501                }
 6502                Ok(responses)
 6503            })
 6504        }
 6505    }
 6506
 6507    pub fn inlay_hints(
 6508        &mut self,
 6509        buffer_handle: Entity<Buffer>,
 6510        range: Range<Anchor>,
 6511        cx: &mut Context<Self>,
 6512    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6513        let buffer = buffer_handle.read(cx);
 6514        let range_start = range.start;
 6515        let range_end = range.end;
 6516        let buffer_id = buffer.remote_id().into();
 6517        let lsp_request = InlayHints { range };
 6518
 6519        if let Some((client, project_id)) = self.upstream_client() {
 6520            let request = proto::InlayHints {
 6521                project_id,
 6522                buffer_id,
 6523                start: Some(serialize_anchor(&range_start)),
 6524                end: Some(serialize_anchor(&range_end)),
 6525                version: serialize_version(&buffer_handle.read(cx).version()),
 6526            };
 6527            cx.spawn(async move |project, cx| {
 6528                let response = client
 6529                    .request(request)
 6530                    .await
 6531                    .context("inlay hints proto request")?;
 6532                LspCommand::response_from_proto(
 6533                    lsp_request,
 6534                    response,
 6535                    project.upgrade().context("No project")?,
 6536                    buffer_handle.clone(),
 6537                    cx.clone(),
 6538                )
 6539                .await
 6540                .context("inlay hints proto response conversion")
 6541            })
 6542        } else {
 6543            let lsp_request_task = self.request_lsp(
 6544                buffer_handle.clone(),
 6545                LanguageServerToQuery::FirstCapable,
 6546                lsp_request,
 6547                cx,
 6548            );
 6549            cx.spawn(async move |_, cx| {
 6550                buffer_handle
 6551                    .update(cx, |buffer, _| {
 6552                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 6553                    })?
 6554                    .await
 6555                    .context("waiting for inlay hint request range edits")?;
 6556                lsp_request_task.await.context("inlay hints LSP request")
 6557            })
 6558        }
 6559    }
 6560
 6561    pub fn pull_diagnostics_for_buffer(
 6562        &mut self,
 6563        buffer: Entity<Buffer>,
 6564        cx: &mut Context<Self>,
 6565    ) -> Task<anyhow::Result<()>> {
 6566        let buffer_id = buffer.read(cx).remote_id();
 6567        let diagnostics = self.pull_diagnostics(buffer, cx);
 6568        cx.spawn(async move |lsp_store, cx| {
 6569            let diagnostics = diagnostics.await.context("pulling diagnostics")?;
 6570            lsp_store.update(cx, |lsp_store, cx| {
 6571                if lsp_store.as_local().is_none() {
 6572                    return;
 6573                }
 6574
 6575                for diagnostics_set in diagnostics {
 6576                    let LspPullDiagnostics::Response {
 6577                        server_id,
 6578                        uri,
 6579                        diagnostics,
 6580                    } = diagnostics_set
 6581                    else {
 6582                        continue;
 6583                    };
 6584
 6585                    let adapter = lsp_store.language_server_adapter_for_id(server_id);
 6586                    let disk_based_sources = adapter
 6587                        .as_ref()
 6588                        .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
 6589                        .unwrap_or(&[]);
 6590                    match diagnostics {
 6591                        PulledDiagnostics::Unchanged { result_id } => {
 6592                            lsp_store
 6593                                .merge_diagnostics(
 6594                                    server_id,
 6595                                    lsp::PublishDiagnosticsParams {
 6596                                        uri: uri.clone(),
 6597                                        diagnostics: Vec::new(),
 6598                                        version: None,
 6599                                    },
 6600                                    Some(result_id),
 6601                                    DiagnosticSourceKind::Pulled,
 6602                                    disk_based_sources,
 6603                                    |_, _, _| true,
 6604                                    cx,
 6605                                )
 6606                                .log_err();
 6607                        }
 6608                        PulledDiagnostics::Changed {
 6609                            diagnostics,
 6610                            result_id,
 6611                        } => {
 6612                            lsp_store
 6613                                .merge_diagnostics(
 6614                                    server_id,
 6615                                    lsp::PublishDiagnosticsParams {
 6616                                        uri: uri.clone(),
 6617                                        diagnostics,
 6618                                        version: None,
 6619                                    },
 6620                                    result_id,
 6621                                    DiagnosticSourceKind::Pulled,
 6622                                    disk_based_sources,
 6623                                    |buffer, old_diagnostic, _| match old_diagnostic.source_kind {
 6624                                        DiagnosticSourceKind::Pulled => {
 6625                                            buffer.remote_id() != buffer_id
 6626                                        }
 6627                                        DiagnosticSourceKind::Other
 6628                                        | DiagnosticSourceKind::Pushed => true,
 6629                                    },
 6630                                    cx,
 6631                                )
 6632                                .log_err();
 6633                        }
 6634                    }
 6635                }
 6636            })
 6637        })
 6638    }
 6639
 6640    pub fn document_colors(
 6641        &mut self,
 6642        fetch_strategy: LspFetchStrategy,
 6643        buffer: Entity<Buffer>,
 6644        cx: &mut Context<Self>,
 6645    ) -> Option<DocumentColorTask> {
 6646        let version_queried_for = buffer.read(cx).version();
 6647        let buffer_id = buffer.read(cx).remote_id();
 6648
 6649        match fetch_strategy {
 6650            LspFetchStrategy::IgnoreCache => {}
 6651            LspFetchStrategy::UseCache {
 6652                known_cache_version,
 6653            } => {
 6654                if let Some(cached_data) = self.lsp_document_colors.get(&buffer_id) {
 6655                    if !version_queried_for.changed_since(&cached_data.colors_for_version) {
 6656                        let has_different_servers = self.as_local().is_some_and(|local| {
 6657                            local
 6658                                .buffers_opened_in_servers
 6659                                .get(&buffer_id)
 6660                                .cloned()
 6661                                .unwrap_or_default()
 6662                                != cached_data.colors.keys().copied().collect()
 6663                        });
 6664                        if !has_different_servers {
 6665                            if Some(cached_data.cache_version) == known_cache_version {
 6666                                return None;
 6667                            } else {
 6668                                return Some(
 6669                                    Task::ready(Ok(DocumentColors {
 6670                                        colors: cached_data
 6671                                            .colors
 6672                                            .values()
 6673                                            .flatten()
 6674                                            .cloned()
 6675                                            .collect(),
 6676                                        cache_version: Some(cached_data.cache_version),
 6677                                    }))
 6678                                    .shared(),
 6679                                );
 6680                            }
 6681                        }
 6682                    }
 6683                }
 6684            }
 6685        }
 6686
 6687        let lsp_data = self.lsp_document_colors.entry(buffer_id).or_default();
 6688        if let Some((updating_for, running_update)) = &lsp_data.colors_update {
 6689            if !version_queried_for.changed_since(&updating_for) {
 6690                return Some(running_update.clone());
 6691            }
 6692        }
 6693        let query_version_queried_for = version_queried_for.clone();
 6694        let new_task = cx
 6695            .spawn(async move |lsp_store, cx| {
 6696                cx.background_executor()
 6697                    .timer(Duration::from_millis(30))
 6698                    .await;
 6699                let fetched_colors = lsp_store
 6700                    .update(cx, |lsp_store, cx| {
 6701                        lsp_store.fetch_document_colors_for_buffer(&buffer, cx)
 6702                    })?
 6703                    .await
 6704                    .context("fetching document colors")
 6705                    .map_err(Arc::new);
 6706                let fetched_colors = match fetched_colors {
 6707                    Ok(fetched_colors) => {
 6708                        if fetch_strategy != LspFetchStrategy::IgnoreCache
 6709                            && Some(true)
 6710                                == buffer
 6711                                    .update(cx, |buffer, _| {
 6712                                        buffer.version() != query_version_queried_for
 6713                                    })
 6714                                    .ok()
 6715                        {
 6716                            return Ok(DocumentColors::default());
 6717                        }
 6718                        fetched_colors
 6719                    }
 6720                    Err(e) => {
 6721                        lsp_store
 6722                            .update(cx, |lsp_store, _| {
 6723                                lsp_store
 6724                                    .lsp_document_colors
 6725                                    .entry(buffer_id)
 6726                                    .or_default()
 6727                                    .colors_update = None;
 6728                            })
 6729                            .ok();
 6730                        return Err(e);
 6731                    }
 6732                };
 6733
 6734                lsp_store
 6735                    .update(cx, |lsp_store, _| {
 6736                        let lsp_data = lsp_store.lsp_document_colors.entry(buffer_id).or_default();
 6737
 6738                        if lsp_data.colors_for_version == query_version_queried_for {
 6739                            lsp_data.colors.extend(fetched_colors.clone());
 6740                            lsp_data.cache_version += 1;
 6741                        } else if !lsp_data
 6742                            .colors_for_version
 6743                            .changed_since(&query_version_queried_for)
 6744                        {
 6745                            lsp_data.colors_for_version = query_version_queried_for;
 6746                            lsp_data.colors = fetched_colors.clone();
 6747                            lsp_data.cache_version += 1;
 6748                        }
 6749                        lsp_data.colors_update = None;
 6750                        let colors = lsp_data
 6751                            .colors
 6752                            .values()
 6753                            .flatten()
 6754                            .cloned()
 6755                            .collect::<HashSet<_>>();
 6756                        DocumentColors {
 6757                            colors,
 6758                            cache_version: Some(lsp_data.cache_version),
 6759                        }
 6760                    })
 6761                    .map_err(Arc::new)
 6762            })
 6763            .shared();
 6764        lsp_data.colors_update = Some((version_queried_for, new_task.clone()));
 6765        Some(new_task)
 6766    }
 6767
 6768    fn fetch_document_colors_for_buffer(
 6769        &mut self,
 6770        buffer: &Entity<Buffer>,
 6771        cx: &mut Context<Self>,
 6772    ) -> Task<anyhow::Result<HashMap<LanguageServerId, HashSet<DocumentColor>>>> {
 6773        if let Some((client, project_id)) = self.upstream_client() {
 6774            let request_task = client.request(proto::MultiLspQuery {
 6775                project_id,
 6776                buffer_id: buffer.read(cx).remote_id().to_proto(),
 6777                version: serialize_version(&buffer.read(cx).version()),
 6778                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6779                    proto::AllLanguageServers {},
 6780                )),
 6781                request: Some(proto::multi_lsp_query::Request::GetDocumentColor(
 6782                    GetDocumentColor {}.to_proto(project_id, buffer.read(cx)),
 6783                )),
 6784            });
 6785            let buffer = buffer.clone();
 6786            cx.spawn(async move |project, cx| {
 6787                let Some(project) = project.upgrade() else {
 6788                    return Ok(HashMap::default());
 6789                };
 6790                let colors = join_all(
 6791                    request_task
 6792                        .await
 6793                        .log_err()
 6794                        .map(|response| response.responses)
 6795                        .unwrap_or_default()
 6796                        .into_iter()
 6797                        .filter_map(|lsp_response| match lsp_response.response? {
 6798                            proto::lsp_response::Response::GetDocumentColorResponse(response) => {
 6799                                Some((
 6800                                    LanguageServerId::from_proto(lsp_response.server_id),
 6801                                    response,
 6802                                ))
 6803                            }
 6804                            unexpected => {
 6805                                debug_panic!("Unexpected response: {unexpected:?}");
 6806                                None
 6807                            }
 6808                        })
 6809                        .map(|(server_id, color_response)| {
 6810                            let response = GetDocumentColor {}.response_from_proto(
 6811                                color_response,
 6812                                project.clone(),
 6813                                buffer.clone(),
 6814                                cx.clone(),
 6815                            );
 6816                            async move { (server_id, response.await.log_err().unwrap_or_default()) }
 6817                        }),
 6818                )
 6819                .await
 6820                .into_iter()
 6821                .fold(HashMap::default(), |mut acc, (server_id, colors)| {
 6822                    acc.entry(server_id)
 6823                        .or_insert_with(HashSet::default)
 6824                        .extend(colors);
 6825                    acc
 6826                });
 6827                Ok(colors)
 6828            })
 6829        } else {
 6830            let document_colors_task =
 6831                self.request_multiple_lsp_locally(buffer, None::<usize>, GetDocumentColor, cx);
 6832            cx.background_spawn(async move {
 6833                Ok(document_colors_task
 6834                    .await
 6835                    .into_iter()
 6836                    .fold(HashMap::default(), |mut acc, (server_id, colors)| {
 6837                        acc.entry(server_id)
 6838                            .or_insert_with(HashSet::default)
 6839                            .extend(colors);
 6840                        acc
 6841                    })
 6842                    .into_iter()
 6843                    .collect())
 6844            })
 6845        }
 6846    }
 6847
 6848    pub fn signature_help<T: ToPointUtf16>(
 6849        &mut self,
 6850        buffer: &Entity<Buffer>,
 6851        position: T,
 6852        cx: &mut Context<Self>,
 6853    ) -> Task<Vec<SignatureHelp>> {
 6854        let position = position.to_point_utf16(buffer.read(cx));
 6855
 6856        if let Some((client, upstream_project_id)) = self.upstream_client() {
 6857            let request_task = client.request(proto::MultiLspQuery {
 6858                buffer_id: buffer.read(cx).remote_id().into(),
 6859                version: serialize_version(&buffer.read(cx).version()),
 6860                project_id: upstream_project_id,
 6861                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6862                    proto::AllLanguageServers {},
 6863                )),
 6864                request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
 6865                    GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
 6866                )),
 6867            });
 6868            let buffer = buffer.clone();
 6869            cx.spawn(async move |weak_project, cx| {
 6870                let Some(project) = weak_project.upgrade() else {
 6871                    return Vec::new();
 6872                };
 6873                join_all(
 6874                    request_task
 6875                        .await
 6876                        .log_err()
 6877                        .map(|response| response.responses)
 6878                        .unwrap_or_default()
 6879                        .into_iter()
 6880                        .filter_map(|lsp_response| match lsp_response.response? {
 6881                            proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
 6882                                Some(response)
 6883                            }
 6884                            unexpected => {
 6885                                debug_panic!("Unexpected response: {unexpected:?}");
 6886                                None
 6887                            }
 6888                        })
 6889                        .map(|signature_response| {
 6890                            let response = GetSignatureHelp { position }.response_from_proto(
 6891                                signature_response,
 6892                                project.clone(),
 6893                                buffer.clone(),
 6894                                cx.clone(),
 6895                            );
 6896                            async move { response.await.log_err().flatten() }
 6897                        }),
 6898                )
 6899                .await
 6900                .into_iter()
 6901                .flatten()
 6902                .collect()
 6903            })
 6904        } else {
 6905            let all_actions_task = self.request_multiple_lsp_locally(
 6906                buffer,
 6907                Some(position),
 6908                GetSignatureHelp { position },
 6909                cx,
 6910            );
 6911            cx.background_spawn(async move {
 6912                all_actions_task
 6913                    .await
 6914                    .into_iter()
 6915                    .flat_map(|(_, actions)| actions)
 6916                    .collect::<Vec<_>>()
 6917            })
 6918        }
 6919    }
 6920
 6921    pub fn hover(
 6922        &mut self,
 6923        buffer: &Entity<Buffer>,
 6924        position: PointUtf16,
 6925        cx: &mut Context<Self>,
 6926    ) -> Task<Vec<Hover>> {
 6927        if let Some((client, upstream_project_id)) = self.upstream_client() {
 6928            let request_task = client.request(proto::MultiLspQuery {
 6929                buffer_id: buffer.read(cx).remote_id().into(),
 6930                version: serialize_version(&buffer.read(cx).version()),
 6931                project_id: upstream_project_id,
 6932                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6933                    proto::AllLanguageServers {},
 6934                )),
 6935                request: Some(proto::multi_lsp_query::Request::GetHover(
 6936                    GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
 6937                )),
 6938            });
 6939            let buffer = buffer.clone();
 6940            cx.spawn(async move |weak_project, cx| {
 6941                let Some(project) = weak_project.upgrade() else {
 6942                    return Vec::new();
 6943                };
 6944                join_all(
 6945                    request_task
 6946                        .await
 6947                        .log_err()
 6948                        .map(|response| response.responses)
 6949                        .unwrap_or_default()
 6950                        .into_iter()
 6951                        .filter_map(|lsp_response| match lsp_response.response? {
 6952                            proto::lsp_response::Response::GetHoverResponse(response) => {
 6953                                Some(response)
 6954                            }
 6955                            unexpected => {
 6956                                debug_panic!("Unexpected response: {unexpected:?}");
 6957                                None
 6958                            }
 6959                        })
 6960                        .map(|hover_response| {
 6961                            let response = GetHover { position }.response_from_proto(
 6962                                hover_response,
 6963                                project.clone(),
 6964                                buffer.clone(),
 6965                                cx.clone(),
 6966                            );
 6967                            async move {
 6968                                response
 6969                                    .await
 6970                                    .log_err()
 6971                                    .flatten()
 6972                                    .and_then(remove_empty_hover_blocks)
 6973                            }
 6974                        }),
 6975                )
 6976                .await
 6977                .into_iter()
 6978                .flatten()
 6979                .collect()
 6980            })
 6981        } else {
 6982            let all_actions_task = self.request_multiple_lsp_locally(
 6983                buffer,
 6984                Some(position),
 6985                GetHover { position },
 6986                cx,
 6987            );
 6988            cx.background_spawn(async move {
 6989                all_actions_task
 6990                    .await
 6991                    .into_iter()
 6992                    .filter_map(|(_, hover)| remove_empty_hover_blocks(hover?))
 6993                    .collect::<Vec<Hover>>()
 6994            })
 6995        }
 6996    }
 6997
 6998    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
 6999        let language_registry = self.languages.clone();
 7000
 7001        if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
 7002            let request = upstream_client.request(proto::GetProjectSymbols {
 7003                project_id: *project_id,
 7004                query: query.to_string(),
 7005            });
 7006            cx.foreground_executor().spawn(async move {
 7007                let response = request.await?;
 7008                let mut symbols = Vec::new();
 7009                let core_symbols = response
 7010                    .symbols
 7011                    .into_iter()
 7012                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 7013                    .collect::<Vec<_>>();
 7014                populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
 7015                    .await;
 7016                Ok(symbols)
 7017            })
 7018        } else if let Some(local) = self.as_local() {
 7019            struct WorkspaceSymbolsResult {
 7020                server_id: LanguageServerId,
 7021                lsp_adapter: Arc<CachedLspAdapter>,
 7022                worktree: WeakEntity<Worktree>,
 7023                worktree_abs_path: Arc<Path>,
 7024                lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
 7025            }
 7026
 7027            let mut requests = Vec::new();
 7028            let mut requested_servers = BTreeSet::new();
 7029            'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
 7030                let Some(worktree_handle) = self
 7031                    .worktree_store
 7032                    .read(cx)
 7033                    .worktree_for_id(*worktree_id, cx)
 7034                else {
 7035                    continue;
 7036                };
 7037                let worktree = worktree_handle.read(cx);
 7038                if !worktree.is_visible() {
 7039                    continue;
 7040                }
 7041
 7042                let mut servers_to_query = server_ids
 7043                    .difference(&requested_servers)
 7044                    .cloned()
 7045                    .collect::<BTreeSet<_>>();
 7046                for server_id in &servers_to_query {
 7047                    let (lsp_adapter, server) = match local.language_servers.get(server_id) {
 7048                        Some(LanguageServerState::Running {
 7049                            adapter, server, ..
 7050                        }) => (adapter.clone(), server),
 7051
 7052                        _ => continue 'next_server,
 7053                    };
 7054                    let supports_workspace_symbol_request =
 7055                        match server.capabilities().workspace_symbol_provider {
 7056                            Some(OneOf::Left(supported)) => supported,
 7057                            Some(OneOf::Right(_)) => true,
 7058                            None => false,
 7059                        };
 7060                    if !supports_workspace_symbol_request {
 7061                        continue 'next_server;
 7062                    }
 7063                    let worktree_abs_path = worktree.abs_path().clone();
 7064                    let worktree_handle = worktree_handle.clone();
 7065                    let server_id = server.server_id();
 7066                    requests.push(
 7067                        server
 7068                            .request::<lsp::request::WorkspaceSymbolRequest>(
 7069                                lsp::WorkspaceSymbolParams {
 7070                                    query: query.to_string(),
 7071                                    ..Default::default()
 7072                                },
 7073                            )
 7074                            .map(move |response| {
 7075                                let lsp_symbols = response.into_response()
 7076                                    .context("workspace symbols request")
 7077                                    .log_err()
 7078                                    .flatten()
 7079                                    .map(|symbol_response| match symbol_response {
 7080                                        lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 7081                                            flat_responses.into_iter().map(|lsp_symbol| {
 7082                                            (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 7083                                            }).collect::<Vec<_>>()
 7084                                        }
 7085                                        lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 7086                                            nested_responses.into_iter().filter_map(|lsp_symbol| {
 7087                                                let location = match lsp_symbol.location {
 7088                                                    OneOf::Left(location) => location,
 7089                                                    OneOf::Right(_) => {
 7090                                                        log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 7091                                                        return None
 7092                                                    }
 7093                                                };
 7094                                                Some((lsp_symbol.name, lsp_symbol.kind, location))
 7095                                            }).collect::<Vec<_>>()
 7096                                        }
 7097                                    }).unwrap_or_default();
 7098
 7099                                WorkspaceSymbolsResult {
 7100                                    server_id,
 7101                                    lsp_adapter,
 7102                                    worktree: worktree_handle.downgrade(),
 7103                                    worktree_abs_path,
 7104                                    lsp_symbols,
 7105                                }
 7106                            }),
 7107                    );
 7108                }
 7109                requested_servers.append(&mut servers_to_query);
 7110            }
 7111
 7112            cx.spawn(async move |this, cx| {
 7113                let responses = futures::future::join_all(requests).await;
 7114                let this = match this.upgrade() {
 7115                    Some(this) => this,
 7116                    None => return Ok(Vec::new()),
 7117                };
 7118
 7119                let mut symbols = Vec::new();
 7120                for result in responses {
 7121                    let core_symbols = this.update(cx, |this, cx| {
 7122                        result
 7123                            .lsp_symbols
 7124                            .into_iter()
 7125                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 7126                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 7127                                let source_worktree = result.worktree.upgrade()?;
 7128                                let source_worktree_id = source_worktree.read(cx).id();
 7129
 7130                                let path;
 7131                                let worktree;
 7132                                if let Some((tree, rel_path)) =
 7133                                    this.worktree_store.read(cx).find_worktree(&abs_path, cx)
 7134                                {
 7135                                    worktree = tree;
 7136                                    path = rel_path;
 7137                                } else {
 7138                                    worktree = source_worktree.clone();
 7139                                    path = relativize_path(&result.worktree_abs_path, &abs_path);
 7140                                }
 7141
 7142                                let worktree_id = worktree.read(cx).id();
 7143                                let project_path = ProjectPath {
 7144                                    worktree_id,
 7145                                    path: path.into(),
 7146                                };
 7147                                let signature = this.symbol_signature(&project_path);
 7148                                Some(CoreSymbol {
 7149                                    source_language_server_id: result.server_id,
 7150                                    language_server_name: result.lsp_adapter.name.clone(),
 7151                                    source_worktree_id,
 7152                                    path: project_path,
 7153                                    kind: symbol_kind,
 7154                                    name: symbol_name,
 7155                                    range: range_from_lsp(symbol_location.range),
 7156                                    signature,
 7157                                })
 7158                            })
 7159                            .collect()
 7160                    })?;
 7161
 7162                    populate_labels_for_symbols(
 7163                        core_symbols,
 7164                        &language_registry,
 7165                        Some(result.lsp_adapter),
 7166                        &mut symbols,
 7167                    )
 7168                    .await;
 7169                }
 7170
 7171                Ok(symbols)
 7172            })
 7173        } else {
 7174            Task::ready(Err(anyhow!("No upstream client or local language server")))
 7175        }
 7176    }
 7177
 7178    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
 7179        let mut summary = DiagnosticSummary::default();
 7180        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 7181            summary.error_count += path_summary.error_count;
 7182            summary.warning_count += path_summary.warning_count;
 7183        }
 7184        summary
 7185    }
 7186
 7187    pub fn diagnostic_summaries<'a>(
 7188        &'a self,
 7189        include_ignored: bool,
 7190        cx: &'a App,
 7191    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 7192        self.worktree_store
 7193            .read(cx)
 7194            .visible_worktrees(cx)
 7195            .filter_map(|worktree| {
 7196                let worktree = worktree.read(cx);
 7197                Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
 7198            })
 7199            .flat_map(move |(worktree, summaries)| {
 7200                let worktree_id = worktree.id();
 7201                summaries
 7202                    .iter()
 7203                    .filter(move |(path, _)| {
 7204                        include_ignored
 7205                            || worktree
 7206                                .entry_for_path(path.as_ref())
 7207                                .map_or(false, |entry| !entry.is_ignored)
 7208                    })
 7209                    .flat_map(move |(path, summaries)| {
 7210                        summaries.iter().map(move |(server_id, summary)| {
 7211                            (
 7212                                ProjectPath {
 7213                                    worktree_id,
 7214                                    path: path.clone(),
 7215                                },
 7216                                *server_id,
 7217                                *summary,
 7218                            )
 7219                        })
 7220                    })
 7221            })
 7222    }
 7223
 7224    pub fn on_buffer_edited(
 7225        &mut self,
 7226        buffer: Entity<Buffer>,
 7227        cx: &mut Context<Self>,
 7228    ) -> Option<()> {
 7229        let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
 7230            Some(
 7231                self.as_local()?
 7232                    .language_servers_for_buffer(buffer, cx)
 7233                    .map(|i| i.1.clone())
 7234                    .collect(),
 7235            )
 7236        })?;
 7237
 7238        let buffer = buffer.read(cx);
 7239        let file = File::from_dyn(buffer.file())?;
 7240        let abs_path = file.as_local()?.abs_path(cx);
 7241        let uri = lsp::Url::from_file_path(abs_path).unwrap();
 7242        let next_snapshot = buffer.text_snapshot();
 7243        for language_server in language_servers {
 7244            let language_server = language_server.clone();
 7245
 7246            let buffer_snapshots = self
 7247                .as_local_mut()
 7248                .unwrap()
 7249                .buffer_snapshots
 7250                .get_mut(&buffer.remote_id())
 7251                .and_then(|m| m.get_mut(&language_server.server_id()))?;
 7252            let previous_snapshot = buffer_snapshots.last()?;
 7253
 7254            let build_incremental_change = || {
 7255                buffer
 7256                    .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
 7257                    .map(|edit| {
 7258                        let edit_start = edit.new.start.0;
 7259                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 7260                        let new_text = next_snapshot
 7261                            .text_for_range(edit.new.start.1..edit.new.end.1)
 7262                            .collect();
 7263                        lsp::TextDocumentContentChangeEvent {
 7264                            range: Some(lsp::Range::new(
 7265                                point_to_lsp(edit_start),
 7266                                point_to_lsp(edit_end),
 7267                            )),
 7268                            range_length: None,
 7269                            text: new_text,
 7270                        }
 7271                    })
 7272                    .collect()
 7273            };
 7274
 7275            let document_sync_kind = language_server
 7276                .capabilities()
 7277                .text_document_sync
 7278                .as_ref()
 7279                .and_then(|sync| match sync {
 7280                    lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 7281                    lsp::TextDocumentSyncCapability::Options(options) => options.change,
 7282                });
 7283
 7284            let content_changes: Vec<_> = match document_sync_kind {
 7285                Some(lsp::TextDocumentSyncKind::FULL) => {
 7286                    vec![lsp::TextDocumentContentChangeEvent {
 7287                        range: None,
 7288                        range_length: None,
 7289                        text: next_snapshot.text(),
 7290                    }]
 7291                }
 7292                Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 7293                _ => {
 7294                    #[cfg(any(test, feature = "test-support"))]
 7295                    {
 7296                        build_incremental_change()
 7297                    }
 7298
 7299                    #[cfg(not(any(test, feature = "test-support")))]
 7300                    {
 7301                        continue;
 7302                    }
 7303                }
 7304            };
 7305
 7306            let next_version = previous_snapshot.version + 1;
 7307            buffer_snapshots.push(LspBufferSnapshot {
 7308                version: next_version,
 7309                snapshot: next_snapshot.clone(),
 7310            });
 7311
 7312            language_server
 7313                .notify::<lsp::notification::DidChangeTextDocument>(
 7314                    &lsp::DidChangeTextDocumentParams {
 7315                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 7316                            uri.clone(),
 7317                            next_version,
 7318                        ),
 7319                        content_changes,
 7320                    },
 7321                )
 7322                .ok();
 7323            self.pull_workspace_diagnostics(language_server.server_id());
 7324        }
 7325
 7326        None
 7327    }
 7328
 7329    pub fn on_buffer_saved(
 7330        &mut self,
 7331        buffer: Entity<Buffer>,
 7332        cx: &mut Context<Self>,
 7333    ) -> Option<()> {
 7334        let file = File::from_dyn(buffer.read(cx).file())?;
 7335        let worktree_id = file.worktree_id(cx);
 7336        let abs_path = file.as_local()?.abs_path(cx);
 7337        let text_document = lsp::TextDocumentIdentifier {
 7338            uri: file_path_to_lsp_url(&abs_path).log_err()?,
 7339        };
 7340        let local = self.as_local()?;
 7341
 7342        for server in local.language_servers_for_worktree(worktree_id) {
 7343            if let Some(include_text) = include_text(server.as_ref()) {
 7344                let text = if include_text {
 7345                    Some(buffer.read(cx).text())
 7346                } else {
 7347                    None
 7348                };
 7349                server
 7350                    .notify::<lsp::notification::DidSaveTextDocument>(
 7351                        &lsp::DidSaveTextDocumentParams {
 7352                            text_document: text_document.clone(),
 7353                            text,
 7354                        },
 7355                    )
 7356                    .ok();
 7357            }
 7358        }
 7359
 7360        let language_servers = buffer.update(cx, |buffer, cx| {
 7361            local.language_server_ids_for_buffer(buffer, cx)
 7362        });
 7363        for language_server_id in language_servers {
 7364            self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
 7365        }
 7366
 7367        None
 7368    }
 7369
 7370    pub(crate) async fn refresh_workspace_configurations(
 7371        lsp_store: &WeakEntity<Self>,
 7372        fs: Arc<dyn Fs>,
 7373        cx: &mut AsyncApp,
 7374    ) {
 7375        maybe!(async move {
 7376            let mut refreshed_servers = HashSet::default();
 7377            let servers = lsp_store
 7378                .update(cx, |lsp_store, cx| {
 7379                    let toolchain_store = lsp_store.toolchain_store(cx);
 7380                    let Some(local) = lsp_store.as_local() else {
 7381                        return Vec::default();
 7382                    };
 7383                    local
 7384                        .language_server_ids
 7385                        .iter()
 7386                        .flat_map(|((worktree_id, _), server_ids)| {
 7387                            let worktree = lsp_store
 7388                                .worktree_store
 7389                                .read(cx)
 7390                                .worktree_for_id(*worktree_id, cx);
 7391                            let delegate = worktree.map(|worktree| {
 7392                                LocalLspAdapterDelegate::new(
 7393                                    local.languages.clone(),
 7394                                    &local.environment,
 7395                                    cx.weak_entity(),
 7396                                    &worktree,
 7397                                    local.http_client.clone(),
 7398                                    local.fs.clone(),
 7399                                    cx,
 7400                                )
 7401                            });
 7402
 7403                            let fs = fs.clone();
 7404                            let toolchain_store = toolchain_store.clone();
 7405                            server_ids.iter().filter_map(|server_id| {
 7406                                let delegate = delegate.clone()? as Arc<dyn LspAdapterDelegate>;
 7407                                let states = local.language_servers.get(server_id)?;
 7408
 7409                                match states {
 7410                                    LanguageServerState::Starting { .. } => None,
 7411                                    LanguageServerState::Running {
 7412                                        adapter, server, ..
 7413                                    } => {
 7414                                        let fs = fs.clone();
 7415                                        let toolchain_store = toolchain_store.clone();
 7416                                        let adapter = adapter.clone();
 7417                                        let server = server.clone();
 7418                                        refreshed_servers.insert(server.name());
 7419                                        Some(cx.spawn(async move |_, cx| {
 7420                                            let settings =
 7421                                                LocalLspStore::workspace_configuration_for_adapter(
 7422                                                    adapter.adapter.clone(),
 7423                                                    fs.as_ref(),
 7424                                                    &delegate,
 7425                                                    toolchain_store,
 7426                                                    cx,
 7427                                                )
 7428                                                .await
 7429                                                .ok()?;
 7430                                            server
 7431                                                .notify::<lsp::notification::DidChangeConfiguration>(
 7432                                                    &lsp::DidChangeConfigurationParams { settings },
 7433                                                )
 7434                                                .ok()?;
 7435                                            Some(())
 7436                                        }))
 7437                                    }
 7438                                }
 7439                            }).collect::<Vec<_>>()
 7440                        })
 7441                        .collect::<Vec<_>>()
 7442                })
 7443                .ok()?;
 7444
 7445            log::info!("Refreshing workspace configurations for servers {refreshed_servers:?}");
 7446            // TODO this asynchronous job runs concurrently with extension (de)registration and may take enough time for a certain extension
 7447            // to stop and unregister its language server wrapper.
 7448            // This is racy : an extension might have already removed all `local.language_servers` state, but here we `.clone()` and hold onto it anyway.
 7449            // This now causes errors in the logs, we should find a way to remove such servers from the processing everywhere.
 7450            let _: Vec<Option<()>> = join_all(servers).await;
 7451            Some(())
 7452        })
 7453        .await;
 7454    }
 7455
 7456    fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
 7457        if let Some(toolchain_store) = self.toolchain_store.as_ref() {
 7458            toolchain_store.read(cx).as_language_toolchain_store()
 7459        } else {
 7460            Arc::new(EmptyToolchainStore)
 7461        }
 7462    }
 7463    fn maintain_workspace_config(
 7464        fs: Arc<dyn Fs>,
 7465        external_refresh_requests: watch::Receiver<()>,
 7466        cx: &mut Context<Self>,
 7467    ) -> Task<Result<()>> {
 7468        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 7469        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 7470
 7471        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 7472            *settings_changed_tx.borrow_mut() = ();
 7473        });
 7474
 7475        let mut joint_future =
 7476            futures::stream::select(settings_changed_rx, external_refresh_requests);
 7477        cx.spawn(async move |this, cx| {
 7478            while let Some(()) = joint_future.next().await {
 7479                Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
 7480            }
 7481
 7482            drop(settings_observation);
 7483            anyhow::Ok(())
 7484        })
 7485    }
 7486
 7487    pub fn language_servers_for_local_buffer<'a>(
 7488        &'a self,
 7489        buffer: &Buffer,
 7490        cx: &mut App,
 7491    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
 7492        let local = self.as_local();
 7493        let language_server_ids = local
 7494            .map(|local| local.language_server_ids_for_buffer(buffer, cx))
 7495            .unwrap_or_default();
 7496
 7497        language_server_ids
 7498            .into_iter()
 7499            .filter_map(
 7500                move |server_id| match local?.language_servers.get(&server_id)? {
 7501                    LanguageServerState::Running {
 7502                        adapter, server, ..
 7503                    } => Some((adapter, server)),
 7504                    _ => None,
 7505                },
 7506            )
 7507    }
 7508
 7509    pub fn language_server_for_local_buffer<'a>(
 7510        &'a self,
 7511        buffer: &'a Buffer,
 7512        server_id: LanguageServerId,
 7513        cx: &'a mut App,
 7514    ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
 7515        self.as_local()?
 7516            .language_servers_for_buffer(buffer, cx)
 7517            .find(|(_, s)| s.server_id() == server_id)
 7518    }
 7519
 7520    fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
 7521        self.diagnostic_summaries.remove(&id_to_remove);
 7522        if let Some(local) = self.as_local_mut() {
 7523            let to_remove = local.remove_worktree(id_to_remove, cx);
 7524            for server in to_remove {
 7525                self.language_server_statuses.remove(&server);
 7526            }
 7527        }
 7528    }
 7529
 7530    pub fn shared(
 7531        &mut self,
 7532        project_id: u64,
 7533        downstream_client: AnyProtoClient,
 7534        _: &mut Context<Self>,
 7535    ) {
 7536        self.downstream_client = Some((downstream_client.clone(), project_id));
 7537
 7538        for (server_id, status) in &self.language_server_statuses {
 7539            downstream_client
 7540                .send(proto::StartLanguageServer {
 7541                    project_id,
 7542                    server: Some(proto::LanguageServer {
 7543                        id: server_id.0 as u64,
 7544                        name: status.name.clone(),
 7545                        worktree_id: None,
 7546                    }),
 7547                })
 7548                .log_err();
 7549        }
 7550    }
 7551
 7552    pub fn disconnected_from_host(&mut self) {
 7553        self.downstream_client.take();
 7554    }
 7555
 7556    pub fn disconnected_from_ssh_remote(&mut self) {
 7557        if let LspStoreMode::Remote(RemoteLspStore {
 7558            upstream_client, ..
 7559        }) = &mut self.mode
 7560        {
 7561            upstream_client.take();
 7562        }
 7563    }
 7564
 7565    pub(crate) fn set_language_server_statuses_from_proto(
 7566        &mut self,
 7567        language_servers: Vec<proto::LanguageServer>,
 7568    ) {
 7569        self.language_server_statuses = language_servers
 7570            .into_iter()
 7571            .map(|server| {
 7572                (
 7573                    LanguageServerId(server.id as usize),
 7574                    LanguageServerStatus {
 7575                        name: server.name,
 7576                        pending_work: Default::default(),
 7577                        has_pending_diagnostic_updates: false,
 7578                        progress_tokens: Default::default(),
 7579                    },
 7580                )
 7581            })
 7582            .collect();
 7583    }
 7584
 7585    fn register_local_language_server(
 7586        &mut self,
 7587        worktree: Entity<Worktree>,
 7588        language_server_name: LanguageServerName,
 7589        language_server_id: LanguageServerId,
 7590        cx: &mut App,
 7591    ) {
 7592        let Some(local) = self.as_local_mut() else {
 7593            return;
 7594        };
 7595
 7596        let worktree_id = worktree.read(cx).id();
 7597        if worktree.read(cx).is_visible() {
 7598            let path = ProjectPath {
 7599                worktree_id,
 7600                path: Arc::from("".as_ref()),
 7601            };
 7602            let delegate = Arc::new(ManifestQueryDelegate::new(worktree.read(cx).snapshot()));
 7603            local.lsp_tree.update(cx, |language_server_tree, cx| {
 7604                for node in language_server_tree.get(
 7605                    path,
 7606                    AdapterQuery::Adapter(&language_server_name),
 7607                    delegate,
 7608                    cx,
 7609                ) {
 7610                    node.server_id_or_init(|disposition| {
 7611                        assert_eq!(disposition.server_name, &language_server_name);
 7612
 7613                        language_server_id
 7614                    });
 7615                }
 7616            });
 7617        }
 7618
 7619        local
 7620            .language_server_ids
 7621            .entry((worktree_id, language_server_name))
 7622            .or_default()
 7623            .insert(language_server_id);
 7624    }
 7625
 7626    #[cfg(test)]
 7627    pub fn update_diagnostic_entries(
 7628        &mut self,
 7629        server_id: LanguageServerId,
 7630        abs_path: PathBuf,
 7631        result_id: Option<String>,
 7632        version: Option<i32>,
 7633        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 7634        cx: &mut Context<Self>,
 7635    ) -> anyhow::Result<()> {
 7636        self.merge_diagnostic_entries(
 7637            server_id,
 7638            abs_path,
 7639            result_id,
 7640            version,
 7641            diagnostics,
 7642            |_, _, _| false,
 7643            cx,
 7644        )?;
 7645        Ok(())
 7646    }
 7647
 7648    pub fn merge_diagnostic_entries(
 7649        &mut self,
 7650        server_id: LanguageServerId,
 7651        abs_path: PathBuf,
 7652        result_id: Option<String>,
 7653        version: Option<i32>,
 7654        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 7655        filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
 7656        cx: &mut Context<Self>,
 7657    ) -> anyhow::Result<()> {
 7658        let Some((worktree, relative_path)) =
 7659            self.worktree_store.read(cx).find_worktree(&abs_path, cx)
 7660        else {
 7661            log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
 7662            return Ok(());
 7663        };
 7664
 7665        let project_path = ProjectPath {
 7666            worktree_id: worktree.read(cx).id(),
 7667            path: relative_path.into(),
 7668        };
 7669
 7670        if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path) {
 7671            let snapshot = buffer_handle.read(cx).snapshot();
 7672            let buffer = buffer_handle.read(cx);
 7673            let reused_diagnostics = buffer
 7674                .get_diagnostics(server_id)
 7675                .into_iter()
 7676                .flat_map(|diag| {
 7677                    diag.iter()
 7678                        .filter(|v| filter(buffer, &v.diagnostic, cx))
 7679                        .map(|v| {
 7680                            let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
 7681                            let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
 7682                            DiagnosticEntry {
 7683                                range: start..end,
 7684                                diagnostic: v.diagnostic.clone(),
 7685                            }
 7686                        })
 7687                })
 7688                .collect::<Vec<_>>();
 7689
 7690            self.as_local_mut()
 7691                .context("cannot merge diagnostics on a remote LspStore")?
 7692                .update_buffer_diagnostics(
 7693                    &buffer_handle,
 7694                    server_id,
 7695                    result_id,
 7696                    version,
 7697                    diagnostics.clone(),
 7698                    reused_diagnostics.clone(),
 7699                    cx,
 7700                )?;
 7701
 7702            diagnostics.extend(reused_diagnostics);
 7703        }
 7704
 7705        let updated = worktree.update(cx, |worktree, cx| {
 7706            self.update_worktree_diagnostics(
 7707                worktree.id(),
 7708                server_id,
 7709                project_path.path.clone(),
 7710                diagnostics,
 7711                cx,
 7712            )
 7713        })?;
 7714        if updated {
 7715            cx.emit(LspStoreEvent::DiagnosticsUpdated {
 7716                language_server_id: server_id,
 7717                path: project_path,
 7718            })
 7719        }
 7720        Ok(())
 7721    }
 7722
 7723    fn update_worktree_diagnostics(
 7724        &mut self,
 7725        worktree_id: WorktreeId,
 7726        server_id: LanguageServerId,
 7727        worktree_path: Arc<Path>,
 7728        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 7729        _: &mut Context<Worktree>,
 7730    ) -> Result<bool> {
 7731        let local = match &mut self.mode {
 7732            LspStoreMode::Local(local_lsp_store) => local_lsp_store,
 7733            _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
 7734        };
 7735
 7736        let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
 7737        let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
 7738        let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
 7739
 7740        let old_summary = summaries_by_server_id
 7741            .remove(&server_id)
 7742            .unwrap_or_default();
 7743
 7744        let new_summary = DiagnosticSummary::new(&diagnostics);
 7745        if new_summary.is_empty() {
 7746            if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
 7747                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 7748                    diagnostics_by_server_id.remove(ix);
 7749                }
 7750                if diagnostics_by_server_id.is_empty() {
 7751                    diagnostics_for_tree.remove(&worktree_path);
 7752                }
 7753            }
 7754        } else {
 7755            summaries_by_server_id.insert(server_id, new_summary);
 7756            let diagnostics_by_server_id = diagnostics_for_tree
 7757                .entry(worktree_path.clone())
 7758                .or_default();
 7759            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 7760                Ok(ix) => {
 7761                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 7762                }
 7763                Err(ix) => {
 7764                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 7765                }
 7766            }
 7767        }
 7768
 7769        if !old_summary.is_empty() || !new_summary.is_empty() {
 7770            if let Some((downstream_client, project_id)) = &self.downstream_client {
 7771                downstream_client
 7772                    .send(proto::UpdateDiagnosticSummary {
 7773                        project_id: *project_id,
 7774                        worktree_id: worktree_id.to_proto(),
 7775                        summary: Some(proto::DiagnosticSummary {
 7776                            path: worktree_path.to_proto(),
 7777                            language_server_id: server_id.0 as u64,
 7778                            error_count: new_summary.error_count as u32,
 7779                            warning_count: new_summary.warning_count as u32,
 7780                        }),
 7781                    })
 7782                    .log_err();
 7783            }
 7784        }
 7785
 7786        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 7787    }
 7788
 7789    pub fn open_buffer_for_symbol(
 7790        &mut self,
 7791        symbol: &Symbol,
 7792        cx: &mut Context<Self>,
 7793    ) -> Task<Result<Entity<Buffer>>> {
 7794        if let Some((client, project_id)) = self.upstream_client() {
 7795            let request = client.request(proto::OpenBufferForSymbol {
 7796                project_id,
 7797                symbol: Some(Self::serialize_symbol(symbol)),
 7798            });
 7799            cx.spawn(async move |this, cx| {
 7800                let response = request.await?;
 7801                let buffer_id = BufferId::new(response.buffer_id)?;
 7802                this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 7803                    .await
 7804            })
 7805        } else if let Some(local) = self.as_local() {
 7806            let Some(language_server_id) = local
 7807                .language_server_ids
 7808                .get(&(
 7809                    symbol.source_worktree_id,
 7810                    symbol.language_server_name.clone(),
 7811                ))
 7812                .and_then(|ids| {
 7813                    ids.contains(&symbol.source_language_server_id)
 7814                        .then_some(symbol.source_language_server_id)
 7815                })
 7816            else {
 7817                return Task::ready(Err(anyhow!(
 7818                    "language server for worktree and language not found"
 7819                )));
 7820            };
 7821
 7822            let worktree_abs_path = if let Some(worktree_abs_path) = self
 7823                .worktree_store
 7824                .read(cx)
 7825                .worktree_for_id(symbol.path.worktree_id, cx)
 7826                .map(|worktree| worktree.read(cx).abs_path())
 7827            {
 7828                worktree_abs_path
 7829            } else {
 7830                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 7831            };
 7832
 7833            let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
 7834            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 7835                uri
 7836            } else {
 7837                return Task::ready(Err(anyhow!("invalid symbol path")));
 7838            };
 7839
 7840            self.open_local_buffer_via_lsp(
 7841                symbol_uri,
 7842                language_server_id,
 7843                symbol.language_server_name.clone(),
 7844                cx,
 7845            )
 7846        } else {
 7847            Task::ready(Err(anyhow!("no upstream client or local store")))
 7848        }
 7849    }
 7850
 7851    pub fn open_local_buffer_via_lsp(
 7852        &mut self,
 7853        mut abs_path: lsp::Url,
 7854        language_server_id: LanguageServerId,
 7855        language_server_name: LanguageServerName,
 7856        cx: &mut Context<Self>,
 7857    ) -> Task<Result<Entity<Buffer>>> {
 7858        cx.spawn(async move |lsp_store, cx| {
 7859            // Escape percent-encoded string.
 7860            let current_scheme = abs_path.scheme().to_owned();
 7861            let _ = abs_path.set_scheme("file");
 7862
 7863            let abs_path = abs_path
 7864                .to_file_path()
 7865                .map_err(|()| anyhow!("can't convert URI to path"))?;
 7866            let p = abs_path.clone();
 7867            let yarn_worktree = lsp_store
 7868                .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
 7869                    Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
 7870                        cx.spawn(async move |this, cx| {
 7871                            let t = this
 7872                                .update(cx, |this, cx| this.process_path(&p, &current_scheme, cx))
 7873                                .ok()?;
 7874                            t.await
 7875                        })
 7876                    }),
 7877                    None => Task::ready(None),
 7878                })?
 7879                .await;
 7880            let (worktree_root_target, known_relative_path) =
 7881                if let Some((zip_root, relative_path)) = yarn_worktree {
 7882                    (zip_root, Some(relative_path))
 7883                } else {
 7884                    (Arc::<Path>::from(abs_path.as_path()), None)
 7885                };
 7886            let (worktree, relative_path) = if let Some(result) =
 7887                lsp_store.update(cx, |lsp_store, cx| {
 7888                    lsp_store.worktree_store.update(cx, |worktree_store, cx| {
 7889                        worktree_store.find_worktree(&worktree_root_target, cx)
 7890                    })
 7891                })? {
 7892                let relative_path =
 7893                    known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
 7894                (result.0, relative_path)
 7895            } else {
 7896                let worktree = lsp_store
 7897                    .update(cx, |lsp_store, cx| {
 7898                        lsp_store.worktree_store.update(cx, |worktree_store, cx| {
 7899                            worktree_store.create_worktree(&worktree_root_target, false, cx)
 7900                        })
 7901                    })?
 7902                    .await?;
 7903                if worktree.read_with(cx, |worktree, _| worktree.is_local())? {
 7904                    lsp_store
 7905                        .update(cx, |lsp_store, cx| {
 7906                            lsp_store.register_local_language_server(
 7907                                worktree.clone(),
 7908                                language_server_name,
 7909                                language_server_id,
 7910                                cx,
 7911                            )
 7912                        })
 7913                        .ok();
 7914                }
 7915                let worktree_root = worktree.read_with(cx, |worktree, _| worktree.abs_path())?;
 7916                let relative_path = if let Some(known_path) = known_relative_path {
 7917                    known_path
 7918                } else {
 7919                    abs_path.strip_prefix(worktree_root)?.into()
 7920                };
 7921                (worktree, relative_path)
 7922            };
 7923            let project_path = ProjectPath {
 7924                worktree_id: worktree.read_with(cx, |worktree, _| worktree.id())?,
 7925                path: relative_path,
 7926            };
 7927            lsp_store
 7928                .update(cx, |lsp_store, cx| {
 7929                    lsp_store.buffer_store().update(cx, |buffer_store, cx| {
 7930                        buffer_store.open_buffer(project_path, cx)
 7931                    })
 7932                })?
 7933                .await
 7934        })
 7935    }
 7936
 7937    fn request_multiple_lsp_locally<P, R>(
 7938        &mut self,
 7939        buffer: &Entity<Buffer>,
 7940        position: Option<P>,
 7941        request: R,
 7942        cx: &mut Context<Self>,
 7943    ) -> Task<Vec<(LanguageServerId, R::Response)>>
 7944    where
 7945        P: ToOffset,
 7946        R: LspCommand + Clone,
 7947        <R::LspRequest as lsp::request::Request>::Result: Send,
 7948        <R::LspRequest as lsp::request::Request>::Params: Send,
 7949    {
 7950        let Some(local) = self.as_local() else {
 7951            return Task::ready(Vec::new());
 7952        };
 7953
 7954        let snapshot = buffer.read(cx).snapshot();
 7955        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 7956
 7957        let server_ids = buffer.update(cx, |buffer, cx| {
 7958            local
 7959                .language_servers_for_buffer(buffer, cx)
 7960                .filter(|(adapter, _)| {
 7961                    scope
 7962                        .as_ref()
 7963                        .map(|scope| scope.language_allowed(&adapter.name))
 7964                        .unwrap_or(true)
 7965                })
 7966                .map(|(_, server)| server.server_id())
 7967                .filter(|server_id| {
 7968                    self.as_local().is_none_or(|local| {
 7969                        local
 7970                            .buffers_opened_in_servers
 7971                            .get(&snapshot.remote_id())
 7972                            .is_some_and(|servers| servers.contains(server_id))
 7973                    })
 7974                })
 7975                .collect::<Vec<_>>()
 7976        });
 7977
 7978        let mut response_results = server_ids
 7979            .into_iter()
 7980            .map(|server_id| {
 7981                let task = self.request_lsp(
 7982                    buffer.clone(),
 7983                    LanguageServerToQuery::Other(server_id),
 7984                    request.clone(),
 7985                    cx,
 7986                );
 7987                async move { (server_id, task.await) }
 7988            })
 7989            .collect::<FuturesUnordered<_>>();
 7990
 7991        cx.background_spawn(async move {
 7992            let mut responses = Vec::with_capacity(response_results.len());
 7993            while let Some((server_id, response_result)) = response_results.next().await {
 7994                if let Some(response) = response_result.log_err() {
 7995                    responses.push((server_id, response));
 7996                }
 7997            }
 7998            responses
 7999        })
 8000    }
 8001
 8002    async fn handle_lsp_command<T: LspCommand>(
 8003        this: Entity<Self>,
 8004        envelope: TypedEnvelope<T::ProtoRequest>,
 8005        mut cx: AsyncApp,
 8006    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 8007    where
 8008        <T::LspRequest as lsp::request::Request>::Params: Send,
 8009        <T::LspRequest as lsp::request::Request>::Result: Send,
 8010    {
 8011        let sender_id = envelope.original_sender_id().unwrap_or_default();
 8012        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 8013        let buffer_handle = this.update(&mut cx, |this, cx| {
 8014            this.buffer_store.read(cx).get_existing(buffer_id)
 8015        })??;
 8016        let request = T::from_proto(
 8017            envelope.payload,
 8018            this.clone(),
 8019            buffer_handle.clone(),
 8020            cx.clone(),
 8021        )
 8022        .await?;
 8023        let response = this
 8024            .update(&mut cx, |this, cx| {
 8025                this.request_lsp(
 8026                    buffer_handle.clone(),
 8027                    LanguageServerToQuery::FirstCapable,
 8028                    request,
 8029                    cx,
 8030                )
 8031            })?
 8032            .await?;
 8033        this.update(&mut cx, |this, cx| {
 8034            Ok(T::response_to_proto(
 8035                response,
 8036                this,
 8037                sender_id,
 8038                &buffer_handle.read(cx).version(),
 8039                cx,
 8040            ))
 8041        })?
 8042    }
 8043
 8044    async fn handle_multi_lsp_query(
 8045        lsp_store: Entity<Self>,
 8046        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8047        mut cx: AsyncApp,
 8048    ) -> Result<proto::MultiLspQueryResponse> {
 8049        let response_from_ssh = lsp_store.read_with(&mut cx, |this, _| {
 8050            let (upstream_client, project_id) = this.upstream_client()?;
 8051            let mut payload = envelope.payload.clone();
 8052            payload.project_id = project_id;
 8053
 8054            Some(upstream_client.request(payload))
 8055        })?;
 8056        if let Some(response_from_ssh) = response_from_ssh {
 8057            return response_from_ssh.await;
 8058        }
 8059
 8060        let sender_id = envelope.original_sender_id().unwrap_or_default();
 8061        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8062        let version = deserialize_version(&envelope.payload.version);
 8063        let buffer = lsp_store.update(&mut cx, |this, cx| {
 8064            this.buffer_store.read(cx).get_existing(buffer_id)
 8065        })??;
 8066        buffer
 8067            .update(&mut cx, |buffer, _| {
 8068                buffer.wait_for_version(version.clone())
 8069            })?
 8070            .await?;
 8071        let buffer_version = buffer.read_with(&mut cx, |buffer, _| buffer.version())?;
 8072        match envelope
 8073            .payload
 8074            .strategy
 8075            .context("invalid request without the strategy")?
 8076        {
 8077            proto::multi_lsp_query::Strategy::All(_) => {
 8078                // currently, there's only one multiple language servers query strategy,
 8079                // so just ensure it's specified correctly
 8080            }
 8081        }
 8082        match envelope.payload.request {
 8083            Some(proto::multi_lsp_query::Request::GetHover(message)) => {
 8084                buffer
 8085                    .update(&mut cx, |buffer, _| {
 8086                        buffer.wait_for_version(deserialize_version(&message.version))
 8087                    })?
 8088                    .await?;
 8089                let get_hover =
 8090                    GetHover::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
 8091                        .await?;
 8092                let all_hovers = lsp_store
 8093                    .update(&mut cx, |this, cx| {
 8094                        this.request_multiple_lsp_locally(
 8095                            &buffer,
 8096                            Some(get_hover.position),
 8097                            get_hover,
 8098                            cx,
 8099                        )
 8100                    })?
 8101                    .await
 8102                    .into_iter()
 8103                    .filter_map(|(server_id, hover)| {
 8104                        Some((server_id, remove_empty_hover_blocks(hover?)?))
 8105                    });
 8106                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8107                    responses: all_hovers
 8108                        .map(|(server_id, hover)| proto::LspResponse {
 8109                            server_id: server_id.to_proto(),
 8110                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8111                                GetHover::response_to_proto(
 8112                                    Some(hover),
 8113                                    project,
 8114                                    sender_id,
 8115                                    &buffer_version,
 8116                                    cx,
 8117                                ),
 8118                            )),
 8119                        })
 8120                        .collect(),
 8121                })
 8122            }
 8123            Some(proto::multi_lsp_query::Request::GetCodeActions(message)) => {
 8124                buffer
 8125                    .update(&mut cx, |buffer, _| {
 8126                        buffer.wait_for_version(deserialize_version(&message.version))
 8127                    })?
 8128                    .await?;
 8129                let get_code_actions = GetCodeActions::from_proto(
 8130                    message,
 8131                    lsp_store.clone(),
 8132                    buffer.clone(),
 8133                    cx.clone(),
 8134                )
 8135                .await?;
 8136
 8137                let all_actions = lsp_store
 8138                    .update(&mut cx, |project, cx| {
 8139                        project.request_multiple_lsp_locally(
 8140                            &buffer,
 8141                            Some(get_code_actions.range.start),
 8142                            get_code_actions,
 8143                            cx,
 8144                        )
 8145                    })?
 8146                    .await
 8147                    .into_iter();
 8148
 8149                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8150                    responses: all_actions
 8151                        .map(|(server_id, code_actions)| proto::LspResponse {
 8152                            server_id: server_id.to_proto(),
 8153                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8154                                GetCodeActions::response_to_proto(
 8155                                    code_actions,
 8156                                    project,
 8157                                    sender_id,
 8158                                    &buffer_version,
 8159                                    cx,
 8160                                ),
 8161                            )),
 8162                        })
 8163                        .collect(),
 8164                })
 8165            }
 8166            Some(proto::multi_lsp_query::Request::GetSignatureHelp(message)) => {
 8167                buffer
 8168                    .update(&mut cx, |buffer, _| {
 8169                        buffer.wait_for_version(deserialize_version(&message.version))
 8170                    })?
 8171                    .await?;
 8172                let get_signature_help = GetSignatureHelp::from_proto(
 8173                    message,
 8174                    lsp_store.clone(),
 8175                    buffer.clone(),
 8176                    cx.clone(),
 8177                )
 8178                .await?;
 8179
 8180                let all_signatures = lsp_store
 8181                    .update(&mut cx, |project, cx| {
 8182                        project.request_multiple_lsp_locally(
 8183                            &buffer,
 8184                            Some(get_signature_help.position),
 8185                            get_signature_help,
 8186                            cx,
 8187                        )
 8188                    })?
 8189                    .await
 8190                    .into_iter();
 8191
 8192                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8193                    responses: all_signatures
 8194                        .map(|(server_id, signature_help)| proto::LspResponse {
 8195                            server_id: server_id.to_proto(),
 8196                            response: Some(
 8197                                proto::lsp_response::Response::GetSignatureHelpResponse(
 8198                                    GetSignatureHelp::response_to_proto(
 8199                                        signature_help,
 8200                                        project,
 8201                                        sender_id,
 8202                                        &buffer_version,
 8203                                        cx,
 8204                                    ),
 8205                                ),
 8206                            ),
 8207                        })
 8208                        .collect(),
 8209                })
 8210            }
 8211            Some(proto::multi_lsp_query::Request::GetCodeLens(message)) => {
 8212                buffer
 8213                    .update(&mut cx, |buffer, _| {
 8214                        buffer.wait_for_version(deserialize_version(&message.version))
 8215                    })?
 8216                    .await?;
 8217                let get_code_lens =
 8218                    GetCodeLens::from_proto(message, lsp_store.clone(), buffer.clone(), cx.clone())
 8219                        .await?;
 8220
 8221                let code_lens_actions = lsp_store
 8222                    .update(&mut cx, |project, cx| {
 8223                        project.request_multiple_lsp_locally(
 8224                            &buffer,
 8225                            None::<usize>,
 8226                            get_code_lens,
 8227                            cx,
 8228                        )
 8229                    })?
 8230                    .await
 8231                    .into_iter();
 8232
 8233                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8234                    responses: code_lens_actions
 8235                        .map(|(server_id, actions)| proto::LspResponse {
 8236                            server_id: server_id.to_proto(),
 8237                            response: Some(proto::lsp_response::Response::GetCodeLensResponse(
 8238                                GetCodeLens::response_to_proto(
 8239                                    actions,
 8240                                    project,
 8241                                    sender_id,
 8242                                    &buffer_version,
 8243                                    cx,
 8244                                ),
 8245                            )),
 8246                        })
 8247                        .collect(),
 8248                })
 8249            }
 8250            Some(proto::multi_lsp_query::Request::GetDocumentDiagnostics(message)) => {
 8251                buffer
 8252                    .update(&mut cx, |buffer, _| {
 8253                        buffer.wait_for_version(deserialize_version(&message.version))
 8254                    })?
 8255                    .await?;
 8256                lsp_store
 8257                    .update(&mut cx, |lsp_store, cx| {
 8258                        lsp_store.pull_diagnostics_for_buffer(buffer, cx)
 8259                    })?
 8260                    .await?;
 8261                // `pull_diagnostics_for_buffer` will merge in the new diagnostics and send them to the client.
 8262                // The client cannot merge anything into its non-local LspStore, so we do not need to return anything.
 8263                Ok(proto::MultiLspQueryResponse {
 8264                    responses: Vec::new(),
 8265                })
 8266            }
 8267            Some(proto::multi_lsp_query::Request::GetDocumentColor(message)) => {
 8268                buffer
 8269                    .update(&mut cx, |buffer, _| {
 8270                        buffer.wait_for_version(deserialize_version(&message.version))
 8271                    })?
 8272                    .await?;
 8273                let get_document_color = GetDocumentColor::from_proto(
 8274                    message,
 8275                    lsp_store.clone(),
 8276                    buffer.clone(),
 8277                    cx.clone(),
 8278                )
 8279                .await?;
 8280
 8281                let all_colors = lsp_store
 8282                    .update(&mut cx, |project, cx| {
 8283                        project.request_multiple_lsp_locally(
 8284                            &buffer,
 8285                            None::<usize>,
 8286                            get_document_color,
 8287                            cx,
 8288                        )
 8289                    })?
 8290                    .await
 8291                    .into_iter();
 8292
 8293                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8294                    responses: all_colors
 8295                        .map(|(server_id, colors)| proto::LspResponse {
 8296                            server_id: server_id.to_proto(),
 8297                            response: Some(
 8298                                proto::lsp_response::Response::GetDocumentColorResponse(
 8299                                    GetDocumentColor::response_to_proto(
 8300                                        colors,
 8301                                        project,
 8302                                        sender_id,
 8303                                        &buffer_version,
 8304                                        cx,
 8305                                    ),
 8306                                ),
 8307                            ),
 8308                        })
 8309                        .collect(),
 8310                })
 8311            }
 8312            Some(proto::multi_lsp_query::Request::GetDefinition(message)) => {
 8313                let get_definitions = GetDefinitions::from_proto(
 8314                    message,
 8315                    lsp_store.clone(),
 8316                    buffer.clone(),
 8317                    cx.clone(),
 8318                )
 8319                .await?;
 8320
 8321                let definitions = lsp_store
 8322                    .update(&mut cx, |project, cx| {
 8323                        project.request_multiple_lsp_locally(
 8324                            &buffer,
 8325                            Some(get_definitions.position),
 8326                            get_definitions,
 8327                            cx,
 8328                        )
 8329                    })?
 8330                    .await
 8331                    .into_iter();
 8332
 8333                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8334                    responses: definitions
 8335                        .map(|(server_id, definitions)| proto::LspResponse {
 8336                            server_id: server_id.to_proto(),
 8337                            response: Some(proto::lsp_response::Response::GetDefinitionResponse(
 8338                                GetDefinitions::response_to_proto(
 8339                                    definitions,
 8340                                    project,
 8341                                    sender_id,
 8342                                    &buffer_version,
 8343                                    cx,
 8344                                ),
 8345                            )),
 8346                        })
 8347                        .collect(),
 8348                })
 8349            }
 8350            Some(proto::multi_lsp_query::Request::GetDeclaration(message)) => {
 8351                let get_declarations = GetDeclarations::from_proto(
 8352                    message,
 8353                    lsp_store.clone(),
 8354                    buffer.clone(),
 8355                    cx.clone(),
 8356                )
 8357                .await?;
 8358
 8359                let declarations = lsp_store
 8360                    .update(&mut cx, |project, cx| {
 8361                        project.request_multiple_lsp_locally(
 8362                            &buffer,
 8363                            Some(get_declarations.position),
 8364                            get_declarations,
 8365                            cx,
 8366                        )
 8367                    })?
 8368                    .await
 8369                    .into_iter();
 8370
 8371                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8372                    responses: declarations
 8373                        .map(|(server_id, declarations)| proto::LspResponse {
 8374                            server_id: server_id.to_proto(),
 8375                            response: Some(proto::lsp_response::Response::GetDeclarationResponse(
 8376                                GetDeclarations::response_to_proto(
 8377                                    declarations,
 8378                                    project,
 8379                                    sender_id,
 8380                                    &buffer_version,
 8381                                    cx,
 8382                                ),
 8383                            )),
 8384                        })
 8385                        .collect(),
 8386                })
 8387            }
 8388            Some(proto::multi_lsp_query::Request::GetTypeDefinition(message)) => {
 8389                let get_type_definitions = GetTypeDefinitions::from_proto(
 8390                    message,
 8391                    lsp_store.clone(),
 8392                    buffer.clone(),
 8393                    cx.clone(),
 8394                )
 8395                .await?;
 8396
 8397                let type_definitions = lsp_store
 8398                    .update(&mut cx, |project, cx| {
 8399                        project.request_multiple_lsp_locally(
 8400                            &buffer,
 8401                            Some(get_type_definitions.position),
 8402                            get_type_definitions,
 8403                            cx,
 8404                        )
 8405                    })?
 8406                    .await
 8407                    .into_iter();
 8408
 8409                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8410                    responses: type_definitions
 8411                        .map(|(server_id, type_definitions)| proto::LspResponse {
 8412                            server_id: server_id.to_proto(),
 8413                            response: Some(
 8414                                proto::lsp_response::Response::GetTypeDefinitionResponse(
 8415                                    GetTypeDefinitions::response_to_proto(
 8416                                        type_definitions,
 8417                                        project,
 8418                                        sender_id,
 8419                                        &buffer_version,
 8420                                        cx,
 8421                                    ),
 8422                                ),
 8423                            ),
 8424                        })
 8425                        .collect(),
 8426                })
 8427            }
 8428            Some(proto::multi_lsp_query::Request::GetImplementation(message)) => {
 8429                let get_implementations = GetImplementations::from_proto(
 8430                    message,
 8431                    lsp_store.clone(),
 8432                    buffer.clone(),
 8433                    cx.clone(),
 8434                )
 8435                .await?;
 8436
 8437                let implementations = lsp_store
 8438                    .update(&mut cx, |project, cx| {
 8439                        project.request_multiple_lsp_locally(
 8440                            &buffer,
 8441                            Some(get_implementations.position),
 8442                            get_implementations,
 8443                            cx,
 8444                        )
 8445                    })?
 8446                    .await
 8447                    .into_iter();
 8448
 8449                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8450                    responses: implementations
 8451                        .map(|(server_id, implementations)| proto::LspResponse {
 8452                            server_id: server_id.to_proto(),
 8453                            response: Some(
 8454                                proto::lsp_response::Response::GetImplementationResponse(
 8455                                    GetImplementations::response_to_proto(
 8456                                        implementations,
 8457                                        project,
 8458                                        sender_id,
 8459                                        &buffer_version,
 8460                                        cx,
 8461                                    ),
 8462                                ),
 8463                            ),
 8464                        })
 8465                        .collect(),
 8466                })
 8467            }
 8468            Some(proto::multi_lsp_query::Request::GetReferences(message)) => {
 8469                let get_references = GetReferences::from_proto(
 8470                    message,
 8471                    lsp_store.clone(),
 8472                    buffer.clone(),
 8473                    cx.clone(),
 8474                )
 8475                .await?;
 8476
 8477                let references = lsp_store
 8478                    .update(&mut cx, |project, cx| {
 8479                        project.request_multiple_lsp_locally(
 8480                            &buffer,
 8481                            Some(get_references.position),
 8482                            get_references,
 8483                            cx,
 8484                        )
 8485                    })?
 8486                    .await
 8487                    .into_iter();
 8488
 8489                lsp_store.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8490                    responses: references
 8491                        .map(|(server_id, references)| proto::LspResponse {
 8492                            server_id: server_id.to_proto(),
 8493                            response: Some(proto::lsp_response::Response::GetReferencesResponse(
 8494                                GetReferences::response_to_proto(
 8495                                    references,
 8496                                    project,
 8497                                    sender_id,
 8498                                    &buffer_version,
 8499                                    cx,
 8500                                ),
 8501                            )),
 8502                        })
 8503                        .collect(),
 8504                })
 8505            }
 8506            None => anyhow::bail!("empty multi lsp query request"),
 8507        }
 8508    }
 8509
 8510    async fn handle_apply_code_action(
 8511        this: Entity<Self>,
 8512        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 8513        mut cx: AsyncApp,
 8514    ) -> Result<proto::ApplyCodeActionResponse> {
 8515        let sender_id = envelope.original_sender_id().unwrap_or_default();
 8516        let action =
 8517            Self::deserialize_code_action(envelope.payload.action.context("invalid action")?)?;
 8518        let apply_code_action = this.update(&mut cx, |this, cx| {
 8519            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8520            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 8521            anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
 8522        })??;
 8523
 8524        let project_transaction = apply_code_action.await?;
 8525        let project_transaction = this.update(&mut cx, |this, cx| {
 8526            this.buffer_store.update(cx, |buffer_store, cx| {
 8527                buffer_store.serialize_project_transaction_for_peer(
 8528                    project_transaction,
 8529                    sender_id,
 8530                    cx,
 8531                )
 8532            })
 8533        })?;
 8534        Ok(proto::ApplyCodeActionResponse {
 8535            transaction: Some(project_transaction),
 8536        })
 8537    }
 8538
 8539    async fn handle_register_buffer_with_language_servers(
 8540        this: Entity<Self>,
 8541        envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
 8542        mut cx: AsyncApp,
 8543    ) -> Result<proto::Ack> {
 8544        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8545        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
 8546        this.update(&mut cx, |this, cx| {
 8547            if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
 8548                return upstream_client.send(proto::RegisterBufferWithLanguageServers {
 8549                    project_id: upstream_project_id,
 8550                    buffer_id: buffer_id.to_proto(),
 8551                    only_servers: envelope.payload.only_servers,
 8552                });
 8553            }
 8554
 8555            let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
 8556                anyhow::bail!("buffer is not open");
 8557            };
 8558
 8559            let handle = this.register_buffer_with_language_servers(
 8560                &buffer,
 8561                envelope
 8562                    .payload
 8563                    .only_servers
 8564                    .into_iter()
 8565                    .filter_map(|selector| {
 8566                        Some(match selector.selector? {
 8567                            proto::language_server_selector::Selector::ServerId(server_id) => {
 8568                                LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
 8569                            }
 8570                            proto::language_server_selector::Selector::Name(name) => {
 8571                                LanguageServerSelector::Name(LanguageServerName(
 8572                                    SharedString::from(name),
 8573                                ))
 8574                            }
 8575                        })
 8576                    })
 8577                    .collect(),
 8578                false,
 8579                cx,
 8580            );
 8581            this.buffer_store().update(cx, |buffer_store, _| {
 8582                buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
 8583            });
 8584
 8585            Ok(())
 8586        })??;
 8587        Ok(proto::Ack {})
 8588    }
 8589
 8590    async fn handle_language_server_id_for_name(
 8591        lsp_store: Entity<Self>,
 8592        envelope: TypedEnvelope<proto::LanguageServerIdForName>,
 8593        mut cx: AsyncApp,
 8594    ) -> Result<proto::LanguageServerIdForNameResponse> {
 8595        let name = &envelope.payload.name;
 8596        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8597        lsp_store
 8598            .update(&mut cx, |lsp_store, cx| {
 8599                let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
 8600                let server_id = buffer.update(cx, |buffer, cx| {
 8601                    lsp_store
 8602                        .language_servers_for_local_buffer(buffer, cx)
 8603                        .find_map(|(adapter, server)| {
 8604                            if adapter.name.0.as_ref() == name {
 8605                                Some(server.server_id())
 8606                            } else {
 8607                                None
 8608                            }
 8609                        })
 8610                });
 8611                Ok(server_id)
 8612            })?
 8613            .map(|server_id| proto::LanguageServerIdForNameResponse {
 8614                server_id: server_id.map(|id| id.to_proto()),
 8615            })
 8616    }
 8617
 8618    async fn handle_rename_project_entry(
 8619        this: Entity<Self>,
 8620        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8621        mut cx: AsyncApp,
 8622    ) -> Result<proto::ProjectEntryResponse> {
 8623        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8624        let (worktree_id, worktree, old_path, is_dir) = this
 8625            .update(&mut cx, |this, cx| {
 8626                this.worktree_store
 8627                    .read(cx)
 8628                    .worktree_and_entry_for_id(entry_id, cx)
 8629                    .map(|(worktree, entry)| {
 8630                        (
 8631                            worktree.read(cx).id(),
 8632                            worktree,
 8633                            entry.path.clone(),
 8634                            entry.is_dir(),
 8635                        )
 8636                    })
 8637            })?
 8638            .context("worktree not found")?;
 8639        let (old_abs_path, new_abs_path) = {
 8640            let root_path = worktree.read_with(&mut cx, |this, _| this.abs_path())?;
 8641            let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
 8642            (root_path.join(&old_path), root_path.join(&new_path))
 8643        };
 8644
 8645        Self::will_rename_entry(
 8646            this.downgrade(),
 8647            worktree_id,
 8648            &old_abs_path,
 8649            &new_abs_path,
 8650            is_dir,
 8651            cx.clone(),
 8652        )
 8653        .await;
 8654        let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
 8655        this.read_with(&mut cx, |this, _| {
 8656            this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
 8657        })
 8658        .ok();
 8659        response
 8660    }
 8661
 8662    async fn handle_update_diagnostic_summary(
 8663        this: Entity<Self>,
 8664        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8665        mut cx: AsyncApp,
 8666    ) -> Result<()> {
 8667        this.update(&mut cx, |this, cx| {
 8668            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8669            if let Some(message) = envelope.payload.summary {
 8670                let project_path = ProjectPath {
 8671                    worktree_id,
 8672                    path: Arc::<Path>::from_proto(message.path),
 8673                };
 8674                let path = project_path.path.clone();
 8675                let server_id = LanguageServerId(message.language_server_id as usize);
 8676                let summary = DiagnosticSummary {
 8677                    error_count: message.error_count as usize,
 8678                    warning_count: message.warning_count as usize,
 8679                };
 8680
 8681                if summary.is_empty() {
 8682                    if let Some(worktree_summaries) =
 8683                        this.diagnostic_summaries.get_mut(&worktree_id)
 8684                    {
 8685                        if let Some(summaries) = worktree_summaries.get_mut(&path) {
 8686                            summaries.remove(&server_id);
 8687                            if summaries.is_empty() {
 8688                                worktree_summaries.remove(&path);
 8689                            }
 8690                        }
 8691                    }
 8692                } else {
 8693                    this.diagnostic_summaries
 8694                        .entry(worktree_id)
 8695                        .or_default()
 8696                        .entry(path)
 8697                        .or_default()
 8698                        .insert(server_id, summary);
 8699                }
 8700                if let Some((downstream_client, project_id)) = &this.downstream_client {
 8701                    downstream_client
 8702                        .send(proto::UpdateDiagnosticSummary {
 8703                            project_id: *project_id,
 8704                            worktree_id: worktree_id.to_proto(),
 8705                            summary: Some(proto::DiagnosticSummary {
 8706                                path: project_path.path.as_ref().to_proto(),
 8707                                language_server_id: server_id.0 as u64,
 8708                                error_count: summary.error_count as u32,
 8709                                warning_count: summary.warning_count as u32,
 8710                            }),
 8711                        })
 8712                        .log_err();
 8713                }
 8714                cx.emit(LspStoreEvent::DiagnosticsUpdated {
 8715                    language_server_id: LanguageServerId(message.language_server_id as usize),
 8716                    path: project_path,
 8717                });
 8718            }
 8719            Ok(())
 8720        })?
 8721    }
 8722
 8723    async fn handle_start_language_server(
 8724        this: Entity<Self>,
 8725        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8726        mut cx: AsyncApp,
 8727    ) -> Result<()> {
 8728        let server = envelope.payload.server.context("invalid server")?;
 8729
 8730        this.update(&mut cx, |this, cx| {
 8731            let server_id = LanguageServerId(server.id as usize);
 8732            this.language_server_statuses.insert(
 8733                server_id,
 8734                LanguageServerStatus {
 8735                    name: server.name.clone(),
 8736                    pending_work: Default::default(),
 8737                    has_pending_diagnostic_updates: false,
 8738                    progress_tokens: Default::default(),
 8739                },
 8740            );
 8741            cx.emit(LspStoreEvent::LanguageServerAdded(
 8742                server_id,
 8743                LanguageServerName(server.name.into()),
 8744                server.worktree_id.map(WorktreeId::from_proto),
 8745            ));
 8746            cx.notify();
 8747        })?;
 8748        Ok(())
 8749    }
 8750
 8751    async fn handle_update_language_server(
 8752        lsp_store: Entity<Self>,
 8753        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8754        mut cx: AsyncApp,
 8755    ) -> Result<()> {
 8756        lsp_store.update(&mut cx, |lsp_store, cx| {
 8757            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8758
 8759            match envelope.payload.variant.context("invalid variant")? {
 8760                proto::update_language_server::Variant::WorkStart(payload) => {
 8761                    lsp_store.on_lsp_work_start(
 8762                        language_server_id,
 8763                        payload.token,
 8764                        LanguageServerProgress {
 8765                            title: payload.title,
 8766                            is_disk_based_diagnostics_progress: false,
 8767                            is_cancellable: payload.is_cancellable.unwrap_or(false),
 8768                            message: payload.message,
 8769                            percentage: payload.percentage.map(|p| p as usize),
 8770                            last_update_at: cx.background_executor().now(),
 8771                        },
 8772                        cx,
 8773                    );
 8774                }
 8775                proto::update_language_server::Variant::WorkProgress(payload) => {
 8776                    lsp_store.on_lsp_work_progress(
 8777                        language_server_id,
 8778                        payload.token,
 8779                        LanguageServerProgress {
 8780                            title: None,
 8781                            is_disk_based_diagnostics_progress: false,
 8782                            is_cancellable: payload.is_cancellable.unwrap_or(false),
 8783                            message: payload.message,
 8784                            percentage: payload.percentage.map(|p| p as usize),
 8785                            last_update_at: cx.background_executor().now(),
 8786                        },
 8787                        cx,
 8788                    );
 8789                }
 8790
 8791                proto::update_language_server::Variant::WorkEnd(payload) => {
 8792                    lsp_store.on_lsp_work_end(language_server_id, payload.token, cx);
 8793                }
 8794
 8795                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8796                    lsp_store.disk_based_diagnostics_started(language_server_id, cx);
 8797                }
 8798
 8799                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8800                    lsp_store.disk_based_diagnostics_finished(language_server_id, cx)
 8801                }
 8802
 8803                non_lsp @ proto::update_language_server::Variant::StatusUpdate(_)
 8804                | non_lsp @ proto::update_language_server::Variant::RegisteredForBuffer(_) => {
 8805                    cx.emit(LspStoreEvent::LanguageServerUpdate {
 8806                        language_server_id,
 8807                        name: envelope
 8808                            .payload
 8809                            .server_name
 8810                            .map(SharedString::new)
 8811                            .map(LanguageServerName),
 8812                        message: non_lsp,
 8813                    });
 8814                }
 8815            }
 8816
 8817            Ok(())
 8818        })?
 8819    }
 8820
 8821    async fn handle_language_server_log(
 8822        this: Entity<Self>,
 8823        envelope: TypedEnvelope<proto::LanguageServerLog>,
 8824        mut cx: AsyncApp,
 8825    ) -> Result<()> {
 8826        let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8827        let log_type = envelope
 8828            .payload
 8829            .log_type
 8830            .map(LanguageServerLogType::from_proto)
 8831            .context("invalid language server log type")?;
 8832
 8833        let message = envelope.payload.message;
 8834
 8835        this.update(&mut cx, |_, cx| {
 8836            cx.emit(LspStoreEvent::LanguageServerLog(
 8837                language_server_id,
 8838                log_type,
 8839                message,
 8840            ));
 8841        })
 8842    }
 8843
 8844    async fn handle_lsp_ext_cancel_flycheck(
 8845        lsp_store: Entity<Self>,
 8846        envelope: TypedEnvelope<proto::LspExtCancelFlycheck>,
 8847        mut cx: AsyncApp,
 8848    ) -> Result<proto::Ack> {
 8849        let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8850        lsp_store.read_with(&mut cx, |lsp_store, _| {
 8851            if let Some(server) = lsp_store.language_server_for_id(server_id) {
 8852                server
 8853                    .notify::<lsp_store::lsp_ext_command::LspExtCancelFlycheck>(&())
 8854                    .context("handling lsp ext cancel flycheck")
 8855            } else {
 8856                anyhow::Ok(())
 8857            }
 8858        })??;
 8859
 8860        Ok(proto::Ack {})
 8861    }
 8862
 8863    async fn handle_lsp_ext_run_flycheck(
 8864        lsp_store: Entity<Self>,
 8865        envelope: TypedEnvelope<proto::LspExtRunFlycheck>,
 8866        mut cx: AsyncApp,
 8867    ) -> Result<proto::Ack> {
 8868        let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8869        lsp_store.update(&mut cx, |lsp_store, cx| {
 8870            if let Some(server) = lsp_store.language_server_for_id(server_id) {
 8871                let text_document = if envelope.payload.current_file_only {
 8872                    let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8873                    lsp_store
 8874                        .buffer_store()
 8875                        .read(cx)
 8876                        .get(buffer_id)
 8877                        .and_then(|buffer| Some(buffer.read(cx).file()?.as_local()?.abs_path(cx)))
 8878                        .map(|path| make_text_document_identifier(&path))
 8879                        .transpose()?
 8880                } else {
 8881                    None
 8882                };
 8883                server
 8884                    .notify::<lsp_store::lsp_ext_command::LspExtRunFlycheck>(
 8885                        &lsp_store::lsp_ext_command::RunFlycheckParams { text_document },
 8886                    )
 8887                    .context("handling lsp ext run flycheck")
 8888            } else {
 8889                anyhow::Ok(())
 8890            }
 8891        })??;
 8892
 8893        Ok(proto::Ack {})
 8894    }
 8895
 8896    async fn handle_lsp_ext_clear_flycheck(
 8897        lsp_store: Entity<Self>,
 8898        envelope: TypedEnvelope<proto::LspExtClearFlycheck>,
 8899        mut cx: AsyncApp,
 8900    ) -> Result<proto::Ack> {
 8901        let server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8902        lsp_store.read_with(&mut cx, |lsp_store, _| {
 8903            if let Some(server) = lsp_store.language_server_for_id(server_id) {
 8904                server
 8905                    .notify::<lsp_store::lsp_ext_command::LspExtClearFlycheck>(&())
 8906                    .context("handling lsp ext clear flycheck")
 8907            } else {
 8908                anyhow::Ok(())
 8909            }
 8910        })??;
 8911
 8912        Ok(proto::Ack {})
 8913    }
 8914
 8915    pub fn disk_based_diagnostics_started(
 8916        &mut self,
 8917        language_server_id: LanguageServerId,
 8918        cx: &mut Context<Self>,
 8919    ) {
 8920        if let Some(language_server_status) =
 8921            self.language_server_statuses.get_mut(&language_server_id)
 8922        {
 8923            language_server_status.has_pending_diagnostic_updates = true;
 8924        }
 8925
 8926        cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
 8927        cx.emit(LspStoreEvent::LanguageServerUpdate {
 8928            language_server_id,
 8929            name: self
 8930                .language_server_adapter_for_id(language_server_id)
 8931                .map(|adapter| adapter.name()),
 8932            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 8933                Default::default(),
 8934            ),
 8935        })
 8936    }
 8937
 8938    pub fn disk_based_diagnostics_finished(
 8939        &mut self,
 8940        language_server_id: LanguageServerId,
 8941        cx: &mut Context<Self>,
 8942    ) {
 8943        if let Some(language_server_status) =
 8944            self.language_server_statuses.get_mut(&language_server_id)
 8945        {
 8946            language_server_status.has_pending_diagnostic_updates = false;
 8947        }
 8948
 8949        cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
 8950        cx.emit(LspStoreEvent::LanguageServerUpdate {
 8951            language_server_id,
 8952            name: self
 8953                .language_server_adapter_for_id(language_server_id)
 8954                .map(|adapter| adapter.name()),
 8955            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 8956                Default::default(),
 8957            ),
 8958        })
 8959    }
 8960
 8961    // After saving a buffer using a language server that doesn't provide a disk-based progress token,
 8962    // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
 8963    // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
 8964    // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
 8965    // the language server might take some time to publish diagnostics.
 8966    fn simulate_disk_based_diagnostics_events_if_needed(
 8967        &mut self,
 8968        language_server_id: LanguageServerId,
 8969        cx: &mut Context<Self>,
 8970    ) {
 8971        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
 8972
 8973        let Some(LanguageServerState::Running {
 8974            simulate_disk_based_diagnostics_completion,
 8975            adapter,
 8976            ..
 8977        }) = self
 8978            .as_local_mut()
 8979            .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
 8980        else {
 8981            return;
 8982        };
 8983
 8984        if adapter.disk_based_diagnostics_progress_token.is_some() {
 8985            return;
 8986        }
 8987
 8988        let prev_task =
 8989            simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
 8990                cx.background_executor()
 8991                    .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
 8992                    .await;
 8993
 8994                this.update(cx, |this, cx| {
 8995                    this.disk_based_diagnostics_finished(language_server_id, cx);
 8996
 8997                    if let Some(LanguageServerState::Running {
 8998                        simulate_disk_based_diagnostics_completion,
 8999                        ..
 9000                    }) = this.as_local_mut().and_then(|local_store| {
 9001                        local_store.language_servers.get_mut(&language_server_id)
 9002                    }) {
 9003                        *simulate_disk_based_diagnostics_completion = None;
 9004                    }
 9005                })
 9006                .ok();
 9007            }));
 9008
 9009        if prev_task.is_none() {
 9010            self.disk_based_diagnostics_started(language_server_id, cx);
 9011        }
 9012    }
 9013
 9014    pub fn language_server_statuses(
 9015        &self,
 9016    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
 9017        self.language_server_statuses
 9018            .iter()
 9019            .map(|(key, value)| (*key, value))
 9020    }
 9021
 9022    pub(super) fn did_rename_entry(
 9023        &self,
 9024        worktree_id: WorktreeId,
 9025        old_path: &Path,
 9026        new_path: &Path,
 9027        is_dir: bool,
 9028    ) {
 9029        maybe!({
 9030            let local_store = self.as_local()?;
 9031
 9032            let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
 9033            let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
 9034
 9035            for language_server in local_store.language_servers_for_worktree(worktree_id) {
 9036                let Some(filter) = local_store
 9037                    .language_server_paths_watched_for_rename
 9038                    .get(&language_server.server_id())
 9039                else {
 9040                    continue;
 9041                };
 9042
 9043                if filter.should_send_did_rename(&old_uri, is_dir) {
 9044                    language_server
 9045                        .notify::<DidRenameFiles>(&RenameFilesParams {
 9046                            files: vec![FileRename {
 9047                                old_uri: old_uri.clone(),
 9048                                new_uri: new_uri.clone(),
 9049                            }],
 9050                        })
 9051                        .ok();
 9052                }
 9053            }
 9054            Some(())
 9055        });
 9056    }
 9057
 9058    pub(super) fn will_rename_entry(
 9059        this: WeakEntity<Self>,
 9060        worktree_id: WorktreeId,
 9061        old_path: &Path,
 9062        new_path: &Path,
 9063        is_dir: bool,
 9064        cx: AsyncApp,
 9065    ) -> Task<()> {
 9066        let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
 9067        let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
 9068        cx.spawn(async move |cx| {
 9069            let mut tasks = vec![];
 9070            this.update(cx, |this, cx| {
 9071                let local_store = this.as_local()?;
 9072                let old_uri = old_uri?;
 9073                let new_uri = new_uri?;
 9074                for language_server in local_store.language_servers_for_worktree(worktree_id) {
 9075                    let Some(filter) = local_store
 9076                        .language_server_paths_watched_for_rename
 9077                        .get(&language_server.server_id())
 9078                    else {
 9079                        continue;
 9080                    };
 9081                    let Some(adapter) =
 9082                        this.language_server_adapter_for_id(language_server.server_id())
 9083                    else {
 9084                        continue;
 9085                    };
 9086                    if filter.should_send_will_rename(&old_uri, is_dir) {
 9087                        let apply_edit = cx.spawn({
 9088                            let old_uri = old_uri.clone();
 9089                            let new_uri = new_uri.clone();
 9090                            let language_server = language_server.clone();
 9091                            async move |this, cx| {
 9092                                let edit = language_server
 9093                                    .request::<WillRenameFiles>(RenameFilesParams {
 9094                                        files: vec![FileRename { old_uri, new_uri }],
 9095                                    })
 9096                                    .await
 9097                                    .into_response()
 9098                                    .context("will rename files")
 9099                                    .log_err()
 9100                                    .flatten()?;
 9101
 9102                                LocalLspStore::deserialize_workspace_edit(
 9103                                    this.upgrade()?,
 9104                                    edit,
 9105                                    false,
 9106                                    adapter.clone(),
 9107                                    language_server.clone(),
 9108                                    cx,
 9109                                )
 9110                                .await
 9111                                .ok();
 9112                                Some(())
 9113                            }
 9114                        });
 9115                        tasks.push(apply_edit);
 9116                    }
 9117                }
 9118                Some(())
 9119            })
 9120            .ok()
 9121            .flatten();
 9122            for task in tasks {
 9123                // Await on tasks sequentially so that the order of application of edits is deterministic
 9124                // (at least with regards to the order of registration of language servers)
 9125                task.await;
 9126            }
 9127        })
 9128    }
 9129
 9130    fn lsp_notify_abs_paths_changed(
 9131        &mut self,
 9132        server_id: LanguageServerId,
 9133        changes: Vec<PathEvent>,
 9134    ) {
 9135        maybe!({
 9136            let server = self.language_server_for_id(server_id)?;
 9137            let changes = changes
 9138                .into_iter()
 9139                .filter_map(|event| {
 9140                    let typ = match event.kind? {
 9141                        PathEventKind::Created => lsp::FileChangeType::CREATED,
 9142                        PathEventKind::Removed => lsp::FileChangeType::DELETED,
 9143                        PathEventKind::Changed => lsp::FileChangeType::CHANGED,
 9144                    };
 9145                    Some(lsp::FileEvent {
 9146                        uri: file_path_to_lsp_url(&event.path).log_err()?,
 9147                        typ,
 9148                    })
 9149                })
 9150                .collect::<Vec<_>>();
 9151            if !changes.is_empty() {
 9152                server
 9153                    .notify::<lsp::notification::DidChangeWatchedFiles>(
 9154                        &lsp::DidChangeWatchedFilesParams { changes },
 9155                    )
 9156                    .ok();
 9157            }
 9158            Some(())
 9159        });
 9160    }
 9161
 9162    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
 9163        let local_lsp_store = self.as_local()?;
 9164        if let Some(LanguageServerState::Running { server, .. }) =
 9165            local_lsp_store.language_servers.get(&id)
 9166        {
 9167            Some(server.clone())
 9168        } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
 9169            Some(Arc::clone(server))
 9170        } else {
 9171            None
 9172        }
 9173    }
 9174
 9175    fn on_lsp_progress(
 9176        &mut self,
 9177        progress: lsp::ProgressParams,
 9178        language_server_id: LanguageServerId,
 9179        disk_based_diagnostics_progress_token: Option<String>,
 9180        cx: &mut Context<Self>,
 9181    ) {
 9182        let token = match progress.token {
 9183            lsp::NumberOrString::String(token) => token,
 9184            lsp::NumberOrString::Number(token) => {
 9185                log::info!("skipping numeric progress token {}", token);
 9186                return;
 9187            }
 9188        };
 9189
 9190        match progress.value {
 9191            lsp::ProgressParamsValue::WorkDone(progress) => {
 9192                self.handle_work_done_progress(
 9193                    progress,
 9194                    language_server_id,
 9195                    disk_based_diagnostics_progress_token,
 9196                    token,
 9197                    cx,
 9198                );
 9199            }
 9200            lsp::ProgressParamsValue::WorkspaceDiagnostic(report) => {
 9201                if let Some(LanguageServerState::Running {
 9202                    workspace_refresh_task: Some(workspace_refresh_task),
 9203                    ..
 9204                }) = self
 9205                    .as_local_mut()
 9206                    .and_then(|local| local.language_servers.get_mut(&language_server_id))
 9207                {
 9208                    workspace_refresh_task.progress_tx.try_send(()).ok();
 9209                    self.apply_workspace_diagnostic_report(language_server_id, report, cx)
 9210                }
 9211            }
 9212        }
 9213    }
 9214
 9215    fn handle_work_done_progress(
 9216        &mut self,
 9217        progress: lsp::WorkDoneProgress,
 9218        language_server_id: LanguageServerId,
 9219        disk_based_diagnostics_progress_token: Option<String>,
 9220        token: String,
 9221        cx: &mut Context<Self>,
 9222    ) {
 9223        let language_server_status =
 9224            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 9225                status
 9226            } else {
 9227                return;
 9228            };
 9229
 9230        if !language_server_status.progress_tokens.contains(&token) {
 9231            return;
 9232        }
 9233
 9234        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 9235            .as_ref()
 9236            .map_or(false, |disk_based_token| {
 9237                token.starts_with(disk_based_token)
 9238            });
 9239
 9240        match progress {
 9241            lsp::WorkDoneProgress::Begin(report) => {
 9242                if is_disk_based_diagnostics_progress {
 9243                    self.disk_based_diagnostics_started(language_server_id, cx);
 9244                }
 9245                self.on_lsp_work_start(
 9246                    language_server_id,
 9247                    token.clone(),
 9248                    LanguageServerProgress {
 9249                        title: Some(report.title),
 9250                        is_disk_based_diagnostics_progress,
 9251                        is_cancellable: report.cancellable.unwrap_or(false),
 9252                        message: report.message.clone(),
 9253                        percentage: report.percentage.map(|p| p as usize),
 9254                        last_update_at: cx.background_executor().now(),
 9255                    },
 9256                    cx,
 9257                );
 9258            }
 9259            lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
 9260                language_server_id,
 9261                token,
 9262                LanguageServerProgress {
 9263                    title: None,
 9264                    is_disk_based_diagnostics_progress,
 9265                    is_cancellable: report.cancellable.unwrap_or(false),
 9266                    message: report.message,
 9267                    percentage: report.percentage.map(|p| p as usize),
 9268                    last_update_at: cx.background_executor().now(),
 9269                },
 9270                cx,
 9271            ),
 9272            lsp::WorkDoneProgress::End(_) => {
 9273                language_server_status.progress_tokens.remove(&token);
 9274                self.on_lsp_work_end(language_server_id, token.clone(), cx);
 9275                if is_disk_based_diagnostics_progress {
 9276                    self.disk_based_diagnostics_finished(language_server_id, cx);
 9277                }
 9278            }
 9279        }
 9280    }
 9281
 9282    fn on_lsp_work_start(
 9283        &mut self,
 9284        language_server_id: LanguageServerId,
 9285        token: String,
 9286        progress: LanguageServerProgress,
 9287        cx: &mut Context<Self>,
 9288    ) {
 9289        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 9290            status.pending_work.insert(token.clone(), progress.clone());
 9291            cx.notify();
 9292        }
 9293        cx.emit(LspStoreEvent::LanguageServerUpdate {
 9294            language_server_id,
 9295            name: self
 9296                .language_server_adapter_for_id(language_server_id)
 9297                .map(|adapter| adapter.name()),
 9298            message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 9299                token,
 9300                title: progress.title,
 9301                message: progress.message,
 9302                percentage: progress.percentage.map(|p| p as u32),
 9303                is_cancellable: Some(progress.is_cancellable),
 9304            }),
 9305        })
 9306    }
 9307
 9308    fn on_lsp_work_progress(
 9309        &mut self,
 9310        language_server_id: LanguageServerId,
 9311        token: String,
 9312        progress: LanguageServerProgress,
 9313        cx: &mut Context<Self>,
 9314    ) {
 9315        let mut did_update = false;
 9316        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 9317            match status.pending_work.entry(token.clone()) {
 9318                btree_map::Entry::Vacant(entry) => {
 9319                    entry.insert(progress.clone());
 9320                    did_update = true;
 9321                }
 9322                btree_map::Entry::Occupied(mut entry) => {
 9323                    let entry = entry.get_mut();
 9324                    if (progress.last_update_at - entry.last_update_at)
 9325                        >= SERVER_PROGRESS_THROTTLE_TIMEOUT
 9326                    {
 9327                        entry.last_update_at = progress.last_update_at;
 9328                        if progress.message.is_some() {
 9329                            entry.message = progress.message.clone();
 9330                        }
 9331                        if progress.percentage.is_some() {
 9332                            entry.percentage = progress.percentage;
 9333                        }
 9334                        if progress.is_cancellable != entry.is_cancellable {
 9335                            entry.is_cancellable = progress.is_cancellable;
 9336                        }
 9337                        did_update = true;
 9338                    }
 9339                }
 9340            }
 9341        }
 9342
 9343        if did_update {
 9344            cx.emit(LspStoreEvent::LanguageServerUpdate {
 9345                language_server_id,
 9346                name: self
 9347                    .language_server_adapter_for_id(language_server_id)
 9348                    .map(|adapter| adapter.name()),
 9349                message: proto::update_language_server::Variant::WorkProgress(
 9350                    proto::LspWorkProgress {
 9351                        token,
 9352                        message: progress.message,
 9353                        percentage: progress.percentage.map(|p| p as u32),
 9354                        is_cancellable: Some(progress.is_cancellable),
 9355                    },
 9356                ),
 9357            })
 9358        }
 9359    }
 9360
 9361    fn on_lsp_work_end(
 9362        &mut self,
 9363        language_server_id: LanguageServerId,
 9364        token: String,
 9365        cx: &mut Context<Self>,
 9366    ) {
 9367        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 9368            if let Some(work) = status.pending_work.remove(&token) {
 9369                if !work.is_disk_based_diagnostics_progress {
 9370                    cx.emit(LspStoreEvent::RefreshInlayHints);
 9371                }
 9372            }
 9373            cx.notify();
 9374        }
 9375
 9376        cx.emit(LspStoreEvent::LanguageServerUpdate {
 9377            language_server_id,
 9378            name: self
 9379                .language_server_adapter_for_id(language_server_id)
 9380                .map(|adapter| adapter.name()),
 9381            message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
 9382        })
 9383    }
 9384
 9385    pub async fn handle_resolve_completion_documentation(
 9386        this: Entity<Self>,
 9387        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 9388        mut cx: AsyncApp,
 9389    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 9390        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 9391
 9392        let completion = this
 9393            .read_with(&cx, |this, cx| {
 9394                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 9395                let server = this
 9396                    .language_server_for_id(id)
 9397                    .with_context(|| format!("No language server {id}"))?;
 9398
 9399                anyhow::Ok(cx.background_spawn(async move {
 9400                    let can_resolve = server
 9401                        .capabilities()
 9402                        .completion_provider
 9403                        .as_ref()
 9404                        .and_then(|options| options.resolve_provider)
 9405                        .unwrap_or(false);
 9406                    if can_resolve {
 9407                        server
 9408                            .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
 9409                            .await
 9410                            .into_response()
 9411                            .context("resolve completion item")
 9412                    } else {
 9413                        anyhow::Ok(lsp_completion)
 9414                    }
 9415                }))
 9416            })??
 9417            .await?;
 9418
 9419        let mut documentation_is_markdown = false;
 9420        let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
 9421        let documentation = match completion.documentation {
 9422            Some(lsp::Documentation::String(text)) => text,
 9423
 9424            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 9425                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 9426                value
 9427            }
 9428
 9429            _ => String::new(),
 9430        };
 9431
 9432        // If we have a new buffer_id, that means we're talking to a new client
 9433        // and want to check for new text_edits in the completion too.
 9434        let mut old_replace_start = None;
 9435        let mut old_replace_end = None;
 9436        let mut old_insert_start = None;
 9437        let mut old_insert_end = None;
 9438        let mut new_text = String::default();
 9439        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9440            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9441                let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9442                anyhow::Ok(buffer.read(cx).snapshot())
 9443            })??;
 9444
 9445            if let Some(text_edit) = completion.text_edit.as_ref() {
 9446                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9447
 9448                if let Some(mut edit) = edit {
 9449                    LineEnding::normalize(&mut edit.new_text);
 9450
 9451                    new_text = edit.new_text;
 9452                    old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
 9453                    old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
 9454                    if let Some(insert_range) = edit.insert_range {
 9455                        old_insert_start = Some(serialize_anchor(&insert_range.start));
 9456                        old_insert_end = Some(serialize_anchor(&insert_range.end));
 9457                    }
 9458                }
 9459            }
 9460        }
 9461
 9462        Ok(proto::ResolveCompletionDocumentationResponse {
 9463            documentation,
 9464            documentation_is_markdown,
 9465            old_replace_start,
 9466            old_replace_end,
 9467            new_text,
 9468            lsp_completion,
 9469            old_insert_start,
 9470            old_insert_end,
 9471        })
 9472    }
 9473
 9474    async fn handle_on_type_formatting(
 9475        this: Entity<Self>,
 9476        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9477        mut cx: AsyncApp,
 9478    ) -> Result<proto::OnTypeFormattingResponse> {
 9479        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9480            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9481            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9482            let position = envelope
 9483                .payload
 9484                .position
 9485                .and_then(deserialize_anchor)
 9486                .context("invalid position")?;
 9487            anyhow::Ok(this.apply_on_type_formatting(
 9488                buffer,
 9489                position,
 9490                envelope.payload.trigger.clone(),
 9491                cx,
 9492            ))
 9493        })??;
 9494
 9495        let transaction = on_type_formatting
 9496            .await?
 9497            .as_ref()
 9498            .map(language::proto::serialize_transaction);
 9499        Ok(proto::OnTypeFormattingResponse { transaction })
 9500    }
 9501
 9502    async fn handle_refresh_inlay_hints(
 9503        this: Entity<Self>,
 9504        _: TypedEnvelope<proto::RefreshInlayHints>,
 9505        mut cx: AsyncApp,
 9506    ) -> Result<proto::Ack> {
 9507        this.update(&mut cx, |_, cx| {
 9508            cx.emit(LspStoreEvent::RefreshInlayHints);
 9509        })?;
 9510        Ok(proto::Ack {})
 9511    }
 9512
 9513    async fn handle_pull_workspace_diagnostics(
 9514        lsp_store: Entity<Self>,
 9515        envelope: TypedEnvelope<proto::PullWorkspaceDiagnostics>,
 9516        mut cx: AsyncApp,
 9517    ) -> Result<proto::Ack> {
 9518        let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
 9519        lsp_store.update(&mut cx, |lsp_store, _| {
 9520            lsp_store.pull_workspace_diagnostics(server_id);
 9521        })?;
 9522        Ok(proto::Ack {})
 9523    }
 9524
 9525    async fn handle_inlay_hints(
 9526        this: Entity<Self>,
 9527        envelope: TypedEnvelope<proto::InlayHints>,
 9528        mut cx: AsyncApp,
 9529    ) -> Result<proto::InlayHintsResponse> {
 9530        let sender_id = envelope.original_sender_id().unwrap_or_default();
 9531        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9532        let buffer = this.update(&mut cx, |this, cx| {
 9533            this.buffer_store.read(cx).get_existing(buffer_id)
 9534        })??;
 9535        buffer
 9536            .update(&mut cx, |buffer, _| {
 9537                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9538            })?
 9539            .await
 9540            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9541
 9542        let start = envelope
 9543            .payload
 9544            .start
 9545            .and_then(deserialize_anchor)
 9546            .context("missing range start")?;
 9547        let end = envelope
 9548            .payload
 9549            .end
 9550            .and_then(deserialize_anchor)
 9551            .context("missing range end")?;
 9552        let buffer_hints = this
 9553            .update(&mut cx, |lsp_store, cx| {
 9554                lsp_store.inlay_hints(buffer.clone(), start..end, cx)
 9555            })?
 9556            .await
 9557            .context("inlay hints fetch")?;
 9558
 9559        this.update(&mut cx, |project, cx| {
 9560            InlayHints::response_to_proto(
 9561                buffer_hints,
 9562                project,
 9563                sender_id,
 9564                &buffer.read(cx).version(),
 9565                cx,
 9566            )
 9567        })
 9568    }
 9569
 9570    async fn handle_get_color_presentation(
 9571        lsp_store: Entity<Self>,
 9572        envelope: TypedEnvelope<proto::GetColorPresentation>,
 9573        mut cx: AsyncApp,
 9574    ) -> Result<proto::GetColorPresentationResponse> {
 9575        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9576        let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
 9577            lsp_store.buffer_store.read(cx).get_existing(buffer_id)
 9578        })??;
 9579
 9580        let color = envelope
 9581            .payload
 9582            .color
 9583            .context("invalid color resolve request")?;
 9584        let start = color
 9585            .lsp_range_start
 9586            .context("invalid color resolve request")?;
 9587        let end = color
 9588            .lsp_range_end
 9589            .context("invalid color resolve request")?;
 9590
 9591        let color = DocumentColor {
 9592            lsp_range: lsp::Range {
 9593                start: point_to_lsp(PointUtf16::new(start.row, start.column)),
 9594                end: point_to_lsp(PointUtf16::new(end.row, end.column)),
 9595            },
 9596            color: lsp::Color {
 9597                red: color.red,
 9598                green: color.green,
 9599                blue: color.blue,
 9600                alpha: color.alpha,
 9601            },
 9602            resolved: false,
 9603            color_presentations: Vec::new(),
 9604        };
 9605        let resolved_color = lsp_store
 9606            .update(&mut cx, |lsp_store, cx| {
 9607                lsp_store.resolve_color_presentation(
 9608                    color,
 9609                    buffer.clone(),
 9610                    LanguageServerId(envelope.payload.server_id as usize),
 9611                    cx,
 9612                )
 9613            })?
 9614            .await
 9615            .context("resolving color presentation")?;
 9616
 9617        Ok(proto::GetColorPresentationResponse {
 9618            presentations: resolved_color
 9619                .color_presentations
 9620                .into_iter()
 9621                .map(|presentation| proto::ColorPresentation {
 9622                    label: presentation.label.to_string(),
 9623                    text_edit: presentation.text_edit.map(serialize_lsp_edit),
 9624                    additional_text_edits: presentation
 9625                        .additional_text_edits
 9626                        .into_iter()
 9627                        .map(serialize_lsp_edit)
 9628                        .collect(),
 9629                })
 9630                .collect(),
 9631        })
 9632    }
 9633
 9634    async fn handle_resolve_inlay_hint(
 9635        this: Entity<Self>,
 9636        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9637        mut cx: AsyncApp,
 9638    ) -> Result<proto::ResolveInlayHintResponse> {
 9639        let proto_hint = envelope
 9640            .payload
 9641            .hint
 9642            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9643        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9644            .context("resolved proto inlay hint conversion")?;
 9645        let buffer = this.update(&mut cx, |this, cx| {
 9646            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9647            this.buffer_store.read(cx).get_existing(buffer_id)
 9648        })??;
 9649        let response_hint = this
 9650            .update(&mut cx, |this, cx| {
 9651                this.resolve_inlay_hint(
 9652                    hint,
 9653                    buffer,
 9654                    LanguageServerId(envelope.payload.language_server_id as usize),
 9655                    cx,
 9656                )
 9657            })?
 9658            .await
 9659            .context("inlay hints fetch")?;
 9660        Ok(proto::ResolveInlayHintResponse {
 9661            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9662        })
 9663    }
 9664
 9665    async fn handle_refresh_code_lens(
 9666        this: Entity<Self>,
 9667        _: TypedEnvelope<proto::RefreshCodeLens>,
 9668        mut cx: AsyncApp,
 9669    ) -> Result<proto::Ack> {
 9670        this.update(&mut cx, |_, cx| {
 9671            cx.emit(LspStoreEvent::RefreshCodeLens);
 9672        })?;
 9673        Ok(proto::Ack {})
 9674    }
 9675
 9676    async fn handle_open_buffer_for_symbol(
 9677        this: Entity<Self>,
 9678        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9679        mut cx: AsyncApp,
 9680    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9681        let peer_id = envelope.original_sender_id().unwrap_or_default();
 9682        let symbol = envelope.payload.symbol.context("invalid symbol")?;
 9683        let symbol = Self::deserialize_symbol(symbol)?;
 9684        let symbol = this.read_with(&mut cx, |this, _| {
 9685            let signature = this.symbol_signature(&symbol.path);
 9686            anyhow::ensure!(signature == symbol.signature, "invalid symbol signature");
 9687            Ok(symbol)
 9688        })??;
 9689        let buffer = this
 9690            .update(&mut cx, |this, cx| {
 9691                this.open_buffer_for_symbol(
 9692                    &Symbol {
 9693                        language_server_name: symbol.language_server_name,
 9694                        source_worktree_id: symbol.source_worktree_id,
 9695                        source_language_server_id: symbol.source_language_server_id,
 9696                        path: symbol.path,
 9697                        name: symbol.name,
 9698                        kind: symbol.kind,
 9699                        range: symbol.range,
 9700                        signature: symbol.signature,
 9701                        label: CodeLabel {
 9702                            text: Default::default(),
 9703                            runs: Default::default(),
 9704                            filter_range: Default::default(),
 9705                        },
 9706                    },
 9707                    cx,
 9708                )
 9709            })?
 9710            .await?;
 9711
 9712        this.update(&mut cx, |this, cx| {
 9713            let is_private = buffer
 9714                .read(cx)
 9715                .file()
 9716                .map(|f| f.is_private())
 9717                .unwrap_or_default();
 9718            if is_private {
 9719                Err(anyhow!(rpc::ErrorCode::UnsharedItem))
 9720            } else {
 9721                this.buffer_store
 9722                    .update(cx, |buffer_store, cx| {
 9723                        buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
 9724                    })
 9725                    .detach_and_log_err(cx);
 9726                let buffer_id = buffer.read(cx).remote_id().to_proto();
 9727                Ok(proto::OpenBufferForSymbolResponse { buffer_id })
 9728            }
 9729        })?
 9730    }
 9731
 9732    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9733        let mut hasher = Sha256::new();
 9734        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9735        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9736        hasher.update(self.nonce.to_be_bytes());
 9737        hasher.finalize().as_slice().try_into().unwrap()
 9738    }
 9739
 9740    pub async fn handle_get_project_symbols(
 9741        this: Entity<Self>,
 9742        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9743        mut cx: AsyncApp,
 9744    ) -> Result<proto::GetProjectSymbolsResponse> {
 9745        let symbols = this
 9746            .update(&mut cx, |this, cx| {
 9747                this.symbols(&envelope.payload.query, cx)
 9748            })?
 9749            .await?;
 9750
 9751        Ok(proto::GetProjectSymbolsResponse {
 9752            symbols: symbols.iter().map(Self::serialize_symbol).collect(),
 9753        })
 9754    }
 9755
 9756    pub async fn handle_restart_language_servers(
 9757        this: Entity<Self>,
 9758        envelope: TypedEnvelope<proto::RestartLanguageServers>,
 9759        mut cx: AsyncApp,
 9760    ) -> Result<proto::Ack> {
 9761        this.update(&mut cx, |lsp_store, cx| {
 9762            let buffers =
 9763                lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
 9764            lsp_store.restart_language_servers_for_buffers(
 9765                buffers,
 9766                envelope
 9767                    .payload
 9768                    .only_servers
 9769                    .into_iter()
 9770                    .filter_map(|selector| {
 9771                        Some(match selector.selector? {
 9772                            proto::language_server_selector::Selector::ServerId(server_id) => {
 9773                                LanguageServerSelector::Id(LanguageServerId::from_proto(server_id))
 9774                            }
 9775                            proto::language_server_selector::Selector::Name(name) => {
 9776                                LanguageServerSelector::Name(LanguageServerName(
 9777                                    SharedString::from(name),
 9778                                ))
 9779                            }
 9780                        })
 9781                    })
 9782                    .collect(),
 9783                cx,
 9784            );
 9785        })?;
 9786
 9787        Ok(proto::Ack {})
 9788    }
 9789
 9790    pub async fn handle_stop_language_servers(
 9791        lsp_store: Entity<Self>,
 9792        envelope: TypedEnvelope<proto::StopLanguageServers>,
 9793        mut cx: AsyncApp,
 9794    ) -> Result<proto::Ack> {
 9795        lsp_store.update(&mut cx, |lsp_store, cx| {
 9796            if envelope.payload.all
 9797                && envelope.payload.also_servers.is_empty()
 9798                && envelope.payload.buffer_ids.is_empty()
 9799            {
 9800                lsp_store.stop_all_language_servers(cx);
 9801            } else {
 9802                let buffers =
 9803                    lsp_store.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
 9804                lsp_store
 9805                    .stop_language_servers_for_buffers(
 9806                        buffers,
 9807                        envelope
 9808                            .payload
 9809                            .also_servers
 9810                            .into_iter()
 9811                            .filter_map(|selector| {
 9812                                Some(match selector.selector? {
 9813                                    proto::language_server_selector::Selector::ServerId(
 9814                                        server_id,
 9815                                    ) => LanguageServerSelector::Id(LanguageServerId::from_proto(
 9816                                        server_id,
 9817                                    )),
 9818                                    proto::language_server_selector::Selector::Name(name) => {
 9819                                        LanguageServerSelector::Name(LanguageServerName(
 9820                                            SharedString::from(name),
 9821                                        ))
 9822                                    }
 9823                                })
 9824                            })
 9825                            .collect(),
 9826                        cx,
 9827                    )
 9828                    .detach_and_log_err(cx);
 9829            }
 9830        })?;
 9831
 9832        Ok(proto::Ack {})
 9833    }
 9834
 9835    pub async fn handle_cancel_language_server_work(
 9836        this: Entity<Self>,
 9837        envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
 9838        mut cx: AsyncApp,
 9839    ) -> Result<proto::Ack> {
 9840        this.update(&mut cx, |this, cx| {
 9841            if let Some(work) = envelope.payload.work {
 9842                match work {
 9843                    proto::cancel_language_server_work::Work::Buffers(buffers) => {
 9844                        let buffers =
 9845                            this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
 9846                        this.cancel_language_server_work_for_buffers(buffers, cx);
 9847                    }
 9848                    proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
 9849                        let server_id = LanguageServerId::from_proto(work.language_server_id);
 9850                        this.cancel_language_server_work(server_id, work.token, cx);
 9851                    }
 9852                }
 9853            }
 9854        })?;
 9855
 9856        Ok(proto::Ack {})
 9857    }
 9858
 9859    fn buffer_ids_to_buffers(
 9860        &mut self,
 9861        buffer_ids: impl Iterator<Item = u64>,
 9862        cx: &mut Context<Self>,
 9863    ) -> Vec<Entity<Buffer>> {
 9864        buffer_ids
 9865            .into_iter()
 9866            .flat_map(|buffer_id| {
 9867                self.buffer_store
 9868                    .read(cx)
 9869                    .get(BufferId::new(buffer_id).log_err()?)
 9870            })
 9871            .collect::<Vec<_>>()
 9872    }
 9873
 9874    async fn handle_apply_additional_edits_for_completion(
 9875        this: Entity<Self>,
 9876        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 9877        mut cx: AsyncApp,
 9878    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 9879        let (buffer, completion) = this.update(&mut cx, |this, cx| {
 9880            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9881            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9882            let completion = Self::deserialize_completion(
 9883                envelope.payload.completion.context("invalid completion")?,
 9884            )?;
 9885            anyhow::Ok((buffer, completion))
 9886        })??;
 9887
 9888        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 9889            this.apply_additional_edits_for_completion(
 9890                buffer,
 9891                Rc::new(RefCell::new(Box::new([Completion {
 9892                    replace_range: completion.replace_range,
 9893                    new_text: completion.new_text,
 9894                    source: completion.source,
 9895                    documentation: None,
 9896                    label: CodeLabel {
 9897                        text: Default::default(),
 9898                        runs: Default::default(),
 9899                        filter_range: Default::default(),
 9900                    },
 9901                    insert_text_mode: None,
 9902                    icon_path: None,
 9903                    confirm: None,
 9904                }]))),
 9905                0,
 9906                false,
 9907                cx,
 9908            )
 9909        })?;
 9910
 9911        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 9912            transaction: apply_additional_edits
 9913                .await?
 9914                .as_ref()
 9915                .map(language::proto::serialize_transaction),
 9916        })
 9917    }
 9918
 9919    pub fn last_formatting_failure(&self) -> Option<&str> {
 9920        self.last_formatting_failure.as_deref()
 9921    }
 9922
 9923    pub fn reset_last_formatting_failure(&mut self) {
 9924        self.last_formatting_failure = None;
 9925    }
 9926
 9927    pub fn environment_for_buffer(
 9928        &self,
 9929        buffer: &Entity<Buffer>,
 9930        cx: &mut Context<Self>,
 9931    ) -> Shared<Task<Option<HashMap<String, String>>>> {
 9932        if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
 9933            environment.update(cx, |env, cx| {
 9934                env.get_buffer_environment(&buffer, &self.worktree_store, cx)
 9935            })
 9936        } else {
 9937            Task::ready(None).shared()
 9938        }
 9939    }
 9940
 9941    pub fn format(
 9942        &mut self,
 9943        buffers: HashSet<Entity<Buffer>>,
 9944        target: LspFormatTarget,
 9945        push_to_history: bool,
 9946        trigger: FormatTrigger,
 9947        cx: &mut Context<Self>,
 9948    ) -> Task<anyhow::Result<ProjectTransaction>> {
 9949        let logger = zlog::scoped!("format");
 9950        if let Some(_) = self.as_local() {
 9951            zlog::trace!(logger => "Formatting locally");
 9952            let logger = zlog::scoped!(logger => "local");
 9953            let buffers = buffers
 9954                .into_iter()
 9955                .map(|buffer_handle| {
 9956                    let buffer = buffer_handle.read(cx);
 9957                    let buffer_abs_path = File::from_dyn(buffer.file())
 9958                        .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
 9959
 9960                    (buffer_handle, buffer_abs_path, buffer.remote_id())
 9961                })
 9962                .collect::<Vec<_>>();
 9963
 9964            cx.spawn(async move |lsp_store, cx| {
 9965                let mut formattable_buffers = Vec::with_capacity(buffers.len());
 9966
 9967                for (handle, abs_path, id) in buffers {
 9968                    let env = lsp_store
 9969                        .update(cx, |lsp_store, cx| {
 9970                            lsp_store.environment_for_buffer(&handle, cx)
 9971                        })?
 9972                        .await;
 9973
 9974                    let ranges = match &target {
 9975                        LspFormatTarget::Buffers => None,
 9976                        LspFormatTarget::Ranges(ranges) => {
 9977                            Some(ranges.get(&id).context("No format ranges provided for buffer")?.clone())
 9978                        }
 9979                    };
 9980
 9981                    formattable_buffers.push(FormattableBuffer {
 9982                        handle,
 9983                        abs_path,
 9984                        env,
 9985                        ranges,
 9986                    });
 9987                }
 9988                zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
 9989
 9990                let format_timer = zlog::time!(logger => "Formatting buffers");
 9991                let result = LocalLspStore::format_locally(
 9992                    lsp_store.clone(),
 9993                    formattable_buffers,
 9994                    push_to_history,
 9995                    trigger,
 9996                    logger,
 9997                    cx,
 9998                )
 9999                .await;
10000                format_timer.end();
10001
10002                zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
10003
10004                lsp_store.update(cx, |lsp_store, _| {
10005                    lsp_store.update_last_formatting_failure(&result);
10006                })?;
10007
10008                result
10009            })
10010        } else if let Some((client, project_id)) = self.upstream_client() {
10011            zlog::trace!(logger => "Formatting remotely");
10012            let logger = zlog::scoped!(logger => "remote");
10013            // Don't support formatting ranges via remote
10014            match target {
10015                LspFormatTarget::Buffers => {}
10016                LspFormatTarget::Ranges(_) => {
10017                    zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
10018                    return Task::ready(Ok(ProjectTransaction::default()));
10019                }
10020            }
10021
10022            let buffer_store = self.buffer_store();
10023            cx.spawn(async move |lsp_store, cx| {
10024                zlog::trace!(logger => "Sending remote format request");
10025                let request_timer = zlog::time!(logger => "remote format request");
10026                let result = client
10027                    .request(proto::FormatBuffers {
10028                        project_id,
10029                        trigger: trigger as i32,
10030                        buffer_ids: buffers
10031                            .iter()
10032                            .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id().into()))
10033                            .collect::<Result<_>>()?,
10034                    })
10035                    .await
10036                    .and_then(|result| result.transaction.context("missing transaction"));
10037                request_timer.end();
10038
10039                zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
10040
10041                lsp_store.update(cx, |lsp_store, _| {
10042                    lsp_store.update_last_formatting_failure(&result);
10043                })?;
10044
10045                let transaction_response = result?;
10046                let _timer = zlog::time!(logger => "deserializing project transaction");
10047                buffer_store
10048                    .update(cx, |buffer_store, cx| {
10049                        buffer_store.deserialize_project_transaction(
10050                            transaction_response,
10051                            push_to_history,
10052                            cx,
10053                        )
10054                    })?
10055                    .await
10056            })
10057        } else {
10058            zlog::trace!(logger => "Not formatting");
10059            Task::ready(Ok(ProjectTransaction::default()))
10060        }
10061    }
10062
10063    async fn handle_format_buffers(
10064        this: Entity<Self>,
10065        envelope: TypedEnvelope<proto::FormatBuffers>,
10066        mut cx: AsyncApp,
10067    ) -> Result<proto::FormatBuffersResponse> {
10068        let sender_id = envelope.original_sender_id().unwrap_or_default();
10069        let format = this.update(&mut cx, |this, cx| {
10070            let mut buffers = HashSet::default();
10071            for buffer_id in &envelope.payload.buffer_ids {
10072                let buffer_id = BufferId::new(*buffer_id)?;
10073                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
10074            }
10075            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
10076            anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
10077        })??;
10078
10079        let project_transaction = format.await?;
10080        let project_transaction = this.update(&mut cx, |this, cx| {
10081            this.buffer_store.update(cx, |buffer_store, cx| {
10082                buffer_store.serialize_project_transaction_for_peer(
10083                    project_transaction,
10084                    sender_id,
10085                    cx,
10086                )
10087            })
10088        })?;
10089        Ok(proto::FormatBuffersResponse {
10090            transaction: Some(project_transaction),
10091        })
10092    }
10093
10094    async fn handle_apply_code_action_kind(
10095        this: Entity<Self>,
10096        envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
10097        mut cx: AsyncApp,
10098    ) -> Result<proto::ApplyCodeActionKindResponse> {
10099        let sender_id = envelope.original_sender_id().unwrap_or_default();
10100        let format = this.update(&mut cx, |this, cx| {
10101            let mut buffers = HashSet::default();
10102            for buffer_id in &envelope.payload.buffer_ids {
10103                let buffer_id = BufferId::new(*buffer_id)?;
10104                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
10105            }
10106            let kind = match envelope.payload.kind.as_str() {
10107                "" => CodeActionKind::EMPTY,
10108                "quickfix" => CodeActionKind::QUICKFIX,
10109                "refactor" => CodeActionKind::REFACTOR,
10110                "refactor.extract" => CodeActionKind::REFACTOR_EXTRACT,
10111                "refactor.inline" => CodeActionKind::REFACTOR_INLINE,
10112                "refactor.rewrite" => CodeActionKind::REFACTOR_REWRITE,
10113                "source" => CodeActionKind::SOURCE,
10114                "source.organizeImports" => CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
10115                "source.fixAll" => CodeActionKind::SOURCE_FIX_ALL,
10116                _ => anyhow::bail!(
10117                    "Invalid code action kind {}",
10118                    envelope.payload.kind.as_str()
10119                ),
10120            };
10121            anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
10122        })??;
10123
10124        let project_transaction = format.await?;
10125        let project_transaction = this.update(&mut cx, |this, cx| {
10126            this.buffer_store.update(cx, |buffer_store, cx| {
10127                buffer_store.serialize_project_transaction_for_peer(
10128                    project_transaction,
10129                    sender_id,
10130                    cx,
10131                )
10132            })
10133        })?;
10134        Ok(proto::ApplyCodeActionKindResponse {
10135            transaction: Some(project_transaction),
10136        })
10137    }
10138
10139    async fn shutdown_language_server(
10140        server_state: Option<LanguageServerState>,
10141        name: LanguageServerName,
10142        cx: &mut AsyncApp,
10143    ) {
10144        let server = match server_state {
10145            Some(LanguageServerState::Starting { startup, .. }) => {
10146                let mut timer = cx
10147                    .background_executor()
10148                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
10149                    .fuse();
10150
10151                select! {
10152                    server = startup.fuse() => server,
10153                    () = timer => {
10154                        log::info!("timeout waiting for language server {name} to finish launching before stopping");
10155                        None
10156                    },
10157                }
10158            }
10159
10160            Some(LanguageServerState::Running { server, .. }) => Some(server),
10161
10162            None => None,
10163        };
10164
10165        if let Some(server) = server {
10166            if let Some(shutdown) = server.shutdown() {
10167                shutdown.await;
10168            }
10169        }
10170    }
10171
10172    // Returns a list of all of the worktrees which no longer have a language server and the root path
10173    // for the stopped server
10174    fn stop_local_language_server(
10175        &mut self,
10176        server_id: LanguageServerId,
10177        cx: &mut Context<Self>,
10178    ) -> Task<Vec<WorktreeId>> {
10179        let local = match &mut self.mode {
10180            LspStoreMode::Local(local) => local,
10181            _ => {
10182                return Task::ready(Vec::new());
10183            }
10184        };
10185
10186        let mut orphaned_worktrees = Vec::new();
10187        // Remove this server ID from all entries in the given worktree.
10188        local.language_server_ids.retain(|(worktree, _), ids| {
10189            if !ids.remove(&server_id) {
10190                return true;
10191            }
10192
10193            if ids.is_empty() {
10194                orphaned_worktrees.push(*worktree);
10195                false
10196            } else {
10197                true
10198            }
10199        });
10200        self.buffer_store.update(cx, |buffer_store, cx| {
10201            for buffer in buffer_store.buffers() {
10202                buffer.update(cx, |buffer, cx| {
10203                    buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
10204                    buffer.set_completion_triggers(server_id, Default::default(), cx);
10205                });
10206            }
10207        });
10208
10209        for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
10210            summaries.retain(|path, summaries_by_server_id| {
10211                if summaries_by_server_id.remove(&server_id).is_some() {
10212                    if let Some((client, project_id)) = self.downstream_client.clone() {
10213                        client
10214                            .send(proto::UpdateDiagnosticSummary {
10215                                project_id,
10216                                worktree_id: worktree_id.to_proto(),
10217                                summary: Some(proto::DiagnosticSummary {
10218                                    path: path.as_ref().to_proto(),
10219                                    language_server_id: server_id.0 as u64,
10220                                    error_count: 0,
10221                                    warning_count: 0,
10222                                }),
10223                            })
10224                            .log_err();
10225                    }
10226                    !summaries_by_server_id.is_empty()
10227                } else {
10228                    true
10229                }
10230            });
10231        }
10232
10233        let local = self.as_local_mut().unwrap();
10234        for diagnostics in local.diagnostics.values_mut() {
10235            diagnostics.retain(|_, diagnostics_by_server_id| {
10236                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
10237                    diagnostics_by_server_id.remove(ix);
10238                    !diagnostics_by_server_id.is_empty()
10239                } else {
10240                    true
10241                }
10242            });
10243        }
10244        local.language_server_watched_paths.remove(&server_id);
10245
10246        let server_state = local.language_servers.remove(&server_id);
10247        self.cleanup_lsp_data(server_id);
10248        let name = self
10249            .language_server_statuses
10250            .remove(&server_id)
10251            .map(|status| LanguageServerName::from(status.name.as_str()))
10252            .or_else(|| {
10253                if let Some(LanguageServerState::Running { adapter, .. }) = server_state.as_ref() {
10254                    Some(adapter.name())
10255                } else {
10256                    None
10257                }
10258            });
10259
10260        if let Some(name) = name {
10261            log::info!("stopping language server {name}");
10262            self.languages
10263                .update_lsp_binary_status(name.clone(), BinaryStatus::Stopping);
10264            cx.notify();
10265
10266            return cx.spawn(async move |lsp_store, cx| {
10267                Self::shutdown_language_server(server_state, name.clone(), cx).await;
10268                lsp_store
10269                    .update(cx, |lsp_store, cx| {
10270                        lsp_store
10271                            .languages
10272                            .update_lsp_binary_status(name, BinaryStatus::Stopped);
10273                        cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
10274                        cx.notify();
10275                    })
10276                    .ok();
10277                orphaned_worktrees
10278            });
10279        }
10280
10281        if server_state.is_some() {
10282            cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
10283        }
10284        Task::ready(orphaned_worktrees)
10285    }
10286
10287    pub fn stop_all_language_servers(&mut self, cx: &mut Context<Self>) {
10288        if let Some((client, project_id)) = self.upstream_client() {
10289            let request = client.request(proto::StopLanguageServers {
10290                project_id,
10291                buffer_ids: Vec::new(),
10292                also_servers: Vec::new(),
10293                all: true,
10294            });
10295            cx.background_spawn(request).detach_and_log_err(cx);
10296        } else {
10297            let Some(local) = self.as_local_mut() else {
10298                return;
10299            };
10300            let language_servers_to_stop = local
10301                .language_server_ids
10302                .values()
10303                .flatten()
10304                .copied()
10305                .collect();
10306            local.lsp_tree.update(cx, |this, _| {
10307                this.remove_nodes(&language_servers_to_stop);
10308            });
10309            let tasks = language_servers_to_stop
10310                .into_iter()
10311                .map(|server| self.stop_local_language_server(server, cx))
10312                .collect::<Vec<_>>();
10313            cx.background_spawn(async move {
10314                futures::future::join_all(tasks).await;
10315            })
10316            .detach();
10317        }
10318    }
10319
10320    pub fn restart_language_servers_for_buffers(
10321        &mut self,
10322        buffers: Vec<Entity<Buffer>>,
10323        only_restart_servers: HashSet<LanguageServerSelector>,
10324        cx: &mut Context<Self>,
10325    ) {
10326        if let Some((client, project_id)) = self.upstream_client() {
10327            let request = client.request(proto::RestartLanguageServers {
10328                project_id,
10329                buffer_ids: buffers
10330                    .into_iter()
10331                    .map(|b| b.read(cx).remote_id().to_proto())
10332                    .collect(),
10333                only_servers: only_restart_servers
10334                    .into_iter()
10335                    .map(|selector| {
10336                        let selector = match selector {
10337                            LanguageServerSelector::Id(language_server_id) => {
10338                                proto::language_server_selector::Selector::ServerId(
10339                                    language_server_id.to_proto(),
10340                                )
10341                            }
10342                            LanguageServerSelector::Name(language_server_name) => {
10343                                proto::language_server_selector::Selector::Name(
10344                                    language_server_name.to_string(),
10345                                )
10346                            }
10347                        };
10348                        proto::LanguageServerSelector {
10349                            selector: Some(selector),
10350                        }
10351                    })
10352                    .collect(),
10353                all: false,
10354            });
10355            cx.background_spawn(request).detach_and_log_err(cx);
10356        } else {
10357            let stop_task = if only_restart_servers.is_empty() {
10358                self.stop_local_language_servers_for_buffers(&buffers, HashSet::default(), cx)
10359            } else {
10360                self.stop_local_language_servers_for_buffers(&[], only_restart_servers.clone(), cx)
10361            };
10362            cx.spawn(async move |lsp_store, cx| {
10363                stop_task.await;
10364                lsp_store
10365                    .update(cx, |lsp_store, cx| {
10366                        for buffer in buffers {
10367                            lsp_store.register_buffer_with_language_servers(
10368                                &buffer,
10369                                only_restart_servers.clone(),
10370                                true,
10371                                cx,
10372                            );
10373                        }
10374                    })
10375                    .ok()
10376            })
10377            .detach();
10378        }
10379    }
10380
10381    pub fn stop_language_servers_for_buffers(
10382        &mut self,
10383        buffers: Vec<Entity<Buffer>>,
10384        also_stop_servers: HashSet<LanguageServerSelector>,
10385        cx: &mut Context<Self>,
10386    ) -> Task<Result<()>> {
10387        if let Some((client, project_id)) = self.upstream_client() {
10388            let request = client.request(proto::StopLanguageServers {
10389                project_id,
10390                buffer_ids: buffers
10391                    .into_iter()
10392                    .map(|b| b.read(cx).remote_id().to_proto())
10393                    .collect(),
10394                also_servers: also_stop_servers
10395                    .into_iter()
10396                    .map(|selector| {
10397                        let selector = match selector {
10398                            LanguageServerSelector::Id(language_server_id) => {
10399                                proto::language_server_selector::Selector::ServerId(
10400                                    language_server_id.to_proto(),
10401                                )
10402                            }
10403                            LanguageServerSelector::Name(language_server_name) => {
10404                                proto::language_server_selector::Selector::Name(
10405                                    language_server_name.to_string(),
10406                                )
10407                            }
10408                        };
10409                        proto::LanguageServerSelector {
10410                            selector: Some(selector),
10411                        }
10412                    })
10413                    .collect(),
10414                all: false,
10415            });
10416            cx.background_spawn(async move {
10417                let _ = request.await?;
10418                Ok(())
10419            })
10420        } else {
10421            let task =
10422                self.stop_local_language_servers_for_buffers(&buffers, also_stop_servers, cx);
10423            cx.background_spawn(async move {
10424                task.await;
10425                Ok(())
10426            })
10427        }
10428    }
10429
10430    fn stop_local_language_servers_for_buffers(
10431        &mut self,
10432        buffers: &[Entity<Buffer>],
10433        also_stop_servers: HashSet<LanguageServerSelector>,
10434        cx: &mut Context<Self>,
10435    ) -> Task<()> {
10436        let Some(local) = self.as_local_mut() else {
10437            return Task::ready(());
10438        };
10439        let mut language_server_names_to_stop = BTreeSet::default();
10440        let mut language_servers_to_stop = also_stop_servers
10441            .into_iter()
10442            .flat_map(|selector| match selector {
10443                LanguageServerSelector::Id(id) => Some(id),
10444                LanguageServerSelector::Name(name) => {
10445                    language_server_names_to_stop.insert(name);
10446                    None
10447                }
10448            })
10449            .collect::<BTreeSet<_>>();
10450
10451        let mut covered_worktrees = HashSet::default();
10452        for buffer in buffers {
10453            buffer.update(cx, |buffer, cx| {
10454                language_servers_to_stop.extend(local.language_server_ids_for_buffer(buffer, cx));
10455                if let Some(worktree_id) = buffer.file().map(|f| f.worktree_id(cx)) {
10456                    if covered_worktrees.insert(worktree_id) {
10457                        language_server_names_to_stop.retain(|name| {
10458                            match local.language_server_ids.get(&(worktree_id, name.clone())) {
10459                                Some(server_ids) => {
10460                                    language_servers_to_stop
10461                                        .extend(server_ids.into_iter().copied());
10462                                    false
10463                                }
10464                                None => true,
10465                            }
10466                        });
10467                    }
10468                }
10469            });
10470        }
10471        for name in language_server_names_to_stop {
10472            if let Some(server_ids) = local
10473                .language_server_ids
10474                .iter()
10475                .filter(|((_, server_name), _)| server_name == &name)
10476                .map(|((_, _), server_ids)| server_ids)
10477                .max_by_key(|server_ids| server_ids.len())
10478            {
10479                language_servers_to_stop.extend(server_ids.into_iter().copied());
10480            }
10481        }
10482
10483        local.lsp_tree.update(cx, |this, _| {
10484            this.remove_nodes(&language_servers_to_stop);
10485        });
10486        let tasks = language_servers_to_stop
10487            .into_iter()
10488            .map(|server| self.stop_local_language_server(server, cx))
10489            .collect::<Vec<_>>();
10490
10491        cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
10492    }
10493
10494    fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
10495        let (worktree, relative_path) =
10496            self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
10497
10498        let project_path = ProjectPath {
10499            worktree_id: worktree.read(cx).id(),
10500            path: relative_path.into(),
10501        };
10502
10503        Some(
10504            self.buffer_store()
10505                .read(cx)
10506                .get_by_path(&project_path)?
10507                .read(cx),
10508        )
10509    }
10510
10511    pub fn update_diagnostics(
10512        &mut self,
10513        language_server_id: LanguageServerId,
10514        params: lsp::PublishDiagnosticsParams,
10515        result_id: Option<String>,
10516        source_kind: DiagnosticSourceKind,
10517        disk_based_sources: &[String],
10518        cx: &mut Context<Self>,
10519    ) -> Result<()> {
10520        self.merge_diagnostics(
10521            language_server_id,
10522            params,
10523            result_id,
10524            source_kind,
10525            disk_based_sources,
10526            |_, _, _| false,
10527            cx,
10528        )
10529    }
10530
10531    pub fn merge_diagnostics(
10532        &mut self,
10533        language_server_id: LanguageServerId,
10534        mut params: lsp::PublishDiagnosticsParams,
10535        result_id: Option<String>,
10536        source_kind: DiagnosticSourceKind,
10537        disk_based_sources: &[String],
10538        filter: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
10539        cx: &mut Context<Self>,
10540    ) -> Result<()> {
10541        anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
10542        let abs_path = params
10543            .uri
10544            .to_file_path()
10545            .map_err(|()| anyhow!("URI is not a file"))?;
10546        let mut diagnostics = Vec::default();
10547        let mut primary_diagnostic_group_ids = HashMap::default();
10548        let mut sources_by_group_id = HashMap::default();
10549        let mut supporting_diagnostics = HashMap::default();
10550
10551        let adapter = self.language_server_adapter_for_id(language_server_id);
10552
10553        // Ensure that primary diagnostics are always the most severe
10554        params.diagnostics.sort_by_key(|item| item.severity);
10555
10556        for diagnostic in &params.diagnostics {
10557            let source = diagnostic.source.as_ref();
10558            let range = range_from_lsp(diagnostic.range);
10559            let is_supporting = diagnostic
10560                .related_information
10561                .as_ref()
10562                .map_or(false, |infos| {
10563                    infos.iter().any(|info| {
10564                        primary_diagnostic_group_ids.contains_key(&(
10565                            source,
10566                            diagnostic.code.clone(),
10567                            range_from_lsp(info.location.range),
10568                        ))
10569                    })
10570                });
10571
10572            let is_unnecessary = diagnostic
10573                .tags
10574                .as_ref()
10575                .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
10576
10577            let underline = self
10578                .language_server_adapter_for_id(language_server_id)
10579                .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
10580
10581            if is_supporting {
10582                supporting_diagnostics.insert(
10583                    (source, diagnostic.code.clone(), range),
10584                    (diagnostic.severity, is_unnecessary),
10585                );
10586            } else {
10587                let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
10588                let is_disk_based =
10589                    source.map_or(false, |source| disk_based_sources.contains(source));
10590
10591                sources_by_group_id.insert(group_id, source);
10592                primary_diagnostic_group_ids
10593                    .insert((source, diagnostic.code.clone(), range.clone()), group_id);
10594
10595                diagnostics.push(DiagnosticEntry {
10596                    range,
10597                    diagnostic: Diagnostic {
10598                        source: diagnostic.source.clone(),
10599                        source_kind,
10600                        code: diagnostic.code.clone(),
10601                        code_description: diagnostic
10602                            .code_description
10603                            .as_ref()
10604                            .and_then(|d| d.href.clone()),
10605                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
10606                        markdown: adapter.as_ref().and_then(|adapter| {
10607                            adapter.diagnostic_message_to_markdown(&diagnostic.message)
10608                        }),
10609                        message: diagnostic.message.trim().to_string(),
10610                        group_id,
10611                        is_primary: true,
10612                        is_disk_based,
10613                        is_unnecessary,
10614                        underline,
10615                        data: diagnostic.data.clone(),
10616                    },
10617                });
10618                if let Some(infos) = &diagnostic.related_information {
10619                    for info in infos {
10620                        if info.location.uri == params.uri && !info.message.is_empty() {
10621                            let range = range_from_lsp(info.location.range);
10622                            diagnostics.push(DiagnosticEntry {
10623                                range,
10624                                diagnostic: Diagnostic {
10625                                    source: diagnostic.source.clone(),
10626                                    source_kind,
10627                                    code: diagnostic.code.clone(),
10628                                    code_description: diagnostic
10629                                        .code_description
10630                                        .as_ref()
10631                                        .and_then(|d| d.href.clone()),
10632                                    severity: DiagnosticSeverity::INFORMATION,
10633                                    markdown: adapter.as_ref().and_then(|adapter| {
10634                                        adapter.diagnostic_message_to_markdown(&info.message)
10635                                    }),
10636                                    message: info.message.trim().to_string(),
10637                                    group_id,
10638                                    is_primary: false,
10639                                    is_disk_based,
10640                                    is_unnecessary: false,
10641                                    underline,
10642                                    data: diagnostic.data.clone(),
10643                                },
10644                            });
10645                        }
10646                    }
10647                }
10648            }
10649        }
10650
10651        for entry in &mut diagnostics {
10652            let diagnostic = &mut entry.diagnostic;
10653            if !diagnostic.is_primary {
10654                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
10655                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
10656                    source,
10657                    diagnostic.code.clone(),
10658                    entry.range.clone(),
10659                )) {
10660                    if let Some(severity) = severity {
10661                        diagnostic.severity = severity;
10662                    }
10663                    diagnostic.is_unnecessary = is_unnecessary;
10664                }
10665            }
10666        }
10667
10668        self.merge_diagnostic_entries(
10669            language_server_id,
10670            abs_path,
10671            result_id,
10672            params.version,
10673            diagnostics,
10674            filter,
10675            cx,
10676        )?;
10677        Ok(())
10678    }
10679
10680    fn insert_newly_running_language_server(
10681        &mut self,
10682        adapter: Arc<CachedLspAdapter>,
10683        language_server: Arc<LanguageServer>,
10684        server_id: LanguageServerId,
10685        key: (WorktreeId, LanguageServerName),
10686        workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
10687        cx: &mut Context<Self>,
10688    ) {
10689        let Some(local) = self.as_local_mut() else {
10690            return;
10691        };
10692        // If the language server for this key doesn't match the server id, don't store the
10693        // server. Which will cause it to be dropped, killing the process
10694        if local
10695            .language_server_ids
10696            .get(&key)
10697            .map(|ids| !ids.contains(&server_id))
10698            .unwrap_or(false)
10699        {
10700            return;
10701        }
10702
10703        // Update language_servers collection with Running variant of LanguageServerState
10704        // indicating that the server is up and running and ready
10705        let workspace_folders = workspace_folders.lock().clone();
10706        language_server.set_workspace_folders(workspace_folders);
10707
10708        local.language_servers.insert(
10709            server_id,
10710            LanguageServerState::Running {
10711                workspace_refresh_task: lsp_workspace_diagnostics_refresh(
10712                    language_server.clone(),
10713                    cx,
10714                ),
10715                adapter: adapter.clone(),
10716                server: language_server.clone(),
10717                simulate_disk_based_diagnostics_completion: None,
10718            },
10719        );
10720        local
10721            .languages
10722            .update_lsp_binary_status(adapter.name(), BinaryStatus::None);
10723        if let Some(file_ops_caps) = language_server
10724            .capabilities()
10725            .workspace
10726            .as_ref()
10727            .and_then(|ws| ws.file_operations.as_ref())
10728        {
10729            let did_rename_caps = file_ops_caps.did_rename.as_ref();
10730            let will_rename_caps = file_ops_caps.will_rename.as_ref();
10731            if did_rename_caps.or(will_rename_caps).is_some() {
10732                let watcher = RenamePathsWatchedForServer::default()
10733                    .with_did_rename_patterns(did_rename_caps)
10734                    .with_will_rename_patterns(will_rename_caps);
10735                local
10736                    .language_server_paths_watched_for_rename
10737                    .insert(server_id, watcher);
10738            }
10739        }
10740
10741        self.language_server_statuses.insert(
10742            server_id,
10743            LanguageServerStatus {
10744                name: language_server.name().to_string(),
10745                pending_work: Default::default(),
10746                has_pending_diagnostic_updates: false,
10747                progress_tokens: Default::default(),
10748            },
10749        );
10750
10751        cx.emit(LspStoreEvent::LanguageServerAdded(
10752            server_id,
10753            language_server.name(),
10754            Some(key.0),
10755        ));
10756        cx.emit(LspStoreEvent::RefreshInlayHints);
10757
10758        if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
10759            downstream_client
10760                .send(proto::StartLanguageServer {
10761                    project_id: *project_id,
10762                    server: Some(proto::LanguageServer {
10763                        id: server_id.0 as u64,
10764                        name: language_server.name().to_string(),
10765                        worktree_id: Some(key.0.to_proto()),
10766                    }),
10767                })
10768                .log_err();
10769        }
10770
10771        // Tell the language server about every open buffer in the worktree that matches the language.
10772        // Also check for buffers in worktrees that reused this server
10773        let mut worktrees_using_server = vec![key.0];
10774        if let Some(local) = self.as_local() {
10775            // Find all worktrees that have this server in their language server tree
10776            for (worktree_id, servers) in &local.lsp_tree.read(cx).instances {
10777                if *worktree_id != key.0 {
10778                    for (_, server_map) in &servers.roots {
10779                        if server_map.contains_key(&key.1) {
10780                            worktrees_using_server.push(*worktree_id);
10781                        }
10782                    }
10783                }
10784            }
10785        }
10786
10787        let mut buffer_paths_registered = Vec::new();
10788        self.buffer_store.clone().update(cx, |buffer_store, cx| {
10789            for buffer_handle in buffer_store.buffers() {
10790                let buffer = buffer_handle.read(cx);
10791                let file = match File::from_dyn(buffer.file()) {
10792                    Some(file) => file,
10793                    None => continue,
10794                };
10795                let language = match buffer.language() {
10796                    Some(language) => language,
10797                    None => continue,
10798                };
10799
10800                if !worktrees_using_server.contains(&file.worktree.read(cx).id())
10801                    || !self
10802                        .languages
10803                        .lsp_adapters(&language.name())
10804                        .iter()
10805                        .any(|a| a.name == key.1)
10806                {
10807                    continue;
10808                }
10809                // didOpen
10810                let file = match file.as_local() {
10811                    Some(file) => file,
10812                    None => continue,
10813                };
10814
10815                let local = self.as_local_mut().unwrap();
10816
10817                if local.registered_buffers.contains_key(&buffer.remote_id()) {
10818                    let versions = local
10819                        .buffer_snapshots
10820                        .entry(buffer.remote_id())
10821                        .or_default()
10822                        .entry(server_id)
10823                        .and_modify(|_| {
10824                            assert!(
10825                            false,
10826                            "There should not be an existing snapshot for a newly inserted buffer"
10827                        )
10828                        })
10829                        .or_insert_with(|| {
10830                            vec![LspBufferSnapshot {
10831                                version: 0,
10832                                snapshot: buffer.text_snapshot(),
10833                            }]
10834                        });
10835
10836                    let snapshot = versions.last().unwrap();
10837                    let version = snapshot.version;
10838                    let initial_snapshot = &snapshot.snapshot;
10839                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
10840                    language_server.register_buffer(
10841                        uri,
10842                        adapter.language_id(&language.name()),
10843                        version,
10844                        initial_snapshot.text(),
10845                    );
10846                    buffer_paths_registered.push(file.abs_path(cx));
10847                    local
10848                        .buffers_opened_in_servers
10849                        .entry(buffer.remote_id())
10850                        .or_default()
10851                        .insert(server_id);
10852                }
10853                buffer_handle.update(cx, |buffer, cx| {
10854                    buffer.set_completion_triggers(
10855                        server_id,
10856                        language_server
10857                            .capabilities()
10858                            .completion_provider
10859                            .as_ref()
10860                            .and_then(|provider| {
10861                                provider
10862                                    .trigger_characters
10863                                    .as_ref()
10864                                    .map(|characters| characters.iter().cloned().collect())
10865                            })
10866                            .unwrap_or_default(),
10867                        cx,
10868                    )
10869                });
10870            }
10871        });
10872
10873        for abs_path in buffer_paths_registered {
10874            cx.emit(LspStoreEvent::LanguageServerUpdate {
10875                language_server_id: server_id,
10876                name: Some(adapter.name()),
10877                message: proto::update_language_server::Variant::RegisteredForBuffer(
10878                    proto::RegisteredForBuffer {
10879                        buffer_abs_path: abs_path.to_string_lossy().to_string(),
10880                    },
10881                ),
10882            });
10883        }
10884
10885        cx.notify();
10886    }
10887
10888    pub fn language_servers_running_disk_based_diagnostics(
10889        &self,
10890    ) -> impl Iterator<Item = LanguageServerId> + '_ {
10891        self.language_server_statuses
10892            .iter()
10893            .filter_map(|(id, status)| {
10894                if status.has_pending_diagnostic_updates {
10895                    Some(*id)
10896                } else {
10897                    None
10898                }
10899            })
10900    }
10901
10902    pub(crate) fn cancel_language_server_work_for_buffers(
10903        &mut self,
10904        buffers: impl IntoIterator<Item = Entity<Buffer>>,
10905        cx: &mut Context<Self>,
10906    ) {
10907        if let Some((client, project_id)) = self.upstream_client() {
10908            let request = client.request(proto::CancelLanguageServerWork {
10909                project_id,
10910                work: Some(proto::cancel_language_server_work::Work::Buffers(
10911                    proto::cancel_language_server_work::Buffers {
10912                        buffer_ids: buffers
10913                            .into_iter()
10914                            .map(|b| b.read(cx).remote_id().to_proto())
10915                            .collect(),
10916                    },
10917                )),
10918            });
10919            cx.background_spawn(request).detach_and_log_err(cx);
10920        } else if let Some(local) = self.as_local() {
10921            let servers = buffers
10922                .into_iter()
10923                .flat_map(|buffer| {
10924                    buffer.update(cx, |buffer, cx| {
10925                        local.language_server_ids_for_buffer(buffer, cx).into_iter()
10926                    })
10927                })
10928                .collect::<HashSet<_>>();
10929            for server_id in servers {
10930                self.cancel_language_server_work(server_id, None, cx);
10931            }
10932        }
10933    }
10934
10935    pub(crate) fn cancel_language_server_work(
10936        &mut self,
10937        server_id: LanguageServerId,
10938        token_to_cancel: Option<String>,
10939        cx: &mut Context<Self>,
10940    ) {
10941        if let Some(local) = self.as_local() {
10942            let status = self.language_server_statuses.get(&server_id);
10943            let server = local.language_servers.get(&server_id);
10944            if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
10945            {
10946                for (token, progress) in &status.pending_work {
10947                    if let Some(token_to_cancel) = token_to_cancel.as_ref() {
10948                        if token != token_to_cancel {
10949                            continue;
10950                        }
10951                    }
10952                    if progress.is_cancellable {
10953                        server
10954                            .notify::<lsp::notification::WorkDoneProgressCancel>(
10955                                &WorkDoneProgressCancelParams {
10956                                    token: lsp::NumberOrString::String(token.clone()),
10957                                },
10958                            )
10959                            .ok();
10960                    }
10961                }
10962            }
10963        } else if let Some((client, project_id)) = self.upstream_client() {
10964            let request = client.request(proto::CancelLanguageServerWork {
10965                project_id,
10966                work: Some(
10967                    proto::cancel_language_server_work::Work::LanguageServerWork(
10968                        proto::cancel_language_server_work::LanguageServerWork {
10969                            language_server_id: server_id.to_proto(),
10970                            token: token_to_cancel,
10971                        },
10972                    ),
10973                ),
10974            });
10975            cx.background_spawn(request).detach_and_log_err(cx);
10976        }
10977    }
10978
10979    fn register_supplementary_language_server(
10980        &mut self,
10981        id: LanguageServerId,
10982        name: LanguageServerName,
10983        server: Arc<LanguageServer>,
10984        cx: &mut Context<Self>,
10985    ) {
10986        if let Some(local) = self.as_local_mut() {
10987            local
10988                .supplementary_language_servers
10989                .insert(id, (name.clone(), server));
10990            cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
10991        }
10992    }
10993
10994    fn unregister_supplementary_language_server(
10995        &mut self,
10996        id: LanguageServerId,
10997        cx: &mut Context<Self>,
10998    ) {
10999        if let Some(local) = self.as_local_mut() {
11000            local.supplementary_language_servers.remove(&id);
11001            cx.emit(LspStoreEvent::LanguageServerRemoved(id));
11002        }
11003    }
11004
11005    pub(crate) fn supplementary_language_servers(
11006        &self,
11007    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
11008        self.as_local().into_iter().flat_map(|local| {
11009            local
11010                .supplementary_language_servers
11011                .iter()
11012                .map(|(id, (name, _))| (*id, name.clone()))
11013        })
11014    }
11015
11016    pub fn language_server_adapter_for_id(
11017        &self,
11018        id: LanguageServerId,
11019    ) -> Option<Arc<CachedLspAdapter>> {
11020        self.as_local()
11021            .and_then(|local| local.language_servers.get(&id))
11022            .and_then(|language_server_state| match language_server_state {
11023                LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
11024                _ => None,
11025            })
11026    }
11027
11028    pub(super) fn update_local_worktree_language_servers(
11029        &mut self,
11030        worktree_handle: &Entity<Worktree>,
11031        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
11032        cx: &mut Context<Self>,
11033    ) {
11034        if changes.is_empty() {
11035            return;
11036        }
11037
11038        let Some(local) = self.as_local() else { return };
11039
11040        local.prettier_store.update(cx, |prettier_store, cx| {
11041            prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
11042        });
11043
11044        let worktree_id = worktree_handle.read(cx).id();
11045        let mut language_server_ids = local
11046            .language_server_ids
11047            .iter()
11048            .flat_map(|((server_worktree, _), server_ids)| {
11049                server_ids
11050                    .iter()
11051                    .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
11052            })
11053            .collect::<Vec<_>>();
11054        language_server_ids.sort();
11055        language_server_ids.dedup();
11056
11057        let abs_path = worktree_handle.read(cx).abs_path();
11058        for server_id in &language_server_ids {
11059            if let Some(LanguageServerState::Running { server, .. }) =
11060                local.language_servers.get(server_id)
11061            {
11062                if let Some(watched_paths) = local
11063                    .language_server_watched_paths
11064                    .get(server_id)
11065                    .and_then(|paths| paths.worktree_paths.get(&worktree_id))
11066                {
11067                    let params = lsp::DidChangeWatchedFilesParams {
11068                        changes: changes
11069                            .iter()
11070                            .filter_map(|(path, _, change)| {
11071                                if !watched_paths.is_match(path) {
11072                                    return None;
11073                                }
11074                                let typ = match change {
11075                                    PathChange::Loaded => return None,
11076                                    PathChange::Added => lsp::FileChangeType::CREATED,
11077                                    PathChange::Removed => lsp::FileChangeType::DELETED,
11078                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
11079                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
11080                                };
11081                                Some(lsp::FileEvent {
11082                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
11083                                    typ,
11084                                })
11085                            })
11086                            .collect(),
11087                    };
11088                    if !params.changes.is_empty() {
11089                        server
11090                            .notify::<lsp::notification::DidChangeWatchedFiles>(&params)
11091                            .ok();
11092                    }
11093                }
11094            }
11095        }
11096    }
11097
11098    pub fn wait_for_remote_buffer(
11099        &mut self,
11100        id: BufferId,
11101        cx: &mut Context<Self>,
11102    ) -> Task<Result<Entity<Buffer>>> {
11103        self.buffer_store.update(cx, |buffer_store, cx| {
11104            buffer_store.wait_for_remote_buffer(id, cx)
11105        })
11106    }
11107
11108    fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
11109        proto::Symbol {
11110            language_server_name: symbol.language_server_name.0.to_string(),
11111            source_worktree_id: symbol.source_worktree_id.to_proto(),
11112            language_server_id: symbol.source_language_server_id.to_proto(),
11113            worktree_id: symbol.path.worktree_id.to_proto(),
11114            path: symbol.path.path.as_ref().to_proto(),
11115            name: symbol.name.clone(),
11116            kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
11117            start: Some(proto::PointUtf16 {
11118                row: symbol.range.start.0.row,
11119                column: symbol.range.start.0.column,
11120            }),
11121            end: Some(proto::PointUtf16 {
11122                row: symbol.range.end.0.row,
11123                column: symbol.range.end.0.column,
11124            }),
11125            signature: symbol.signature.to_vec(),
11126        }
11127    }
11128
11129    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
11130        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
11131        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
11132        let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
11133        let path = ProjectPath {
11134            worktree_id,
11135            path: Arc::<Path>::from_proto(serialized_symbol.path),
11136        };
11137
11138        let start = serialized_symbol.start.context("invalid start")?;
11139        let end = serialized_symbol.end.context("invalid end")?;
11140        Ok(CoreSymbol {
11141            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
11142            source_worktree_id,
11143            source_language_server_id: LanguageServerId::from_proto(
11144                serialized_symbol.language_server_id,
11145            ),
11146            path,
11147            name: serialized_symbol.name,
11148            range: Unclipped(PointUtf16::new(start.row, start.column))
11149                ..Unclipped(PointUtf16::new(end.row, end.column)),
11150            kind,
11151            signature: serialized_symbol
11152                .signature
11153                .try_into()
11154                .map_err(|_| anyhow!("invalid signature"))?,
11155        })
11156    }
11157
11158    pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
11159        let mut serialized_completion = proto::Completion {
11160            old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
11161            old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
11162            new_text: completion.new_text.clone(),
11163            ..proto::Completion::default()
11164        };
11165        match &completion.source {
11166            CompletionSource::Lsp {
11167                insert_range,
11168                server_id,
11169                lsp_completion,
11170                lsp_defaults,
11171                resolved,
11172            } => {
11173                let (old_insert_start, old_insert_end) = insert_range
11174                    .as_ref()
11175                    .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
11176                    .unzip();
11177
11178                serialized_completion.old_insert_start = old_insert_start;
11179                serialized_completion.old_insert_end = old_insert_end;
11180                serialized_completion.source = proto::completion::Source::Lsp as i32;
11181                serialized_completion.server_id = server_id.0 as u64;
11182                serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
11183                serialized_completion.lsp_defaults = lsp_defaults
11184                    .as_deref()
11185                    .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
11186                serialized_completion.resolved = *resolved;
11187            }
11188            CompletionSource::BufferWord {
11189                word_range,
11190                resolved,
11191            } => {
11192                serialized_completion.source = proto::completion::Source::BufferWord as i32;
11193                serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
11194                serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
11195                serialized_completion.resolved = *resolved;
11196            }
11197            CompletionSource::Custom => {
11198                serialized_completion.source = proto::completion::Source::Custom as i32;
11199                serialized_completion.resolved = true;
11200            }
11201            CompletionSource::Dap { sort_text } => {
11202                serialized_completion.source = proto::completion::Source::Dap as i32;
11203                serialized_completion.sort_text = Some(sort_text.clone());
11204            }
11205        }
11206
11207        serialized_completion
11208    }
11209
11210    pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
11211        let old_replace_start = completion
11212            .old_replace_start
11213            .and_then(deserialize_anchor)
11214            .context("invalid old start")?;
11215        let old_replace_end = completion
11216            .old_replace_end
11217            .and_then(deserialize_anchor)
11218            .context("invalid old end")?;
11219        let insert_range = {
11220            match completion.old_insert_start.zip(completion.old_insert_end) {
11221                Some((start, end)) => {
11222                    let start = deserialize_anchor(start).context("invalid insert old start")?;
11223                    let end = deserialize_anchor(end).context("invalid insert old end")?;
11224                    Some(start..end)
11225                }
11226                None => None,
11227            }
11228        };
11229        Ok(CoreCompletion {
11230            replace_range: old_replace_start..old_replace_end,
11231            new_text: completion.new_text,
11232            source: match proto::completion::Source::from_i32(completion.source) {
11233                Some(proto::completion::Source::Custom) => CompletionSource::Custom,
11234                Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
11235                    insert_range,
11236                    server_id: LanguageServerId::from_proto(completion.server_id),
11237                    lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
11238                    lsp_defaults: completion
11239                        .lsp_defaults
11240                        .as_deref()
11241                        .map(serde_json::from_slice)
11242                        .transpose()?,
11243                    resolved: completion.resolved,
11244                },
11245                Some(proto::completion::Source::BufferWord) => {
11246                    let word_range = completion
11247                        .buffer_word_start
11248                        .and_then(deserialize_anchor)
11249                        .context("invalid buffer word start")?
11250                        ..completion
11251                            .buffer_word_end
11252                            .and_then(deserialize_anchor)
11253                            .context("invalid buffer word end")?;
11254                    CompletionSource::BufferWord {
11255                        word_range,
11256                        resolved: completion.resolved,
11257                    }
11258                }
11259                Some(proto::completion::Source::Dap) => CompletionSource::Dap {
11260                    sort_text: completion
11261                        .sort_text
11262                        .context("expected sort text to exist")?,
11263                },
11264                _ => anyhow::bail!("Unexpected completion source {}", completion.source),
11265            },
11266        })
11267    }
11268
11269    pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
11270        let (kind, lsp_action) = match &action.lsp_action {
11271            LspAction::Action(code_action) => (
11272                proto::code_action::Kind::Action as i32,
11273                serde_json::to_vec(code_action).unwrap(),
11274            ),
11275            LspAction::Command(command) => (
11276                proto::code_action::Kind::Command as i32,
11277                serde_json::to_vec(command).unwrap(),
11278            ),
11279            LspAction::CodeLens(code_lens) => (
11280                proto::code_action::Kind::CodeLens as i32,
11281                serde_json::to_vec(code_lens).unwrap(),
11282            ),
11283        };
11284
11285        proto::CodeAction {
11286            server_id: action.server_id.0 as u64,
11287            start: Some(serialize_anchor(&action.range.start)),
11288            end: Some(serialize_anchor(&action.range.end)),
11289            lsp_action,
11290            kind,
11291            resolved: action.resolved,
11292        }
11293    }
11294
11295    pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
11296        let start = action
11297            .start
11298            .and_then(deserialize_anchor)
11299            .context("invalid start")?;
11300        let end = action
11301            .end
11302            .and_then(deserialize_anchor)
11303            .context("invalid end")?;
11304        let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
11305            Some(proto::code_action::Kind::Action) => {
11306                LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
11307            }
11308            Some(proto::code_action::Kind::Command) => {
11309                LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
11310            }
11311            Some(proto::code_action::Kind::CodeLens) => {
11312                LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
11313            }
11314            None => anyhow::bail!("Unknown action kind {}", action.kind),
11315        };
11316        Ok(CodeAction {
11317            server_id: LanguageServerId(action.server_id as usize),
11318            range: start..end,
11319            resolved: action.resolved,
11320            lsp_action,
11321        })
11322    }
11323
11324    fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
11325        match &formatting_result {
11326            Ok(_) => self.last_formatting_failure = None,
11327            Err(error) => {
11328                let error_string = format!("{error:#}");
11329                log::error!("Formatting failed: {error_string}");
11330                self.last_formatting_failure
11331                    .replace(error_string.lines().join(" "));
11332            }
11333        }
11334    }
11335
11336    fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
11337        for buffer_colors in self.lsp_document_colors.values_mut() {
11338            buffer_colors.colors.remove(&for_server);
11339            buffer_colors.cache_version += 1;
11340        }
11341        for buffer_lens in self.lsp_code_lens.values_mut() {
11342            buffer_lens.lens.remove(&for_server);
11343        }
11344        if let Some(local) = self.as_local_mut() {
11345            local.buffer_pull_diagnostics_result_ids.remove(&for_server);
11346            for buffer_servers in local.buffers_opened_in_servers.values_mut() {
11347                buffer_servers.remove(&for_server);
11348            }
11349        }
11350    }
11351
11352    pub fn result_id(
11353        &self,
11354        server_id: LanguageServerId,
11355        buffer_id: BufferId,
11356        cx: &App,
11357    ) -> Option<String> {
11358        let abs_path = self
11359            .buffer_store
11360            .read(cx)
11361            .get(buffer_id)
11362            .and_then(|b| File::from_dyn(b.read(cx).file()))
11363            .map(|f| f.abs_path(cx))?;
11364        self.as_local()?
11365            .buffer_pull_diagnostics_result_ids
11366            .get(&server_id)?
11367            .get(&abs_path)?
11368            .clone()
11369    }
11370
11371    pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
11372        let Some(local) = self.as_local() else {
11373            return HashMap::default();
11374        };
11375        local
11376            .buffer_pull_diagnostics_result_ids
11377            .get(&server_id)
11378            .into_iter()
11379            .flatten()
11380            .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
11381            .collect()
11382    }
11383
11384    pub fn pull_workspace_diagnostics(&mut self, server_id: LanguageServerId) {
11385        if let Some(LanguageServerState::Running {
11386            workspace_refresh_task: Some(workspace_refresh_task),
11387            ..
11388        }) = self
11389            .as_local_mut()
11390            .and_then(|local| local.language_servers.get_mut(&server_id))
11391        {
11392            workspace_refresh_task.refresh_tx.try_send(()).ok();
11393        }
11394    }
11395
11396    pub fn pull_workspace_diagnostics_for_buffer(&mut self, buffer_id: BufferId, cx: &mut App) {
11397        let Some(buffer) = self.buffer_store().read(cx).get_existing(buffer_id).ok() else {
11398            return;
11399        };
11400        let Some(local) = self.as_local_mut() else {
11401            return;
11402        };
11403
11404        for server_id in buffer.update(cx, |buffer, cx| {
11405            local.language_server_ids_for_buffer(buffer, cx)
11406        }) {
11407            if let Some(LanguageServerState::Running {
11408                workspace_refresh_task: Some(workspace_refresh_task),
11409                ..
11410            }) = local.language_servers.get_mut(&server_id)
11411            {
11412                workspace_refresh_task.refresh_tx.try_send(()).ok();
11413            }
11414        }
11415    }
11416
11417    fn apply_workspace_diagnostic_report(
11418        &mut self,
11419        server_id: LanguageServerId,
11420        report: lsp::WorkspaceDiagnosticReportResult,
11421        cx: &mut Context<Self>,
11422    ) {
11423        let workspace_diagnostics =
11424            GetDocumentDiagnostics::deserialize_workspace_diagnostics_report(report, server_id);
11425        for workspace_diagnostics in workspace_diagnostics {
11426            let LspPullDiagnostics::Response {
11427                server_id,
11428                uri,
11429                diagnostics,
11430            } = workspace_diagnostics.diagnostics
11431            else {
11432                continue;
11433            };
11434
11435            let adapter = self.language_server_adapter_for_id(server_id);
11436            let disk_based_sources = adapter
11437                .as_ref()
11438                .map(|adapter| adapter.disk_based_diagnostic_sources.as_slice())
11439                .unwrap_or(&[]);
11440
11441            match diagnostics {
11442                PulledDiagnostics::Unchanged { result_id } => {
11443                    self.merge_diagnostics(
11444                        server_id,
11445                        lsp::PublishDiagnosticsParams {
11446                            uri: uri.clone(),
11447                            diagnostics: Vec::new(),
11448                            version: None,
11449                        },
11450                        Some(result_id),
11451                        DiagnosticSourceKind::Pulled,
11452                        disk_based_sources,
11453                        |_, _, _| true,
11454                        cx,
11455                    )
11456                    .log_err();
11457                }
11458                PulledDiagnostics::Changed {
11459                    diagnostics,
11460                    result_id,
11461                } => {
11462                    self.merge_diagnostics(
11463                        server_id,
11464                        lsp::PublishDiagnosticsParams {
11465                            uri: uri.clone(),
11466                            diagnostics,
11467                            version: workspace_diagnostics.version,
11468                        },
11469                        result_id,
11470                        DiagnosticSourceKind::Pulled,
11471                        disk_based_sources,
11472                        |buffer, old_diagnostic, cx| match old_diagnostic.source_kind {
11473                            DiagnosticSourceKind::Pulled => {
11474                                let buffer_url = File::from_dyn(buffer.file())
11475                                    .map(|f| f.abs_path(cx))
11476                                    .and_then(|abs_path| file_path_to_lsp_url(&abs_path).ok());
11477                                buffer_url.is_none_or(|buffer_url| buffer_url != uri)
11478                            }
11479                            DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => true,
11480                        },
11481                        cx,
11482                    )
11483                    .log_err();
11484                }
11485            }
11486        }
11487    }
11488}
11489
11490fn subscribe_to_binary_statuses(
11491    languages: &Arc<LanguageRegistry>,
11492    cx: &mut Context<'_, LspStore>,
11493) -> Task<()> {
11494    let mut server_statuses = languages.language_server_binary_statuses();
11495    cx.spawn(async move |lsp_store, cx| {
11496        while let Some((server_name, binary_status)) = server_statuses.next().await {
11497            if lsp_store
11498                .update(cx, |_, cx| {
11499                    let mut message = None;
11500                    let binary_status = match binary_status {
11501                        BinaryStatus::None => proto::ServerBinaryStatus::None,
11502                        BinaryStatus::CheckingForUpdate => {
11503                            proto::ServerBinaryStatus::CheckingForUpdate
11504                        }
11505                        BinaryStatus::Downloading => proto::ServerBinaryStatus::Downloading,
11506                        BinaryStatus::Starting => proto::ServerBinaryStatus::Starting,
11507                        BinaryStatus::Stopping => proto::ServerBinaryStatus::Stopping,
11508                        BinaryStatus::Stopped => proto::ServerBinaryStatus::Stopped,
11509                        BinaryStatus::Failed { error } => {
11510                            message = Some(error);
11511                            proto::ServerBinaryStatus::Failed
11512                        }
11513                    };
11514                    cx.emit(LspStoreEvent::LanguageServerUpdate {
11515                        // Binary updates are about the binary that might not have any language server id at that point.
11516                        // Reuse `LanguageServerUpdate` for them and provide a fake id that won't be used on the receiver side.
11517                        language_server_id: LanguageServerId(0),
11518                        name: Some(server_name),
11519                        message: proto::update_language_server::Variant::StatusUpdate(
11520                            proto::StatusUpdate {
11521                                message,
11522                                status: Some(proto::status_update::Status::Binary(
11523                                    binary_status as i32,
11524                                )),
11525                            },
11526                        ),
11527                    });
11528                })
11529                .is_err()
11530            {
11531                break;
11532            }
11533        }
11534    })
11535}
11536
11537fn lsp_workspace_diagnostics_refresh(
11538    server: Arc<LanguageServer>,
11539    cx: &mut Context<'_, LspStore>,
11540) -> Option<WorkspaceRefreshTask> {
11541    let identifier = match server.capabilities().diagnostic_provider? {
11542        lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {
11543            if !diagnostic_options.workspace_diagnostics {
11544                return None;
11545            }
11546            diagnostic_options.identifier
11547        }
11548        lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {
11549            let diagnostic_options = registration_options.diagnostic_options;
11550            if !diagnostic_options.workspace_diagnostics {
11551                return None;
11552            }
11553            diagnostic_options.identifier
11554        }
11555    };
11556
11557    let (progress_tx, mut progress_rx) = mpsc::channel(1);
11558    let (mut refresh_tx, mut refresh_rx) = mpsc::channel(1);
11559    refresh_tx.try_send(()).ok();
11560
11561    let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {
11562        let mut attempts = 0;
11563        let max_attempts = 50;
11564        let mut requests = 0;
11565
11566        loop {
11567            let Some(()) = refresh_rx.recv().await else {
11568                return;
11569            };
11570
11571            'request: loop {
11572                requests += 1;
11573                if attempts > max_attempts {
11574                    log::error!(
11575                        "Failed to pull workspace diagnostics {max_attempts} times, aborting"
11576                    );
11577                    return;
11578                }
11579                let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);
11580                cx.background_executor()
11581                    .timer(Duration::from_millis(backoff_millis))
11582                    .await;
11583                attempts += 1;
11584
11585                let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
11586                    lsp_store
11587                        .all_result_ids(server.server_id())
11588                        .into_iter()
11589                        .filter_map(|(abs_path, result_id)| {
11590                            let uri = file_path_to_lsp_url(&abs_path).ok()?;
11591                            Some(lsp::PreviousResultId {
11592                                uri,
11593                                value: result_id,
11594                            })
11595                        })
11596                        .collect()
11597                }) else {
11598                    return;
11599                };
11600
11601                let token = format!("workspace/diagnostic-{}-{}", server.server_id(), requests);
11602
11603                progress_rx.try_recv().ok();
11604                let timer =
11605                    LanguageServer::default_request_timer(cx.background_executor().clone()).fuse();
11606                let progress = pin!(progress_rx.recv().fuse());
11607                let response_result = server
11608                    .request_with_timer::<lsp::WorkspaceDiagnosticRequest, _>(
11609                        lsp::WorkspaceDiagnosticParams {
11610                            previous_result_ids,
11611                            identifier: identifier.clone(),
11612                            work_done_progress_params: Default::default(),
11613                            partial_result_params: lsp::PartialResultParams {
11614                                partial_result_token: Some(lsp::ProgressToken::String(token)),
11615                            },
11616                        },
11617                        select(timer, progress).then(|either| match either {
11618                            Either::Left((message, ..)) => ready(message).left_future(),
11619                            Either::Right(..) => pending::<String>().right_future(),
11620                        }),
11621                    )
11622                    .await;
11623
11624                // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh
11625                // >  If a server closes a workspace diagnostic pull request the client should re-trigger the request.
11626                match response_result {
11627                    ConnectionResult::Timeout => {
11628                        log::error!("Timeout during workspace diagnostics pull");
11629                        continue 'request;
11630                    }
11631                    ConnectionResult::ConnectionReset => {
11632                        log::error!("Server closed a workspace diagnostics pull request");
11633                        continue 'request;
11634                    }
11635                    ConnectionResult::Result(Err(e)) => {
11636                        log::error!("Error during workspace diagnostics pull: {e:#}");
11637                        break 'request;
11638                    }
11639                    ConnectionResult::Result(Ok(pulled_diagnostics)) => {
11640                        attempts = 0;
11641                        if lsp_store
11642                            .update(cx, |lsp_store, cx| {
11643                                lsp_store.apply_workspace_diagnostic_report(
11644                                    server.server_id(),
11645                                    pulled_diagnostics,
11646                                    cx,
11647                                )
11648                            })
11649                            .is_err()
11650                        {
11651                            return;
11652                        }
11653                        break 'request;
11654                    }
11655                }
11656            }
11657        }
11658    });
11659
11660    Some(WorkspaceRefreshTask {
11661        refresh_tx,
11662        progress_tx,
11663        task: workspace_query_language_server,
11664    })
11665}
11666
11667fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
11668    let CompletionSource::BufferWord {
11669        word_range,
11670        resolved,
11671    } = &mut completion.source
11672    else {
11673        return;
11674    };
11675    if *resolved {
11676        return;
11677    }
11678
11679    if completion.new_text
11680        != snapshot
11681            .text_for_range(word_range.clone())
11682            .collect::<String>()
11683    {
11684        return;
11685    }
11686
11687    let mut offset = 0;
11688    for chunk in snapshot.chunks(word_range.clone(), true) {
11689        let end_offset = offset + chunk.text.len();
11690        if let Some(highlight_id) = chunk.syntax_highlight_id {
11691            completion
11692                .label
11693                .runs
11694                .push((offset..end_offset, highlight_id));
11695        }
11696        offset = end_offset;
11697    }
11698    *resolved = true;
11699}
11700
11701impl EventEmitter<LspStoreEvent> for LspStore {}
11702
11703fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11704    hover
11705        .contents
11706        .retain(|hover_block| !hover_block.text.trim().is_empty());
11707    if hover.contents.is_empty() {
11708        None
11709    } else {
11710        Some(hover)
11711    }
11712}
11713
11714async fn populate_labels_for_completions(
11715    new_completions: Vec<CoreCompletion>,
11716    language: Option<Arc<Language>>,
11717    lsp_adapter: Option<Arc<CachedLspAdapter>>,
11718) -> Vec<Completion> {
11719    let lsp_completions = new_completions
11720        .iter()
11721        .filter_map(|new_completion| {
11722            if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
11723                Some(lsp_completion.into_owned())
11724            } else {
11725                None
11726            }
11727        })
11728        .collect::<Vec<_>>();
11729
11730    let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
11731        lsp_adapter
11732            .labels_for_completions(&lsp_completions, language)
11733            .await
11734            .log_err()
11735            .unwrap_or_default()
11736    } else {
11737        Vec::new()
11738    }
11739    .into_iter()
11740    .fuse();
11741
11742    let mut completions = Vec::new();
11743    for completion in new_completions {
11744        match completion.source.lsp_completion(true) {
11745            Some(lsp_completion) => {
11746                let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
11747                    Some(docs.into())
11748                } else {
11749                    None
11750                };
11751
11752                let mut label = labels.next().flatten().unwrap_or_else(|| {
11753                    CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
11754                });
11755                ensure_uniform_list_compatible_label(&mut label);
11756                completions.push(Completion {
11757                    label,
11758                    documentation,
11759                    replace_range: completion.replace_range,
11760                    new_text: completion.new_text,
11761                    insert_text_mode: lsp_completion.insert_text_mode,
11762                    source: completion.source,
11763                    icon_path: None,
11764                    confirm: None,
11765                });
11766            }
11767            None => {
11768                let mut label = CodeLabel::plain(completion.new_text.clone(), None);
11769                ensure_uniform_list_compatible_label(&mut label);
11770                completions.push(Completion {
11771                    label,
11772                    documentation: None,
11773                    replace_range: completion.replace_range,
11774                    new_text: completion.new_text,
11775                    source: completion.source,
11776                    insert_text_mode: None,
11777                    icon_path: None,
11778                    confirm: None,
11779                });
11780            }
11781        }
11782    }
11783    completions
11784}
11785
11786#[derive(Debug)]
11787pub enum LanguageServerToQuery {
11788    /// Query language servers in order of users preference, up until one capable of handling the request is found.
11789    FirstCapable,
11790    /// Query a specific language server.
11791    Other(LanguageServerId),
11792}
11793
11794#[derive(Default)]
11795struct RenamePathsWatchedForServer {
11796    did_rename: Vec<RenameActionPredicate>,
11797    will_rename: Vec<RenameActionPredicate>,
11798}
11799
11800impl RenamePathsWatchedForServer {
11801    fn with_did_rename_patterns(
11802        mut self,
11803        did_rename: Option<&FileOperationRegistrationOptions>,
11804    ) -> Self {
11805        if let Some(did_rename) = did_rename {
11806            self.did_rename = did_rename
11807                .filters
11808                .iter()
11809                .filter_map(|filter| filter.try_into().log_err())
11810                .collect();
11811        }
11812        self
11813    }
11814    fn with_will_rename_patterns(
11815        mut self,
11816        will_rename: Option<&FileOperationRegistrationOptions>,
11817    ) -> Self {
11818        if let Some(will_rename) = will_rename {
11819            self.will_rename = will_rename
11820                .filters
11821                .iter()
11822                .filter_map(|filter| filter.try_into().log_err())
11823                .collect();
11824        }
11825        self
11826    }
11827
11828    fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
11829        self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
11830    }
11831    fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
11832        self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
11833    }
11834}
11835
11836impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
11837    type Error = globset::Error;
11838    fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
11839        Ok(Self {
11840            kind: ops.pattern.matches.clone(),
11841            glob: GlobBuilder::new(&ops.pattern.glob)
11842                .case_insensitive(
11843                    ops.pattern
11844                        .options
11845                        .as_ref()
11846                        .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
11847                )
11848                .build()?
11849                .compile_matcher(),
11850        })
11851    }
11852}
11853struct RenameActionPredicate {
11854    glob: GlobMatcher,
11855    kind: Option<FileOperationPatternKind>,
11856}
11857
11858impl RenameActionPredicate {
11859    // Returns true if language server should be notified
11860    fn eval(&self, path: &str, is_dir: bool) -> bool {
11861        self.kind.as_ref().map_or(true, |kind| {
11862            let expected_kind = if is_dir {
11863                FileOperationPatternKind::Folder
11864            } else {
11865                FileOperationPatternKind::File
11866            };
11867            kind == &expected_kind
11868        }) && self.glob.is_match(path)
11869    }
11870}
11871
11872#[derive(Default)]
11873struct LanguageServerWatchedPaths {
11874    worktree_paths: HashMap<WorktreeId, GlobSet>,
11875    abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
11876}
11877
11878#[derive(Default)]
11879struct LanguageServerWatchedPathsBuilder {
11880    worktree_paths: HashMap<WorktreeId, GlobSet>,
11881    abs_paths: HashMap<Arc<Path>, GlobSet>,
11882}
11883
11884impl LanguageServerWatchedPathsBuilder {
11885    fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
11886        self.worktree_paths.insert(worktree_id, glob_set);
11887    }
11888    fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
11889        self.abs_paths.insert(path, glob_set);
11890    }
11891    fn build(
11892        self,
11893        fs: Arc<dyn Fs>,
11894        language_server_id: LanguageServerId,
11895        cx: &mut Context<LspStore>,
11896    ) -> LanguageServerWatchedPaths {
11897        let project = cx.weak_entity();
11898
11899        const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
11900        let abs_paths = self
11901            .abs_paths
11902            .into_iter()
11903            .map(|(abs_path, globset)| {
11904                let task = cx.spawn({
11905                    let abs_path = abs_path.clone();
11906                    let fs = fs.clone();
11907
11908                    let lsp_store = project.clone();
11909                    async move |_, cx| {
11910                        maybe!(async move {
11911                            let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
11912                            while let Some(update) = push_updates.0.next().await {
11913                                let action = lsp_store
11914                                    .update(cx, |this, _| {
11915                                        let Some(local) = this.as_local() else {
11916                                            return ControlFlow::Break(());
11917                                        };
11918                                        let Some(watcher) = local
11919                                            .language_server_watched_paths
11920                                            .get(&language_server_id)
11921                                        else {
11922                                            return ControlFlow::Break(());
11923                                        };
11924                                        let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
11925                                            "Watched abs path is not registered with a watcher",
11926                                        );
11927                                        let matching_entries = update
11928                                            .into_iter()
11929                                            .filter(|event| globs.is_match(&event.path))
11930                                            .collect::<Vec<_>>();
11931                                        this.lsp_notify_abs_paths_changed(
11932                                            language_server_id,
11933                                            matching_entries,
11934                                        );
11935                                        ControlFlow::Continue(())
11936                                    })
11937                                    .ok()?;
11938
11939                                if action.is_break() {
11940                                    break;
11941                                }
11942                            }
11943                            Some(())
11944                        })
11945                        .await;
11946                    }
11947                });
11948                (abs_path, (globset, task))
11949            })
11950            .collect();
11951        LanguageServerWatchedPaths {
11952            worktree_paths: self.worktree_paths,
11953            abs_paths,
11954        }
11955    }
11956}
11957
11958struct LspBufferSnapshot {
11959    version: i32,
11960    snapshot: TextBufferSnapshot,
11961}
11962
11963/// A prompt requested by LSP server.
11964#[derive(Clone, Debug)]
11965pub struct LanguageServerPromptRequest {
11966    pub level: PromptLevel,
11967    pub message: String,
11968    pub actions: Vec<MessageActionItem>,
11969    pub lsp_name: String,
11970    pub(crate) response_channel: Sender<MessageActionItem>,
11971}
11972
11973impl LanguageServerPromptRequest {
11974    pub async fn respond(self, index: usize) -> Option<()> {
11975        if let Some(response) = self.actions.into_iter().nth(index) {
11976            self.response_channel.send(response).await.ok()
11977        } else {
11978            None
11979        }
11980    }
11981}
11982impl PartialEq for LanguageServerPromptRequest {
11983    fn eq(&self, other: &Self) -> bool {
11984        self.message == other.message && self.actions == other.actions
11985    }
11986}
11987
11988#[derive(Clone, Debug, PartialEq)]
11989pub enum LanguageServerLogType {
11990    Log(MessageType),
11991    Trace(Option<String>),
11992}
11993
11994impl LanguageServerLogType {
11995    pub fn to_proto(&self) -> proto::language_server_log::LogType {
11996        match self {
11997            Self::Log(log_type) => {
11998                let message_type = match *log_type {
11999                    MessageType::ERROR => 1,
12000                    MessageType::WARNING => 2,
12001                    MessageType::INFO => 3,
12002                    MessageType::LOG => 4,
12003                    other => {
12004                        log::warn!("Unknown lsp log message type: {:?}", other);
12005                        4
12006                    }
12007                };
12008                proto::language_server_log::LogType::LogMessageType(message_type)
12009            }
12010            Self::Trace(message) => {
12011                proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
12012                    message: message.clone(),
12013                })
12014            }
12015        }
12016    }
12017
12018    pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
12019        match log_type {
12020            proto::language_server_log::LogType::LogMessageType(message_type) => {
12021                Self::Log(match message_type {
12022                    1 => MessageType::ERROR,
12023                    2 => MessageType::WARNING,
12024                    3 => MessageType::INFO,
12025                    4 => MessageType::LOG,
12026                    _ => MessageType::LOG,
12027                })
12028            }
12029            proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
12030        }
12031    }
12032}
12033
12034pub struct WorkspaceRefreshTask {
12035    refresh_tx: mpsc::Sender<()>,
12036    progress_tx: mpsc::Sender<()>,
12037    #[allow(dead_code)]
12038    task: Task<()>,
12039}
12040
12041pub enum LanguageServerState {
12042    Starting {
12043        startup: Task<Option<Arc<LanguageServer>>>,
12044        /// List of language servers that will be added to the workspace once it's initialization completes.
12045        pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
12046    },
12047
12048    Running {
12049        adapter: Arc<CachedLspAdapter>,
12050        server: Arc<LanguageServer>,
12051        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
12052        workspace_refresh_task: Option<WorkspaceRefreshTask>,
12053    },
12054}
12055
12056impl LanguageServerState {
12057    fn add_workspace_folder(&self, uri: Url) {
12058        match self {
12059            LanguageServerState::Starting {
12060                pending_workspace_folders,
12061                ..
12062            } => {
12063                pending_workspace_folders.lock().insert(uri);
12064            }
12065            LanguageServerState::Running { server, .. } => {
12066                server.add_workspace_folder(uri);
12067            }
12068        }
12069    }
12070    fn _remove_workspace_folder(&self, uri: Url) {
12071        match self {
12072            LanguageServerState::Starting {
12073                pending_workspace_folders,
12074                ..
12075            } => {
12076                pending_workspace_folders.lock().remove(&uri);
12077            }
12078            LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
12079        }
12080    }
12081}
12082
12083impl std::fmt::Debug for LanguageServerState {
12084    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12085        match self {
12086            LanguageServerState::Starting { .. } => {
12087                f.debug_struct("LanguageServerState::Starting").finish()
12088            }
12089            LanguageServerState::Running { .. } => {
12090                f.debug_struct("LanguageServerState::Running").finish()
12091            }
12092        }
12093    }
12094}
12095
12096#[derive(Clone, Debug, Serialize)]
12097pub struct LanguageServerProgress {
12098    pub is_disk_based_diagnostics_progress: bool,
12099    pub is_cancellable: bool,
12100    pub title: Option<String>,
12101    pub message: Option<String>,
12102    pub percentage: Option<usize>,
12103    #[serde(skip_serializing)]
12104    pub last_update_at: Instant,
12105}
12106
12107#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
12108pub struct DiagnosticSummary {
12109    pub error_count: usize,
12110    pub warning_count: usize,
12111}
12112
12113impl DiagnosticSummary {
12114    pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
12115        let mut this = Self {
12116            error_count: 0,
12117            warning_count: 0,
12118        };
12119
12120        for entry in diagnostics {
12121            if entry.diagnostic.is_primary {
12122                match entry.diagnostic.severity {
12123                    DiagnosticSeverity::ERROR => this.error_count += 1,
12124                    DiagnosticSeverity::WARNING => this.warning_count += 1,
12125                    _ => {}
12126                }
12127            }
12128        }
12129
12130        this
12131    }
12132
12133    pub fn is_empty(&self) -> bool {
12134        self.error_count == 0 && self.warning_count == 0
12135    }
12136
12137    pub fn to_proto(
12138        &self,
12139        language_server_id: LanguageServerId,
12140        path: &Path,
12141    ) -> proto::DiagnosticSummary {
12142        proto::DiagnosticSummary {
12143            path: path.to_proto(),
12144            language_server_id: language_server_id.0 as u64,
12145            error_count: self.error_count as u32,
12146            warning_count: self.warning_count as u32,
12147        }
12148    }
12149}
12150
12151#[derive(Clone, Debug)]
12152pub enum CompletionDocumentation {
12153    /// There is no documentation for this completion.
12154    Undocumented,
12155    /// A single line of documentation.
12156    SingleLine(SharedString),
12157    /// Multiple lines of plain text documentation.
12158    MultiLinePlainText(SharedString),
12159    /// Markdown documentation.
12160    MultiLineMarkdown(SharedString),
12161    /// Both single line and multiple lines of plain text documentation.
12162    SingleLineAndMultiLinePlainText {
12163        single_line: SharedString,
12164        plain_text: Option<SharedString>,
12165    },
12166}
12167
12168impl From<lsp::Documentation> for CompletionDocumentation {
12169    fn from(docs: lsp::Documentation) -> Self {
12170        match docs {
12171            lsp::Documentation::String(text) => {
12172                if text.lines().count() <= 1 {
12173                    CompletionDocumentation::SingleLine(text.into())
12174                } else {
12175                    CompletionDocumentation::MultiLinePlainText(text.into())
12176                }
12177            }
12178
12179            lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
12180                lsp::MarkupKind::PlainText => {
12181                    if value.lines().count() <= 1 {
12182                        CompletionDocumentation::SingleLine(value.into())
12183                    } else {
12184                        CompletionDocumentation::MultiLinePlainText(value.into())
12185                    }
12186                }
12187
12188                lsp::MarkupKind::Markdown => {
12189                    CompletionDocumentation::MultiLineMarkdown(value.into())
12190                }
12191            },
12192        }
12193    }
12194}
12195
12196fn glob_literal_prefix(glob: &Path) -> PathBuf {
12197    glob.components()
12198        .take_while(|component| match component {
12199            path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
12200            _ => true,
12201        })
12202        .collect()
12203}
12204
12205pub struct SshLspAdapter {
12206    name: LanguageServerName,
12207    binary: LanguageServerBinary,
12208    initialization_options: Option<String>,
12209    code_action_kinds: Option<Vec<CodeActionKind>>,
12210}
12211
12212impl SshLspAdapter {
12213    pub fn new(
12214        name: LanguageServerName,
12215        binary: LanguageServerBinary,
12216        initialization_options: Option<String>,
12217        code_action_kinds: Option<String>,
12218    ) -> Self {
12219        Self {
12220            name,
12221            binary,
12222            initialization_options,
12223            code_action_kinds: code_action_kinds
12224                .as_ref()
12225                .and_then(|c| serde_json::from_str(c).ok()),
12226        }
12227    }
12228}
12229
12230#[async_trait(?Send)]
12231impl LspAdapter for SshLspAdapter {
12232    fn name(&self) -> LanguageServerName {
12233        self.name.clone()
12234    }
12235
12236    async fn initialization_options(
12237        self: Arc<Self>,
12238        _: &dyn Fs,
12239        _: &Arc<dyn LspAdapterDelegate>,
12240    ) -> Result<Option<serde_json::Value>> {
12241        let Some(options) = &self.initialization_options else {
12242            return Ok(None);
12243        };
12244        let result = serde_json::from_str(options)?;
12245        Ok(result)
12246    }
12247
12248    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
12249        self.code_action_kinds.clone()
12250    }
12251
12252    async fn check_if_user_installed(
12253        &self,
12254        _: &dyn LspAdapterDelegate,
12255        _: Arc<dyn LanguageToolchainStore>,
12256        _: &AsyncApp,
12257    ) -> Option<LanguageServerBinary> {
12258        Some(self.binary.clone())
12259    }
12260
12261    async fn cached_server_binary(
12262        &self,
12263        _: PathBuf,
12264        _: &dyn LspAdapterDelegate,
12265    ) -> Option<LanguageServerBinary> {
12266        None
12267    }
12268
12269    async fn fetch_latest_server_version(
12270        &self,
12271        _: &dyn LspAdapterDelegate,
12272    ) -> Result<Box<dyn 'static + Send + Any>> {
12273        anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
12274    }
12275
12276    async fn fetch_server_binary(
12277        &self,
12278        _: Box<dyn 'static + Send + Any>,
12279        _: PathBuf,
12280        _: &dyn LspAdapterDelegate,
12281    ) -> Result<LanguageServerBinary> {
12282        anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
12283    }
12284}
12285
12286pub fn language_server_settings<'a>(
12287    delegate: &'a dyn LspAdapterDelegate,
12288    language: &LanguageServerName,
12289    cx: &'a App,
12290) -> Option<&'a LspSettings> {
12291    language_server_settings_for(
12292        SettingsLocation {
12293            worktree_id: delegate.worktree_id(),
12294            path: delegate.worktree_root_path(),
12295        },
12296        language,
12297        cx,
12298    )
12299}
12300
12301pub(crate) fn language_server_settings_for<'a>(
12302    location: SettingsLocation<'a>,
12303    language: &LanguageServerName,
12304    cx: &'a App,
12305) -> Option<&'a LspSettings> {
12306    ProjectSettings::get(Some(location), cx).lsp.get(language)
12307}
12308
12309pub struct LocalLspAdapterDelegate {
12310    lsp_store: WeakEntity<LspStore>,
12311    worktree: worktree::Snapshot,
12312    fs: Arc<dyn Fs>,
12313    http_client: Arc<dyn HttpClient>,
12314    language_registry: Arc<LanguageRegistry>,
12315    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
12316}
12317
12318impl LocalLspAdapterDelegate {
12319    pub fn new(
12320        language_registry: Arc<LanguageRegistry>,
12321        environment: &Entity<ProjectEnvironment>,
12322        lsp_store: WeakEntity<LspStore>,
12323        worktree: &Entity<Worktree>,
12324        http_client: Arc<dyn HttpClient>,
12325        fs: Arc<dyn Fs>,
12326        cx: &mut App,
12327    ) -> Arc<Self> {
12328        let load_shell_env_task = environment.update(cx, |env, cx| {
12329            env.get_worktree_environment(worktree.clone(), cx)
12330        });
12331
12332        Arc::new(Self {
12333            lsp_store,
12334            worktree: worktree.read(cx).snapshot(),
12335            fs,
12336            http_client,
12337            language_registry,
12338            load_shell_env_task,
12339        })
12340    }
12341
12342    fn from_local_lsp(
12343        local: &LocalLspStore,
12344        worktree: &Entity<Worktree>,
12345        cx: &mut App,
12346    ) -> Arc<Self> {
12347        Self::new(
12348            local.languages.clone(),
12349            &local.environment,
12350            local.weak.clone(),
12351            worktree,
12352            local.http_client.clone(),
12353            local.fs.clone(),
12354            cx,
12355        )
12356    }
12357}
12358
12359#[async_trait]
12360impl LspAdapterDelegate for LocalLspAdapterDelegate {
12361    fn show_notification(&self, message: &str, cx: &mut App) {
12362        self.lsp_store
12363            .update(cx, |_, cx| {
12364                cx.emit(LspStoreEvent::Notification(message.to_owned()))
12365            })
12366            .ok();
12367    }
12368
12369    fn http_client(&self) -> Arc<dyn HttpClient> {
12370        self.http_client.clone()
12371    }
12372
12373    fn worktree_id(&self) -> WorktreeId {
12374        self.worktree.id()
12375    }
12376
12377    fn worktree_root_path(&self) -> &Path {
12378        self.worktree.abs_path().as_ref()
12379    }
12380
12381    async fn shell_env(&self) -> HashMap<String, String> {
12382        let task = self.load_shell_env_task.clone();
12383        task.await.unwrap_or_default()
12384    }
12385
12386    async fn npm_package_installed_version(
12387        &self,
12388        package_name: &str,
12389    ) -> Result<Option<(PathBuf, String)>> {
12390        let local_package_directory = self.worktree_root_path();
12391        let node_modules_directory = local_package_directory.join("node_modules");
12392
12393        if let Some(version) =
12394            read_package_installed_version(node_modules_directory.clone(), package_name).await?
12395        {
12396            return Ok(Some((node_modules_directory, version)));
12397        }
12398        let Some(npm) = self.which("npm".as_ref()).await else {
12399            log::warn!(
12400                "Failed to find npm executable for {:?}",
12401                local_package_directory
12402            );
12403            return Ok(None);
12404        };
12405
12406        let env = self.shell_env().await;
12407        let output = util::command::new_smol_command(&npm)
12408            .args(["root", "-g"])
12409            .envs(env)
12410            .current_dir(local_package_directory)
12411            .output()
12412            .await?;
12413        let global_node_modules =
12414            PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
12415
12416        if let Some(version) =
12417            read_package_installed_version(global_node_modules.clone(), package_name).await?
12418        {
12419            return Ok(Some((global_node_modules, version)));
12420        }
12421        return Ok(None);
12422    }
12423
12424    #[cfg(not(target_os = "windows"))]
12425    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
12426        let worktree_abs_path = self.worktree.abs_path();
12427        let shell_path = self.shell_env().await.get("PATH").cloned();
12428        which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
12429    }
12430
12431    #[cfg(target_os = "windows")]
12432    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
12433        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
12434        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
12435        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
12436        which::which(command).ok()
12437    }
12438
12439    async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
12440        let working_dir = self.worktree_root_path();
12441        let output = util::command::new_smol_command(&command.path)
12442            .args(command.arguments)
12443            .envs(command.env.clone().unwrap_or_default())
12444            .current_dir(working_dir)
12445            .output()
12446            .await?;
12447
12448        anyhow::ensure!(
12449            output.status.success(),
12450            "{}, stdout: {:?}, stderr: {:?}",
12451            output.status,
12452            String::from_utf8_lossy(&output.stdout),
12453            String::from_utf8_lossy(&output.stderr)
12454        );
12455        Ok(())
12456    }
12457
12458    fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
12459        self.language_registry
12460            .update_lsp_binary_status(server_name, status);
12461    }
12462
12463    fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
12464        self.language_registry
12465            .all_lsp_adapters()
12466            .into_iter()
12467            .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
12468            .collect()
12469    }
12470
12471    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
12472        let dir = self.language_registry.language_server_download_dir(name)?;
12473
12474        if !dir.exists() {
12475            smol::fs::create_dir_all(&dir)
12476                .await
12477                .context("failed to create container directory")
12478                .log_err()?;
12479        }
12480
12481        Some(dir)
12482    }
12483
12484    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
12485        let entry = self
12486            .worktree
12487            .entry_for_path(&path)
12488            .with_context(|| format!("no worktree entry for path {path:?}"))?;
12489        let abs_path = self
12490            .worktree
12491            .absolutize(&entry.path)
12492            .with_context(|| format!("cannot absolutize path {path:?}"))?;
12493
12494        self.fs.load(&abs_path).await
12495    }
12496}
12497
12498async fn populate_labels_for_symbols(
12499    symbols: Vec<CoreSymbol>,
12500    language_registry: &Arc<LanguageRegistry>,
12501    lsp_adapter: Option<Arc<CachedLspAdapter>>,
12502    output: &mut Vec<Symbol>,
12503) {
12504    #[allow(clippy::mutable_key_type)]
12505    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
12506
12507    let mut unknown_paths = BTreeSet::new();
12508    for symbol in symbols {
12509        let language = language_registry
12510            .language_for_file_path(&symbol.path.path)
12511            .await
12512            .ok()
12513            .or_else(|| {
12514                unknown_paths.insert(symbol.path.path.clone());
12515                None
12516            });
12517        symbols_by_language
12518            .entry(language)
12519            .or_default()
12520            .push(symbol);
12521    }
12522
12523    for unknown_path in unknown_paths {
12524        log::info!(
12525            "no language found for symbol path {}",
12526            unknown_path.display()
12527        );
12528    }
12529
12530    let mut label_params = Vec::new();
12531    for (language, mut symbols) in symbols_by_language {
12532        label_params.clear();
12533        label_params.extend(
12534            symbols
12535                .iter_mut()
12536                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
12537        );
12538
12539        let mut labels = Vec::new();
12540        if let Some(language) = language {
12541            let lsp_adapter = lsp_adapter.clone().or_else(|| {
12542                language_registry
12543                    .lsp_adapters(&language.name())
12544                    .first()
12545                    .cloned()
12546            });
12547            if let Some(lsp_adapter) = lsp_adapter {
12548                labels = lsp_adapter
12549                    .labels_for_symbols(&label_params, &language)
12550                    .await
12551                    .log_err()
12552                    .unwrap_or_default();
12553            }
12554        }
12555
12556        for ((symbol, (name, _)), label) in symbols
12557            .into_iter()
12558            .zip(label_params.drain(..))
12559            .zip(labels.into_iter().chain(iter::repeat(None)))
12560        {
12561            output.push(Symbol {
12562                language_server_name: symbol.language_server_name,
12563                source_worktree_id: symbol.source_worktree_id,
12564                source_language_server_id: symbol.source_language_server_id,
12565                path: symbol.path,
12566                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
12567                name,
12568                kind: symbol.kind,
12569                range: symbol.range,
12570                signature: symbol.signature,
12571            });
12572        }
12573    }
12574}
12575
12576fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
12577    match server.capabilities().text_document_sync.as_ref()? {
12578        lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
12579            lsp::TextDocumentSyncKind::NONE => None,
12580            lsp::TextDocumentSyncKind::FULL => Some(true),
12581            lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
12582            _ => None,
12583        },
12584        lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
12585            lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
12586                if *supported {
12587                    Some(true)
12588                } else {
12589                    None
12590                }
12591            }
12592            lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
12593                Some(save_options.include_text.unwrap_or(false))
12594            }
12595        },
12596    }
12597}
12598
12599/// Completion items are displayed in a `UniformList`.
12600/// Usually, those items are single-line strings, but in LSP responses,
12601/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
12602/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
12603/// 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,
12604/// breaking the completions menu presentation.
12605///
12606/// 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.
12607fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
12608    let mut new_text = String::with_capacity(label.text.len());
12609    let mut offset_map = vec![0; label.text.len() + 1];
12610    let mut last_char_was_space = false;
12611    let mut new_idx = 0;
12612    let mut chars = label.text.char_indices().fuse();
12613    let mut newlines_removed = false;
12614
12615    while let Some((idx, c)) = chars.next() {
12616        offset_map[idx] = new_idx;
12617
12618        match c {
12619            '\n' if last_char_was_space => {
12620                newlines_removed = true;
12621            }
12622            '\t' | ' ' if last_char_was_space => {}
12623            '\n' if !last_char_was_space => {
12624                new_text.push(' ');
12625                new_idx += 1;
12626                last_char_was_space = true;
12627                newlines_removed = true;
12628            }
12629            ' ' | '\t' => {
12630                new_text.push(' ');
12631                new_idx += 1;
12632                last_char_was_space = true;
12633            }
12634            _ => {
12635                new_text.push(c);
12636                new_idx += c.len_utf8();
12637                last_char_was_space = false;
12638            }
12639        }
12640    }
12641    offset_map[label.text.len()] = new_idx;
12642
12643    // Only modify the label if newlines were removed.
12644    if !newlines_removed {
12645        return;
12646    }
12647
12648    let last_index = new_idx;
12649    let mut run_ranges_errors = Vec::new();
12650    label.runs.retain_mut(|(range, _)| {
12651        match offset_map.get(range.start) {
12652            Some(&start) => range.start = start,
12653            None => {
12654                run_ranges_errors.push(range.clone());
12655                return false;
12656            }
12657        }
12658
12659        match offset_map.get(range.end) {
12660            Some(&end) => range.end = end,
12661            None => {
12662                run_ranges_errors.push(range.clone());
12663                range.end = last_index;
12664            }
12665        }
12666        true
12667    });
12668    if !run_ranges_errors.is_empty() {
12669        log::error!(
12670            "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
12671            label.text
12672        );
12673    }
12674
12675    let mut wrong_filter_range = None;
12676    if label.filter_range == (0..label.text.len()) {
12677        label.filter_range = 0..new_text.len();
12678    } else {
12679        let mut original_filter_range = Some(label.filter_range.clone());
12680        match offset_map.get(label.filter_range.start) {
12681            Some(&start) => label.filter_range.start = start,
12682            None => {
12683                wrong_filter_range = original_filter_range.take();
12684                label.filter_range.start = last_index;
12685            }
12686        }
12687
12688        match offset_map.get(label.filter_range.end) {
12689            Some(&end) => label.filter_range.end = end,
12690            None => {
12691                wrong_filter_range = original_filter_range.take();
12692                label.filter_range.end = last_index;
12693            }
12694        }
12695    }
12696    if let Some(wrong_filter_range) = wrong_filter_range {
12697        log::error!(
12698            "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
12699            label.text
12700        );
12701    }
12702
12703    label.text = new_text;
12704}
12705
12706#[cfg(test)]
12707mod tests {
12708    use language::HighlightId;
12709
12710    use super::*;
12711
12712    #[test]
12713    fn test_glob_literal_prefix() {
12714        assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
12715        assert_eq!(
12716            glob_literal_prefix(Path::new("node_modules/**/*.js")),
12717            Path::new("node_modules")
12718        );
12719        assert_eq!(
12720            glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12721            Path::new("foo")
12722        );
12723        assert_eq!(
12724            glob_literal_prefix(Path::new("foo/bar/baz.js")),
12725            Path::new("foo/bar/baz.js")
12726        );
12727
12728        #[cfg(target_os = "windows")]
12729        {
12730            assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
12731            assert_eq!(
12732                glob_literal_prefix(Path::new("node_modules\\**/*.js")),
12733                Path::new("node_modules")
12734            );
12735            assert_eq!(
12736                glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
12737                Path::new("foo")
12738            );
12739            assert_eq!(
12740                glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
12741                Path::new("foo/bar/baz.js")
12742            );
12743        }
12744    }
12745
12746    #[test]
12747    fn test_multi_len_chars_normalization() {
12748        let mut label = CodeLabel {
12749            text: "myElˇ (parameter) myElˇ: {\n    foo: string;\n}".to_string(),
12750            runs: vec![(0..6, HighlightId(1))],
12751            filter_range: 0..6,
12752        };
12753        ensure_uniform_list_compatible_label(&mut label);
12754        assert_eq!(
12755            label,
12756            CodeLabel {
12757                text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
12758                runs: vec![(0..6, HighlightId(1))],
12759                filter_range: 0..6,
12760            }
12761        );
12762    }
12763}