lsp_store.rs

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