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