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