lsp_store.rs

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