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        #[expect(
 3794            irrefutable_let_patterns,
 3795            reason = "Make sure to handle new event types in extension properly"
 3796        )]
 3797        let extension::Event::ExtensionsInstalledChanged = evt else {
 3798            return;
 3799        };
 3800        if self.as_local().is_none() {
 3801            return;
 3802        }
 3803        cx.spawn(async move |this, cx| {
 3804            let weak_ref = this.clone();
 3805
 3806            let servers = this
 3807                .update(cx, |this, cx| {
 3808                    let local = this.as_local()?;
 3809
 3810                    let mut servers = Vec::new();
 3811                    for ((worktree_id, _), server_ids) in &local.language_server_ids {
 3812                        for server_id in server_ids {
 3813                            let Some(states) = local.language_servers.get(server_id) else {
 3814                                continue;
 3815                            };
 3816                            let (json_adapter, json_server) = match states {
 3817                                LanguageServerState::Running {
 3818                                    adapter, server, ..
 3819                                } if adapter.adapter.is_primary_zed_json_schema_adapter() => {
 3820                                    (adapter.adapter.clone(), server.clone())
 3821                                }
 3822                                _ => continue,
 3823                            };
 3824
 3825                            let Some(worktree) = this
 3826                                .worktree_store
 3827                                .read(cx)
 3828                                .worktree_for_id(*worktree_id, cx)
 3829                            else {
 3830                                continue;
 3831                            };
 3832                            let json_delegate: Arc<dyn LspAdapterDelegate> =
 3833                                LocalLspAdapterDelegate::new(
 3834                                    local.languages.clone(),
 3835                                    &local.environment,
 3836                                    weak_ref.clone(),
 3837                                    &worktree,
 3838                                    local.http_client.clone(),
 3839                                    local.fs.clone(),
 3840                                    cx,
 3841                                );
 3842
 3843                            servers.push((json_adapter, json_server, json_delegate));
 3844                        }
 3845                    }
 3846                    return Some(servers);
 3847                })
 3848                .ok()
 3849                .flatten();
 3850
 3851            let Some(servers) = servers else {
 3852                return;
 3853            };
 3854
 3855            let Ok(Some((fs, toolchain_store))) = this.read_with(cx, |this, cx| {
 3856                let local = this.as_local()?;
 3857                let toolchain_store = this.toolchain_store(cx);
 3858                return Some((local.fs.clone(), toolchain_store));
 3859            }) else {
 3860                return;
 3861            };
 3862            for (adapter, server, delegate) in servers {
 3863                adapter.clear_zed_json_schema_cache().await;
 3864
 3865                let Some(json_workspace_config) = LocalLspStore::workspace_configuration_for_adapter(
 3866                        adapter,
 3867                        fs.as_ref(),
 3868                        &delegate,
 3869                        toolchain_store.clone(),
 3870                        cx,
 3871                    )
 3872                    .await
 3873                    .context("generate new workspace configuration for JSON language server while trying to refresh JSON Schemas")
 3874                    .ok()
 3875                else {
 3876                    continue;
 3877                };
 3878                server
 3879                    .notify::<lsp::notification::DidChangeConfiguration>(
 3880                        &lsp::DidChangeConfigurationParams {
 3881                            settings: json_workspace_config,
 3882                        },
 3883                    )
 3884                    .ok();
 3885            }
 3886        })
 3887        .detach();
 3888    }
 3889
 3890    pub(crate) fn register_buffer_with_language_servers(
 3891        &mut self,
 3892        buffer: &Entity<Buffer>,
 3893        ignore_refcounts: bool,
 3894        cx: &mut Context<Self>,
 3895    ) -> OpenLspBufferHandle {
 3896        let buffer_id = buffer.read(cx).remote_id();
 3897        let handle = cx.new(|_| buffer.clone());
 3898        if let Some(local) = self.as_local_mut() {
 3899            let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 3900                return handle;
 3901            };
 3902            if !file.is_local() {
 3903                return handle;
 3904            }
 3905
 3906            let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
 3907            if !ignore_refcounts {
 3908                *refcount += 1;
 3909            }
 3910
 3911            if ignore_refcounts || *refcount == 1 {
 3912                local.register_buffer_with_language_servers(buffer, cx);
 3913            }
 3914            if !ignore_refcounts {
 3915                cx.observe_release(&handle, move |this, buffer, cx| {
 3916                    let local = this.as_local_mut().unwrap();
 3917                    let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
 3918                        debug_panic!("bad refcounting");
 3919                        return;
 3920                    };
 3921
 3922                    *refcount -= 1;
 3923                    if *refcount == 0 {
 3924                        local.registered_buffers.remove(&buffer_id);
 3925                        if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
 3926                            local.unregister_old_buffer_from_language_servers(&buffer, &file, cx);
 3927                        }
 3928                    }
 3929                })
 3930                .detach();
 3931            }
 3932        } else if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
 3933            let buffer_id = buffer.read(cx).remote_id().to_proto();
 3934            cx.background_spawn(async move {
 3935                upstream_client
 3936                    .request(proto::RegisterBufferWithLanguageServers {
 3937                        project_id: upstream_project_id,
 3938                        buffer_id,
 3939                    })
 3940                    .await
 3941            })
 3942            .detach();
 3943        } else {
 3944            panic!("oops!");
 3945        }
 3946        handle
 3947    }
 3948
 3949    fn maintain_buffer_languages(
 3950        languages: Arc<LanguageRegistry>,
 3951        cx: &mut Context<Self>,
 3952    ) -> Task<()> {
 3953        let mut subscription = languages.subscribe();
 3954        let mut prev_reload_count = languages.reload_count();
 3955        cx.spawn(async move |this, cx| {
 3956            while let Some(()) = subscription.next().await {
 3957                if let Some(this) = this.upgrade() {
 3958                    // If the language registry has been reloaded, then remove and
 3959                    // re-assign the languages on all open buffers.
 3960                    let reload_count = languages.reload_count();
 3961                    if reload_count > prev_reload_count {
 3962                        prev_reload_count = reload_count;
 3963                        this.update(cx, |this, cx| {
 3964                            this.buffer_store.clone().update(cx, |buffer_store, cx| {
 3965                                for buffer in buffer_store.buffers() {
 3966                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
 3967                                    {
 3968                                        buffer
 3969                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
 3970                                        if let Some(local) = this.as_local_mut() {
 3971                                            local.reset_buffer(&buffer, &f, cx);
 3972
 3973                                            if local
 3974                                                .registered_buffers
 3975                                                .contains_key(&buffer.read(cx).remote_id())
 3976                                            {
 3977                                                if let Some(file_url) =
 3978                                                    lsp::Url::from_file_path(&f.abs_path(cx))
 3979                                                        .log_err()
 3980                                                {
 3981                                                    local.unregister_buffer_from_language_servers(
 3982                                                        &buffer, &file_url, cx,
 3983                                                    );
 3984                                                }
 3985                                            }
 3986                                        }
 3987                                    }
 3988                                }
 3989                            });
 3990                        })
 3991                        .ok();
 3992                    }
 3993
 3994                    this.update(cx, |this, cx| {
 3995                        let mut plain_text_buffers = Vec::new();
 3996                        let mut buffers_with_unknown_injections = Vec::new();
 3997                        for handle in this.buffer_store.read(cx).buffers() {
 3998                            let buffer = handle.read(cx);
 3999                            if buffer.language().is_none()
 4000                                || buffer.language() == Some(&*language::PLAIN_TEXT)
 4001                            {
 4002                                plain_text_buffers.push(handle);
 4003                            } else if buffer.contains_unknown_injections() {
 4004                                buffers_with_unknown_injections.push(handle);
 4005                            }
 4006                        }
 4007                        for buffer in plain_text_buffers {
 4008                            this.detect_language_for_buffer(&buffer, cx);
 4009                            if let Some(local) = this.as_local_mut() {
 4010                                local.initialize_buffer(&buffer, cx);
 4011                                if local
 4012                                    .registered_buffers
 4013                                    .contains_key(&buffer.read(cx).remote_id())
 4014                                {
 4015                                    local.register_buffer_with_language_servers(&buffer, cx);
 4016                                }
 4017                            }
 4018                        }
 4019
 4020                        for buffer in buffers_with_unknown_injections {
 4021                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
 4022                        }
 4023                    })
 4024                    .ok();
 4025                }
 4026            }
 4027        })
 4028    }
 4029
 4030    fn detect_language_for_buffer(
 4031        &mut self,
 4032        buffer_handle: &Entity<Buffer>,
 4033        cx: &mut Context<Self>,
 4034    ) -> Option<language::AvailableLanguage> {
 4035        // If the buffer has a language, set it and start the language server if we haven't already.
 4036        let buffer = buffer_handle.read(cx);
 4037        let file = buffer.file()?;
 4038
 4039        let content = buffer.as_rope();
 4040        let available_language = self.languages.language_for_file(file, Some(content), cx);
 4041        if let Some(available_language) = &available_language {
 4042            if let Some(Ok(Ok(new_language))) = self
 4043                .languages
 4044                .load_language(available_language)
 4045                .now_or_never()
 4046            {
 4047                self.set_language_for_buffer(buffer_handle, new_language, cx);
 4048            }
 4049        } else {
 4050            cx.emit(LspStoreEvent::LanguageDetected {
 4051                buffer: buffer_handle.clone(),
 4052                new_language: None,
 4053            });
 4054        }
 4055
 4056        available_language
 4057    }
 4058
 4059    pub(crate) fn set_language_for_buffer(
 4060        &mut self,
 4061        buffer_entity: &Entity<Buffer>,
 4062        new_language: Arc<Language>,
 4063        cx: &mut Context<Self>,
 4064    ) {
 4065        let buffer = buffer_entity.read(cx);
 4066        let buffer_file = buffer.file().cloned();
 4067        let buffer_id = buffer.remote_id();
 4068        if let Some(local_store) = self.as_local_mut() {
 4069            if local_store.registered_buffers.contains_key(&buffer_id) {
 4070                if let Some(abs_path) =
 4071                    File::from_dyn(buffer_file.as_ref()).map(|file| file.abs_path(cx))
 4072                {
 4073                    if let Some(file_url) = lsp::Url::from_file_path(&abs_path).log_err() {
 4074                        local_store.unregister_buffer_from_language_servers(
 4075                            buffer_entity,
 4076                            &file_url,
 4077                            cx,
 4078                        );
 4079                    }
 4080                }
 4081            }
 4082        }
 4083        buffer_entity.update(cx, |buffer, cx| {
 4084            if buffer.language().map_or(true, |old_language| {
 4085                !Arc::ptr_eq(old_language, &new_language)
 4086            }) {
 4087                buffer.set_language(Some(new_language.clone()), cx);
 4088            }
 4089        });
 4090
 4091        let settings =
 4092            language_settings(Some(new_language.name()), buffer_file.as_ref(), cx).into_owned();
 4093        let buffer_file = File::from_dyn(buffer_file.as_ref());
 4094
 4095        let worktree_id = if let Some(file) = buffer_file {
 4096            let worktree = file.worktree.clone();
 4097
 4098            if let Some(local) = self.as_local_mut() {
 4099                if local.registered_buffers.contains_key(&buffer_id) {
 4100                    local.register_buffer_with_language_servers(buffer_entity, cx);
 4101                }
 4102            }
 4103            Some(worktree.read(cx).id())
 4104        } else {
 4105            None
 4106        };
 4107
 4108        if settings.prettier.allowed {
 4109            if let Some(prettier_plugins) = prettier_store::prettier_plugins_for_language(&settings)
 4110            {
 4111                let prettier_store = self.as_local().map(|s| s.prettier_store.clone());
 4112                if let Some(prettier_store) = prettier_store {
 4113                    prettier_store.update(cx, |prettier_store, cx| {
 4114                        prettier_store.install_default_prettier(
 4115                            worktree_id,
 4116                            prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
 4117                            cx,
 4118                        )
 4119                    })
 4120                }
 4121            }
 4122        }
 4123
 4124        cx.emit(LspStoreEvent::LanguageDetected {
 4125            buffer: buffer_entity.clone(),
 4126            new_language: Some(new_language),
 4127        })
 4128    }
 4129
 4130    pub fn buffer_store(&self) -> Entity<BufferStore> {
 4131        self.buffer_store.clone()
 4132    }
 4133
 4134    pub fn set_active_entry(&mut self, active_entry: Option<ProjectEntryId>) {
 4135        self.active_entry = active_entry;
 4136    }
 4137
 4138    pub(crate) fn send_diagnostic_summaries(&self, worktree: &mut Worktree) {
 4139        if let Some((client, downstream_project_id)) = self.downstream_client.clone() {
 4140            if let Some(summaries) = self.diagnostic_summaries.get(&worktree.id()) {
 4141                for (path, summaries) in summaries {
 4142                    for (&server_id, summary) in summaries {
 4143                        client
 4144                            .send(proto::UpdateDiagnosticSummary {
 4145                                project_id: downstream_project_id,
 4146                                worktree_id: worktree.id().to_proto(),
 4147                                summary: Some(summary.to_proto(server_id, path)),
 4148                            })
 4149                            .log_err();
 4150                    }
 4151                }
 4152            }
 4153        }
 4154    }
 4155
 4156    pub fn request_lsp<R: LspCommand>(
 4157        &mut self,
 4158        buffer_handle: Entity<Buffer>,
 4159        server: LanguageServerToQuery,
 4160        request: R,
 4161        cx: &mut Context<Self>,
 4162    ) -> Task<Result<R::Response>>
 4163    where
 4164        <R::LspRequest as lsp::request::Request>::Result: Send,
 4165        <R::LspRequest as lsp::request::Request>::Params: Send,
 4166    {
 4167        if let Some((upstream_client, upstream_project_id)) = self.upstream_client() {
 4168            return self.send_lsp_proto_request(
 4169                buffer_handle,
 4170                upstream_client,
 4171                upstream_project_id,
 4172                request,
 4173                cx,
 4174            );
 4175        }
 4176
 4177        let Some(language_server) = buffer_handle.update(cx, |buffer, cx| match server {
 4178            LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
 4179                local
 4180                    .language_servers_for_buffer(buffer, cx)
 4181                    .find(|(_, server)| {
 4182                        request.check_capabilities(server.adapter_server_capabilities())
 4183                    })
 4184                    .map(|(_, server)| server.clone())
 4185            }),
 4186            LanguageServerToQuery::Other(id) => self
 4187                .language_server_for_local_buffer(buffer, id, cx)
 4188                .and_then(|(_, server)| {
 4189                    request
 4190                        .check_capabilities(server.adapter_server_capabilities())
 4191                        .then(|| Arc::clone(server))
 4192                }),
 4193        }) else {
 4194            return Task::ready(Ok(Default::default()));
 4195        };
 4196
 4197        let buffer = buffer_handle.read(cx);
 4198        let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 4199
 4200        let Some(file) = file else {
 4201            return Task::ready(Ok(Default::default()));
 4202        };
 4203
 4204        let lsp_params = match request.to_lsp_params_or_response(
 4205            &file.abs_path(cx),
 4206            buffer,
 4207            &language_server,
 4208            cx,
 4209        ) {
 4210            Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
 4211            Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
 4212
 4213            Err(err) => {
 4214                let message = format!(
 4215                    "{} via {} failed: {}",
 4216                    request.display_name(),
 4217                    language_server.name(),
 4218                    err
 4219                );
 4220                log::warn!("{}", message);
 4221                return Task::ready(Err(anyhow!(message)));
 4222            }
 4223        };
 4224
 4225        let status = request.status();
 4226        if !request.check_capabilities(language_server.adapter_server_capabilities()) {
 4227            return Task::ready(Ok(Default::default()));
 4228        }
 4229        return cx.spawn(async move |this, cx| {
 4230            let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 4231
 4232            let id = lsp_request.id();
 4233            let _cleanup = if status.is_some() {
 4234                cx.update(|cx| {
 4235                    this.update(cx, |this, cx| {
 4236                        this.on_lsp_work_start(
 4237                            language_server.server_id(),
 4238                            id.to_string(),
 4239                            LanguageServerProgress {
 4240                                is_disk_based_diagnostics_progress: false,
 4241                                is_cancellable: false,
 4242                                title: None,
 4243                                message: status.clone(),
 4244                                percentage: None,
 4245                                last_update_at: cx.background_executor().now(),
 4246                            },
 4247                            cx,
 4248                        );
 4249                    })
 4250                })
 4251                .log_err();
 4252
 4253                Some(defer(|| {
 4254                    cx.update(|cx| {
 4255                        this.update(cx, |this, cx| {
 4256                            this.on_lsp_work_end(language_server.server_id(), id.to_string(), cx);
 4257                        })
 4258                    })
 4259                    .log_err();
 4260                }))
 4261            } else {
 4262                None
 4263            };
 4264
 4265            let result = lsp_request.await;
 4266
 4267            let response = result.map_err(|err| {
 4268                let message = format!(
 4269                    "{} via {} failed: {}",
 4270                    request.display_name(),
 4271                    language_server.name(),
 4272                    err
 4273                );
 4274                log::warn!("{}", message);
 4275                anyhow!(message)
 4276            })?;
 4277
 4278            let response = request
 4279                .response_from_lsp(
 4280                    response,
 4281                    this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 4282                    buffer_handle,
 4283                    language_server.server_id(),
 4284                    cx.clone(),
 4285                )
 4286                .await;
 4287            response
 4288        });
 4289    }
 4290
 4291    fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
 4292        let mut language_formatters_to_check = Vec::new();
 4293        for buffer in self.buffer_store.read(cx).buffers() {
 4294            let buffer = buffer.read(cx);
 4295            let buffer_file = File::from_dyn(buffer.file());
 4296            let buffer_language = buffer.language();
 4297            let settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
 4298            if buffer_language.is_some() {
 4299                language_formatters_to_check.push((
 4300                    buffer_file.map(|f| f.worktree_id(cx)),
 4301                    settings.into_owned(),
 4302                ));
 4303            }
 4304        }
 4305
 4306        self.refresh_server_tree(cx);
 4307
 4308        if let Some(prettier_store) = self.as_local().map(|s| s.prettier_store.clone()) {
 4309            prettier_store.update(cx, |prettier_store, cx| {
 4310                prettier_store.on_settings_changed(language_formatters_to_check, cx)
 4311            })
 4312        }
 4313
 4314        cx.notify();
 4315    }
 4316
 4317    fn refresh_server_tree(&mut self, cx: &mut Context<Self>) {
 4318        let buffer_store = self.buffer_store.clone();
 4319        if let Some(local) = self.as_local_mut() {
 4320            let mut adapters = BTreeMap::default();
 4321            let to_stop = local.lsp_tree.clone().update(cx, |lsp_tree, cx| {
 4322                let get_adapter = {
 4323                    let languages = local.languages.clone();
 4324                    let environment = local.environment.clone();
 4325                    let weak = local.weak.clone();
 4326                    let worktree_store = local.worktree_store.clone();
 4327                    let http_client = local.http_client.clone();
 4328                    let fs = local.fs.clone();
 4329                    move |worktree_id, cx: &mut App| {
 4330                        let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
 4331                        Some(LocalLspAdapterDelegate::new(
 4332                            languages.clone(),
 4333                            &environment,
 4334                            weak.clone(),
 4335                            &worktree,
 4336                            http_client.clone(),
 4337                            fs.clone(),
 4338                            cx,
 4339                        ))
 4340                    }
 4341                };
 4342
 4343                let mut rebase = lsp_tree.rebase();
 4344                for buffer in buffer_store.read(cx).buffers().collect::<Vec<_>>() {
 4345                    let buffer = buffer.read(cx);
 4346                    if !local.registered_buffers.contains_key(&buffer.remote_id()) {
 4347                        continue;
 4348                    }
 4349                    if let Some((file, language)) = File::from_dyn(buffer.file())
 4350                        .cloned()
 4351                        .zip(buffer.language().map(|l| l.name()))
 4352                    {
 4353                        let worktree_id = file.worktree_id(cx);
 4354                        let Some(worktree) = local
 4355                            .worktree_store
 4356                            .read(cx)
 4357                            .worktree_for_id(worktree_id, cx)
 4358                        else {
 4359                            continue;
 4360                        };
 4361                        let path: Arc<Path> = file
 4362                            .path()
 4363                            .parent()
 4364                            .map(Arc::from)
 4365                            .unwrap_or_else(|| file.path().clone());
 4366                        let worktree_path = ProjectPath { worktree_id, path };
 4367
 4368                        let Some(delegate) = adapters
 4369                            .entry(worktree_id)
 4370                            .or_insert_with(|| get_adapter(worktree_id, cx))
 4371                            .clone()
 4372                        else {
 4373                            continue;
 4374                        };
 4375                        let nodes = rebase.get(
 4376                            worktree_path,
 4377                            AdapterQuery::Language(&language),
 4378                            delegate.clone(),
 4379                            cx,
 4380                        );
 4381                        for node in nodes {
 4382                            node.server_id_or_init(
 4383                                |LaunchDisposition {
 4384                                     server_name,
 4385                                     attach,
 4386                                     path,
 4387                                     settings,
 4388                                 }| match attach {
 4389                                    language::Attach::InstancePerRoot => {
 4390                                        // todo: handle instance per root proper.
 4391                                        if let Some(server_ids) = local
 4392                                            .language_server_ids
 4393                                            .get(&(worktree_id, server_name.clone()))
 4394                                        {
 4395                                            server_ids.iter().cloned().next().unwrap()
 4396                                        } else {
 4397                                            local.start_language_server(
 4398                                                &worktree,
 4399                                                delegate.clone(),
 4400                                                local
 4401                                                    .languages
 4402                                                    .lsp_adapters(&language)
 4403                                                    .into_iter()
 4404                                                    .find(|adapter| &adapter.name() == server_name)
 4405                                                    .expect("To find LSP adapter"),
 4406                                                settings,
 4407                                                cx,
 4408                                            )
 4409                                        }
 4410                                    }
 4411                                    language::Attach::Shared => {
 4412                                        let uri = Url::from_file_path(
 4413                                            worktree.read(cx).abs_path().join(&path.path),
 4414                                        );
 4415                                        let key = (worktree_id, server_name.clone());
 4416                                        local.language_server_ids.remove(&key);
 4417
 4418                                        let server_id = local.start_language_server(
 4419                                            &worktree,
 4420                                            delegate.clone(),
 4421                                            local
 4422                                                .languages
 4423                                                .lsp_adapters(&language)
 4424                                                .into_iter()
 4425                                                .find(|adapter| &adapter.name() == server_name)
 4426                                                .expect("To find LSP adapter"),
 4427                                            settings,
 4428                                            cx,
 4429                                        );
 4430                                        if let Some(state) = local.language_servers.get(&server_id)
 4431                                        {
 4432                                            if let Ok(uri) = uri {
 4433                                                state.add_workspace_folder(uri);
 4434                                            };
 4435                                        }
 4436                                        server_id
 4437                                    }
 4438                                },
 4439                            );
 4440                        }
 4441                    }
 4442                }
 4443                rebase.finish()
 4444            });
 4445            for (id, name) in to_stop {
 4446                self.stop_local_language_server(id, name, cx).detach();
 4447            }
 4448        }
 4449    }
 4450
 4451    pub fn apply_code_action(
 4452        &self,
 4453        buffer_handle: Entity<Buffer>,
 4454        mut action: CodeAction,
 4455        push_to_history: bool,
 4456        cx: &mut Context<Self>,
 4457    ) -> Task<Result<ProjectTransaction>> {
 4458        if let Some((upstream_client, project_id)) = self.upstream_client() {
 4459            let request = proto::ApplyCodeAction {
 4460                project_id,
 4461                buffer_id: buffer_handle.read(cx).remote_id().into(),
 4462                action: Some(Self::serialize_code_action(&action)),
 4463            };
 4464            let buffer_store = self.buffer_store();
 4465            cx.spawn(async move |_, cx| {
 4466                let response = upstream_client
 4467                    .request(request)
 4468                    .await?
 4469                    .transaction
 4470                    .ok_or_else(|| anyhow!("missing transaction"))?;
 4471
 4472                buffer_store
 4473                    .update(cx, |buffer_store, cx| {
 4474                        buffer_store.deserialize_project_transaction(response, push_to_history, cx)
 4475                    })?
 4476                    .await
 4477            })
 4478        } else if self.mode.is_local() {
 4479            let Some((lsp_adapter, lang_server)) = buffer_handle.update(cx, |buffer, cx| {
 4480                self.language_server_for_local_buffer(buffer, action.server_id, cx)
 4481                    .map(|(adapter, server)| (adapter.clone(), server.clone()))
 4482            }) else {
 4483                return Task::ready(Ok(ProjectTransaction::default()));
 4484            };
 4485            cx.spawn(async move |this,  cx| {
 4486                LocalLspStore::try_resolve_code_action(&lang_server, &mut action)
 4487                    .await
 4488                    .context("resolving a code action")?;
 4489                if let Some(edit) = action.lsp_action.edit() {
 4490                    if edit.changes.is_some() || edit.document_changes.is_some() {
 4491                        return LocalLspStore::deserialize_workspace_edit(
 4492                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 4493                            edit.clone(),
 4494                            push_to_history,
 4495                            lsp_adapter.clone(),
 4496                            lang_server.clone(),
 4497                            cx,
 4498                        )
 4499                        .await;
 4500                    }
 4501                }
 4502
 4503                if let Some(command) = action.lsp_action.command() {
 4504                    let server_capabilities = lang_server.capabilities();
 4505                    let available_commands = server_capabilities
 4506                        .execute_command_provider
 4507                        .as_ref()
 4508                        .map(|options| options.commands.as_slice())
 4509                        .unwrap_or_default();
 4510                    if available_commands.contains(&command.command) {
 4511                        this.update(cx, |this, _| {
 4512                            this.as_local_mut()
 4513                                .unwrap()
 4514                                .last_workspace_edits_by_language_server
 4515                                .remove(&lang_server.server_id());
 4516                        })?;
 4517
 4518                        let result = lang_server
 4519                            .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 4520                                command: command.command.clone(),
 4521                                arguments: command.arguments.clone().unwrap_or_default(),
 4522                                ..Default::default()
 4523                            })
 4524                            .await;
 4525
 4526                        result?;
 4527
 4528                        return this.update(cx, |this, _| {
 4529                            this.as_local_mut()
 4530                                .unwrap()
 4531                                .last_workspace_edits_by_language_server
 4532                                .remove(&lang_server.server_id())
 4533                                .unwrap_or_default()
 4534                        });
 4535                    } else {
 4536                        log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command);
 4537                    }
 4538                }
 4539
 4540                Ok(ProjectTransaction::default())
 4541            })
 4542        } else {
 4543            Task::ready(Err(anyhow!("no upstream client and not local")))
 4544        }
 4545    }
 4546
 4547    pub fn apply_code_action_kind(
 4548        &mut self,
 4549        buffers: HashSet<Entity<Buffer>>,
 4550        kind: CodeActionKind,
 4551        push_to_history: bool,
 4552        cx: &mut Context<Self>,
 4553    ) -> Task<anyhow::Result<ProjectTransaction>> {
 4554        if let Some(_) = self.as_local() {
 4555            cx.spawn(async move |lsp_store, cx| {
 4556                let buffers = buffers.into_iter().collect::<Vec<_>>();
 4557                let result = LocalLspStore::execute_code_action_kind_locally(
 4558                    lsp_store.clone(),
 4559                    buffers,
 4560                    kind,
 4561                    push_to_history,
 4562                    cx,
 4563                )
 4564                .await;
 4565                lsp_store.update(cx, |lsp_store, _| {
 4566                    lsp_store.update_last_formatting_failure(&result);
 4567                })?;
 4568                result
 4569            })
 4570        } else if let Some((client, project_id)) = self.upstream_client() {
 4571            let buffer_store = self.buffer_store();
 4572            cx.spawn(async move |lsp_store, cx| {
 4573                let result = client
 4574                    .request(proto::ApplyCodeActionKind {
 4575                        project_id,
 4576                        kind: kind.as_str().to_owned(),
 4577                        buffer_ids: buffers
 4578                            .iter()
 4579                            .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
 4580                            .collect::<Result<_>>()?,
 4581                    })
 4582                    .await
 4583                    .and_then(|result| result.transaction.context("missing transaction"));
 4584                lsp_store.update(cx, |lsp_store, _| {
 4585                    lsp_store.update_last_formatting_failure(&result);
 4586                })?;
 4587
 4588                let transaction_response = result?;
 4589                buffer_store
 4590                    .update(cx, |buffer_store, cx| {
 4591                        buffer_store.deserialize_project_transaction(
 4592                            transaction_response,
 4593                            push_to_history,
 4594                            cx,
 4595                        )
 4596                    })?
 4597                    .await
 4598            })
 4599        } else {
 4600            Task::ready(Ok(ProjectTransaction::default()))
 4601        }
 4602    }
 4603
 4604    pub fn resolve_inlay_hint(
 4605        &self,
 4606        hint: InlayHint,
 4607        buffer_handle: Entity<Buffer>,
 4608        server_id: LanguageServerId,
 4609        cx: &mut Context<Self>,
 4610    ) -> Task<anyhow::Result<InlayHint>> {
 4611        if let Some((upstream_client, project_id)) = self.upstream_client() {
 4612            let request = proto::ResolveInlayHint {
 4613                project_id,
 4614                buffer_id: buffer_handle.read(cx).remote_id().into(),
 4615                language_server_id: server_id.0 as u64,
 4616                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 4617            };
 4618            cx.spawn(async move |_, _| {
 4619                let response = upstream_client
 4620                    .request(request)
 4621                    .await
 4622                    .context("inlay hints proto request")?;
 4623                match response.hint {
 4624                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 4625                        .context("inlay hints proto resolve response conversion"),
 4626                    None => Ok(hint),
 4627                }
 4628            })
 4629        } else {
 4630            let Some(lang_server) = buffer_handle.update(cx, |buffer, cx| {
 4631                self.language_server_for_local_buffer(buffer, server_id, cx)
 4632                    .map(|(_, server)| server.clone())
 4633            }) else {
 4634                return Task::ready(Ok(hint));
 4635            };
 4636            if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
 4637                return Task::ready(Ok(hint));
 4638            }
 4639            let buffer_snapshot = buffer_handle.read(cx).snapshot();
 4640            cx.spawn(async move |_, cx| {
 4641                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 4642                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 4643                );
 4644                let resolved_hint = resolve_task
 4645                    .await
 4646                    .context("inlay hint resolve LSP request")?;
 4647                let resolved_hint = InlayHints::lsp_to_project_hint(
 4648                    resolved_hint,
 4649                    &buffer_handle,
 4650                    server_id,
 4651                    ResolveState::Resolved,
 4652                    false,
 4653                    cx,
 4654                )
 4655                .await?;
 4656                Ok(resolved_hint)
 4657            })
 4658        }
 4659    }
 4660
 4661    pub(crate) fn linked_edit(
 4662        &mut self,
 4663        buffer: &Entity<Buffer>,
 4664        position: Anchor,
 4665        cx: &mut Context<Self>,
 4666    ) -> Task<Result<Vec<Range<Anchor>>>> {
 4667        let snapshot = buffer.read(cx).snapshot();
 4668        let scope = snapshot.language_scope_at(position);
 4669        let Some(server_id) = self
 4670            .as_local()
 4671            .and_then(|local| {
 4672                buffer.update(cx, |buffer, cx| {
 4673                    local
 4674                        .language_servers_for_buffer(buffer, cx)
 4675                        .filter(|(_, server)| {
 4676                            server
 4677                                .capabilities()
 4678                                .linked_editing_range_provider
 4679                                .is_some()
 4680                        })
 4681                        .filter(|(adapter, _)| {
 4682                            scope
 4683                                .as_ref()
 4684                                .map(|scope| scope.language_allowed(&adapter.name))
 4685                                .unwrap_or(true)
 4686                        })
 4687                        .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
 4688                        .next()
 4689                })
 4690            })
 4691            .or_else(|| {
 4692                self.upstream_client()
 4693                    .is_some()
 4694                    .then_some(LanguageServerToQuery::FirstCapable)
 4695            })
 4696            .filter(|_| {
 4697                maybe!({
 4698                    let language = buffer.read(cx).language_at(position)?;
 4699                    Some(
 4700                        language_settings(Some(language.name()), buffer.read(cx).file(), cx)
 4701                            .linked_edits,
 4702                    )
 4703                }) == Some(true)
 4704            })
 4705        else {
 4706            return Task::ready(Ok(vec![]));
 4707        };
 4708
 4709        self.request_lsp(
 4710            buffer.clone(),
 4711            server_id,
 4712            LinkedEditingRange { position },
 4713            cx,
 4714        )
 4715    }
 4716
 4717    fn apply_on_type_formatting(
 4718        &mut self,
 4719        buffer: Entity<Buffer>,
 4720        position: Anchor,
 4721        trigger: String,
 4722        cx: &mut Context<Self>,
 4723    ) -> Task<Result<Option<Transaction>>> {
 4724        if let Some((client, project_id)) = self.upstream_client() {
 4725            let request = proto::OnTypeFormatting {
 4726                project_id,
 4727                buffer_id: buffer.read(cx).remote_id().into(),
 4728                position: Some(serialize_anchor(&position)),
 4729                trigger,
 4730                version: serialize_version(&buffer.read(cx).version()),
 4731            };
 4732            cx.spawn(async move |_, _| {
 4733                client
 4734                    .request(request)
 4735                    .await?
 4736                    .transaction
 4737                    .map(language::proto::deserialize_transaction)
 4738                    .transpose()
 4739            })
 4740        } else if let Some(local) = self.as_local_mut() {
 4741            let buffer_id = buffer.read(cx).remote_id();
 4742            local.buffers_being_formatted.insert(buffer_id);
 4743            cx.spawn(async move |this, cx| {
 4744                let _cleanup = defer({
 4745                    let this = this.clone();
 4746                    let mut cx = cx.clone();
 4747                    move || {
 4748                        this.update(&mut cx, |this, _| {
 4749                            if let Some(local) = this.as_local_mut() {
 4750                                local.buffers_being_formatted.remove(&buffer_id);
 4751                            }
 4752                        })
 4753                        .ok();
 4754                    }
 4755                });
 4756
 4757                buffer
 4758                    .update(cx, |buffer, _| {
 4759                        buffer.wait_for_edits(Some(position.timestamp))
 4760                    })?
 4761                    .await?;
 4762                this.update(cx, |this, cx| {
 4763                    let position = position.to_point_utf16(buffer.read(cx));
 4764                    this.on_type_format(buffer, position, trigger, false, cx)
 4765                })?
 4766                .await
 4767            })
 4768        } else {
 4769            Task::ready(Err(anyhow!("No upstream client or local language server")))
 4770        }
 4771    }
 4772
 4773    pub fn on_type_format<T: ToPointUtf16>(
 4774        &mut self,
 4775        buffer: Entity<Buffer>,
 4776        position: T,
 4777        trigger: String,
 4778        push_to_history: bool,
 4779        cx: &mut Context<Self>,
 4780    ) -> Task<Result<Option<Transaction>>> {
 4781        let position = position.to_point_utf16(buffer.read(cx));
 4782        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 4783    }
 4784
 4785    fn on_type_format_impl(
 4786        &mut self,
 4787        buffer: Entity<Buffer>,
 4788        position: PointUtf16,
 4789        trigger: String,
 4790        push_to_history: bool,
 4791        cx: &mut Context<Self>,
 4792    ) -> Task<Result<Option<Transaction>>> {
 4793        let options = buffer.update(cx, |buffer, cx| {
 4794            lsp_command::lsp_formatting_options(
 4795                language_settings(
 4796                    buffer.language_at(position).map(|l| l.name()),
 4797                    buffer.file(),
 4798                    cx,
 4799                )
 4800                .as_ref(),
 4801            )
 4802        });
 4803        self.request_lsp(
 4804            buffer.clone(),
 4805            LanguageServerToQuery::FirstCapable,
 4806            OnTypeFormatting {
 4807                position,
 4808                trigger,
 4809                options,
 4810                push_to_history,
 4811            },
 4812            cx,
 4813        )
 4814    }
 4815
 4816    pub fn code_actions(
 4817        &mut self,
 4818        buffer_handle: &Entity<Buffer>,
 4819        range: Range<Anchor>,
 4820        kinds: Option<Vec<CodeActionKind>>,
 4821        cx: &mut Context<Self>,
 4822    ) -> Task<Result<Vec<CodeAction>>> {
 4823        if let Some((upstream_client, project_id)) = self.upstream_client() {
 4824            let request_task = upstream_client.request(proto::MultiLspQuery {
 4825                buffer_id: buffer_handle.read(cx).remote_id().into(),
 4826                version: serialize_version(&buffer_handle.read(cx).version()),
 4827                project_id,
 4828                strategy: Some(proto::multi_lsp_query::Strategy::All(
 4829                    proto::AllLanguageServers {},
 4830                )),
 4831                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 4832                    GetCodeActions {
 4833                        range: range.clone(),
 4834                        kinds: kinds.clone(),
 4835                    }
 4836                    .to_proto(project_id, buffer_handle.read(cx)),
 4837                )),
 4838            });
 4839            let buffer = buffer_handle.clone();
 4840            cx.spawn(async move |weak_project, cx| {
 4841                let Some(project) = weak_project.upgrade() else {
 4842                    return Ok(Vec::new());
 4843                };
 4844                let responses = request_task.await?.responses;
 4845                let actions = join_all(
 4846                    responses
 4847                        .into_iter()
 4848                        .filter_map(|lsp_response| match lsp_response.response? {
 4849                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 4850                                Some(response)
 4851                            }
 4852                            unexpected => {
 4853                                debug_panic!("Unexpected response: {unexpected:?}");
 4854                                None
 4855                            }
 4856                        })
 4857                        .map(|code_actions_response| {
 4858                            GetCodeActions {
 4859                                range: range.clone(),
 4860                                kinds: kinds.clone(),
 4861                            }
 4862                            .response_from_proto(
 4863                                code_actions_response,
 4864                                project.clone(),
 4865                                buffer.clone(),
 4866                                cx.clone(),
 4867                            )
 4868                        }),
 4869                )
 4870                .await;
 4871
 4872                Ok(actions
 4873                    .into_iter()
 4874                    .collect::<Result<Vec<Vec<_>>>>()?
 4875                    .into_iter()
 4876                    .flatten()
 4877                    .collect())
 4878            })
 4879        } else {
 4880            let all_actions_task = self.request_multiple_lsp_locally(
 4881                buffer_handle,
 4882                Some(range.start),
 4883                GetCodeActions {
 4884                    range: range.clone(),
 4885                    kinds: kinds.clone(),
 4886                },
 4887                cx,
 4888            );
 4889            cx.spawn(async move |_, _| Ok(all_actions_task.await.into_iter().flatten().collect()))
 4890        }
 4891    }
 4892
 4893    pub fn code_lens(
 4894        &mut self,
 4895        buffer_handle: &Entity<Buffer>,
 4896        cx: &mut Context<Self>,
 4897    ) -> Task<Result<Vec<CodeAction>>> {
 4898        if let Some((upstream_client, project_id)) = self.upstream_client() {
 4899            let request_task = upstream_client.request(proto::MultiLspQuery {
 4900                buffer_id: buffer_handle.read(cx).remote_id().into(),
 4901                version: serialize_version(&buffer_handle.read(cx).version()),
 4902                project_id,
 4903                strategy: Some(proto::multi_lsp_query::Strategy::All(
 4904                    proto::AllLanguageServers {},
 4905                )),
 4906                request: Some(proto::multi_lsp_query::Request::GetCodeLens(
 4907                    GetCodeLens.to_proto(project_id, buffer_handle.read(cx)),
 4908                )),
 4909            });
 4910            let buffer = buffer_handle.clone();
 4911            cx.spawn(async move |weak_project, cx| {
 4912                let Some(project) = weak_project.upgrade() else {
 4913                    return Ok(Vec::new());
 4914                };
 4915                let responses = request_task.await?.responses;
 4916                let code_lens = join_all(
 4917                    responses
 4918                        .into_iter()
 4919                        .filter_map(|lsp_response| match lsp_response.response? {
 4920                            proto::lsp_response::Response::GetCodeLensResponse(response) => {
 4921                                Some(response)
 4922                            }
 4923                            unexpected => {
 4924                                debug_panic!("Unexpected response: {unexpected:?}");
 4925                                None
 4926                            }
 4927                        })
 4928                        .map(|code_lens_response| {
 4929                            GetCodeLens.response_from_proto(
 4930                                code_lens_response,
 4931                                project.clone(),
 4932                                buffer.clone(),
 4933                                cx.clone(),
 4934                            )
 4935                        }),
 4936                )
 4937                .await;
 4938
 4939                Ok(code_lens
 4940                    .into_iter()
 4941                    .collect::<Result<Vec<Vec<_>>>>()?
 4942                    .into_iter()
 4943                    .flatten()
 4944                    .collect())
 4945            })
 4946        } else {
 4947            let code_lens_task =
 4948                self.request_multiple_lsp_locally(buffer_handle, None::<usize>, GetCodeLens, cx);
 4949            cx.spawn(async move |_, _| Ok(code_lens_task.await.into_iter().flatten().collect()))
 4950        }
 4951    }
 4952
 4953    #[inline(never)]
 4954    pub fn completions(
 4955        &self,
 4956        buffer: &Entity<Buffer>,
 4957        position: PointUtf16,
 4958        context: CompletionContext,
 4959        cx: &mut Context<Self>,
 4960    ) -> Task<Result<Option<Vec<Completion>>>> {
 4961        let language_registry = self.languages.clone();
 4962
 4963        if let Some((upstream_client, project_id)) = self.upstream_client() {
 4964            let task = self.send_lsp_proto_request(
 4965                buffer.clone(),
 4966                upstream_client,
 4967                project_id,
 4968                GetCompletions { position, context },
 4969                cx,
 4970            );
 4971            let language = buffer.read(cx).language().cloned();
 4972
 4973            // In the future, we should provide project guests with the names of LSP adapters,
 4974            // so that they can use the correct LSP adapter when computing labels. For now,
 4975            // guests just use the first LSP adapter associated with the buffer's language.
 4976            let lsp_adapter = language.as_ref().and_then(|language| {
 4977                language_registry
 4978                    .lsp_adapters(&language.name())
 4979                    .first()
 4980                    .cloned()
 4981            });
 4982
 4983            cx.foreground_executor().spawn(async move {
 4984                let completions = task.await?;
 4985                let mut result = Vec::new();
 4986                populate_labels_for_completions(completions, language, lsp_adapter, &mut result)
 4987                    .await;
 4988                Ok(Some(result))
 4989            })
 4990        } else if let Some(local) = self.as_local() {
 4991            let snapshot = buffer.read(cx).snapshot();
 4992            let offset = position.to_offset(&snapshot);
 4993            let scope = snapshot.language_scope_at(offset);
 4994            let language = snapshot.language().cloned();
 4995            let completion_settings = language_settings(
 4996                language.as_ref().map(|language| language.name()),
 4997                buffer.read(cx).file(),
 4998                cx,
 4999            )
 5000            .completions;
 5001            if !completion_settings.lsp {
 5002                return Task::ready(Ok(None));
 5003            }
 5004
 5005            let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
 5006                local
 5007                    .language_servers_for_buffer(buffer, cx)
 5008                    .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5009                    .filter(|(adapter, _)| {
 5010                        scope
 5011                            .as_ref()
 5012                            .map(|scope| scope.language_allowed(&adapter.name))
 5013                            .unwrap_or(true)
 5014                    })
 5015                    .map(|(_, server)| server.server_id())
 5016                    .collect()
 5017            });
 5018
 5019            let buffer = buffer.clone();
 5020            let lsp_timeout = completion_settings.lsp_fetch_timeout_ms;
 5021            let lsp_timeout = if lsp_timeout > 0 {
 5022                Some(Duration::from_millis(lsp_timeout))
 5023            } else {
 5024                None
 5025            };
 5026            cx.spawn(async move |this,  cx| {
 5027                let mut tasks = Vec::with_capacity(server_ids.len());
 5028                this.update(cx, |lsp_store, cx| {
 5029                    for server_id in server_ids {
 5030                        let lsp_adapter = lsp_store.language_server_adapter_for_id(server_id);
 5031                        let lsp_timeout = lsp_timeout
 5032                            .map(|lsp_timeout| cx.background_executor().timer(lsp_timeout));
 5033                        let mut timeout = cx.background_spawn(async move {
 5034                            match lsp_timeout {
 5035                                Some(lsp_timeout) => {
 5036                                    lsp_timeout.await;
 5037                                    true
 5038                                },
 5039                                None => false,
 5040                            }
 5041                        }).fuse();
 5042                        let mut lsp_request = lsp_store.request_lsp(
 5043                            buffer.clone(),
 5044                            LanguageServerToQuery::Other(server_id),
 5045                            GetCompletions {
 5046                                position,
 5047                                context: context.clone(),
 5048                            },
 5049                            cx,
 5050                        ).fuse();
 5051                        let new_task = cx.background_spawn(async move {
 5052                            select_biased! {
 5053                                response = lsp_request => anyhow::Ok(Some(response?)),
 5054                                timeout_happened = timeout => {
 5055                                    if timeout_happened {
 5056                                        log::warn!("Fetching completions from server {server_id} timed out, timeout ms: {}", completion_settings.lsp_fetch_timeout_ms);
 5057                                        Ok(None)
 5058                                    } else {
 5059                                        let completions = lsp_request.await?;
 5060                                        Ok(Some(completions))
 5061                                    }
 5062                                },
 5063                            }
 5064                        });
 5065                        tasks.push((lsp_adapter, new_task));
 5066                    }
 5067                })?;
 5068
 5069                let mut has_completions_returned = false;
 5070                let mut completions = Vec::new();
 5071                for (lsp_adapter, task) in tasks {
 5072                    if let Ok(Some(new_completions)) = task.await {
 5073                        has_completions_returned = true;
 5074                        populate_labels_for_completions(
 5075                            new_completions,
 5076                            language.clone(),
 5077                            lsp_adapter,
 5078                            &mut completions,
 5079                        )
 5080                        .await;
 5081                    }
 5082                }
 5083                if has_completions_returned {
 5084                    Ok(Some(completions))
 5085                } else {
 5086                    Ok(None)
 5087                }
 5088            })
 5089        } else {
 5090            Task::ready(Err(anyhow!("No upstream client or local language server")))
 5091        }
 5092    }
 5093
 5094    pub fn resolve_completions(
 5095        &self,
 5096        buffer: Entity<Buffer>,
 5097        completion_indices: Vec<usize>,
 5098        completions: Rc<RefCell<Box<[Completion]>>>,
 5099        cx: &mut Context<Self>,
 5100    ) -> Task<Result<bool>> {
 5101        let client = self.upstream_client();
 5102
 5103        let buffer_id = buffer.read(cx).remote_id();
 5104        let buffer_snapshot = buffer.read(cx).snapshot();
 5105
 5106        cx.spawn(async move |this, cx| {
 5107            let mut did_resolve = false;
 5108            if let Some((client, project_id)) = client {
 5109                for completion_index in completion_indices {
 5110                    let server_id = {
 5111                        let completion = &completions.borrow()[completion_index];
 5112                        completion.source.server_id()
 5113                    };
 5114                    if let Some(server_id) = server_id {
 5115                        if Self::resolve_completion_remote(
 5116                            project_id,
 5117                            server_id,
 5118                            buffer_id,
 5119                            completions.clone(),
 5120                            completion_index,
 5121                            client.clone(),
 5122                        )
 5123                        .await
 5124                        .log_err()
 5125                        .is_some()
 5126                        {
 5127                            did_resolve = true;
 5128                        }
 5129                    } else {
 5130                        resolve_word_completion(
 5131                            &buffer_snapshot,
 5132                            &mut completions.borrow_mut()[completion_index],
 5133                        );
 5134                    }
 5135                }
 5136            } else {
 5137                for completion_index in completion_indices {
 5138                    let server_id = {
 5139                        let completion = &completions.borrow()[completion_index];
 5140                        completion.source.server_id()
 5141                    };
 5142                    if let Some(server_id) = server_id {
 5143                        let server_and_adapter = this
 5144                            .read_with(cx, |lsp_store, _| {
 5145                                let server = lsp_store.language_server_for_id(server_id)?;
 5146                                let adapter =
 5147                                    lsp_store.language_server_adapter_for_id(server.server_id())?;
 5148                                Some((server, adapter))
 5149                            })
 5150                            .ok()
 5151                            .flatten();
 5152                        let Some((server, adapter)) = server_and_adapter else {
 5153                            continue;
 5154                        };
 5155
 5156                        let resolved = Self::resolve_completion_local(
 5157                            server,
 5158                            &buffer_snapshot,
 5159                            completions.clone(),
 5160                            completion_index,
 5161                        )
 5162                        .await
 5163                        .log_err()
 5164                        .is_some();
 5165                        if resolved {
 5166                            Self::regenerate_completion_labels(
 5167                                adapter,
 5168                                &buffer_snapshot,
 5169                                completions.clone(),
 5170                                completion_index,
 5171                            )
 5172                            .await
 5173                            .log_err();
 5174                            did_resolve = true;
 5175                        }
 5176                    } else {
 5177                        resolve_word_completion(
 5178                            &buffer_snapshot,
 5179                            &mut completions.borrow_mut()[completion_index],
 5180                        );
 5181                    }
 5182                }
 5183            }
 5184
 5185            Ok(did_resolve)
 5186        })
 5187    }
 5188
 5189    async fn resolve_completion_local(
 5190        server: Arc<lsp::LanguageServer>,
 5191        snapshot: &BufferSnapshot,
 5192        completions: Rc<RefCell<Box<[Completion]>>>,
 5193        completion_index: usize,
 5194    ) -> Result<()> {
 5195        let server_id = server.server_id();
 5196        let can_resolve = server
 5197            .capabilities()
 5198            .completion_provider
 5199            .as_ref()
 5200            .and_then(|options| options.resolve_provider)
 5201            .unwrap_or(false);
 5202        if !can_resolve {
 5203            return Ok(());
 5204        }
 5205
 5206        let request = {
 5207            let completion = &completions.borrow()[completion_index];
 5208            match &completion.source {
 5209                CompletionSource::Lsp {
 5210                    lsp_completion,
 5211                    resolved,
 5212                    server_id: completion_server_id,
 5213                    ..
 5214                } => {
 5215                    if *resolved {
 5216                        return Ok(());
 5217                    }
 5218                    anyhow::ensure!(
 5219                        server_id == *completion_server_id,
 5220                        "server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
 5221                    );
 5222                    server.request::<lsp::request::ResolveCompletionItem>(*lsp_completion.clone())
 5223                }
 5224                CompletionSource::BufferWord { .. } | CompletionSource::Custom => {
 5225                    return Ok(());
 5226                }
 5227            }
 5228        };
 5229        let resolved_completion = request.await?;
 5230
 5231        let mut updated_insert_range = None;
 5232        if let Some(text_edit) = resolved_completion.text_edit.as_ref() {
 5233            // Technically we don't have to parse the whole `text_edit`, since the only
 5234            // language server we currently use that does update `text_edit` in `completionItem/resolve`
 5235            // is `typescript-language-server` and they only update `text_edit.new_text`.
 5236            // But we should not rely on that.
 5237            let edit = parse_completion_text_edit(text_edit, snapshot);
 5238
 5239            if let Some(mut parsed_edit) = edit {
 5240                LineEnding::normalize(&mut parsed_edit.new_text);
 5241
 5242                let mut completions = completions.borrow_mut();
 5243                let completion = &mut completions[completion_index];
 5244
 5245                completion.new_text = parsed_edit.new_text;
 5246                completion.replace_range = parsed_edit.replace_range;
 5247
 5248                updated_insert_range = parsed_edit.insert_range;
 5249            }
 5250        }
 5251
 5252        let mut completions = completions.borrow_mut();
 5253        let completion = &mut completions[completion_index];
 5254        if let CompletionSource::Lsp {
 5255            insert_range,
 5256            lsp_completion,
 5257            resolved,
 5258            server_id: completion_server_id,
 5259            ..
 5260        } = &mut completion.source
 5261        {
 5262            *insert_range = updated_insert_range;
 5263            if *resolved {
 5264                return Ok(());
 5265            }
 5266            anyhow::ensure!(
 5267                server_id == *completion_server_id,
 5268                "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
 5269            );
 5270            *lsp_completion = Box::new(resolved_completion);
 5271            *resolved = true;
 5272        }
 5273        Ok(())
 5274    }
 5275
 5276    async fn regenerate_completion_labels(
 5277        adapter: Arc<CachedLspAdapter>,
 5278        snapshot: &BufferSnapshot,
 5279        completions: Rc<RefCell<Box<[Completion]>>>,
 5280        completion_index: usize,
 5281    ) -> Result<()> {
 5282        let completion_item = completions.borrow()[completion_index]
 5283            .source
 5284            .lsp_completion(true)
 5285            .map(Cow::into_owned);
 5286        if let Some(lsp_documentation) = completion_item
 5287            .as_ref()
 5288            .and_then(|completion_item| completion_item.documentation.clone())
 5289        {
 5290            let mut completions = completions.borrow_mut();
 5291            let completion = &mut completions[completion_index];
 5292            completion.documentation = Some(lsp_documentation.into());
 5293        } else {
 5294            let mut completions = completions.borrow_mut();
 5295            let completion = &mut completions[completion_index];
 5296            completion.documentation = Some(CompletionDocumentation::Undocumented);
 5297        }
 5298
 5299        let mut new_label = match completion_item {
 5300            Some(completion_item) => {
 5301                // 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
 5302                // So we have to update the label here anyway...
 5303                let language = snapshot.language();
 5304                match language {
 5305                    Some(language) => {
 5306                        adapter
 5307                            .labels_for_completions(&[completion_item.clone()], language)
 5308                            .await?
 5309                    }
 5310                    None => Vec::new(),
 5311                }
 5312                .pop()
 5313                .flatten()
 5314                .unwrap_or_else(|| {
 5315                    CodeLabel::fallback_for_completion(
 5316                        &completion_item,
 5317                        language.map(|language| language.as_ref()),
 5318                    )
 5319                })
 5320            }
 5321            None => CodeLabel::plain(
 5322                completions.borrow()[completion_index].new_text.clone(),
 5323                None,
 5324            ),
 5325        };
 5326        ensure_uniform_list_compatible_label(&mut new_label);
 5327
 5328        let mut completions = completions.borrow_mut();
 5329        let completion = &mut completions[completion_index];
 5330        if completion.label.filter_text() == new_label.filter_text() {
 5331            completion.label = new_label;
 5332        } else {
 5333            log::error!(
 5334                "Resolved completion changed display label from {} to {}. \
 5335                 Refusing to apply this because it changes the fuzzy match text from {} to {}",
 5336                completion.label.text(),
 5337                new_label.text(),
 5338                completion.label.filter_text(),
 5339                new_label.filter_text()
 5340            );
 5341        }
 5342
 5343        Ok(())
 5344    }
 5345
 5346    async fn resolve_completion_remote(
 5347        project_id: u64,
 5348        server_id: LanguageServerId,
 5349        buffer_id: BufferId,
 5350        completions: Rc<RefCell<Box<[Completion]>>>,
 5351        completion_index: usize,
 5352        client: AnyProtoClient,
 5353    ) -> Result<()> {
 5354        let lsp_completion = {
 5355            let completion = &completions.borrow()[completion_index];
 5356            match &completion.source {
 5357                CompletionSource::Lsp {
 5358                    lsp_completion,
 5359                    resolved,
 5360                    server_id: completion_server_id,
 5361                    ..
 5362                } => {
 5363                    anyhow::ensure!(
 5364                        server_id == *completion_server_id,
 5365                        "remote server_id mismatch, querying completion resolve for {server_id} but completion server id is {completion_server_id}"
 5366                    );
 5367                    if *resolved {
 5368                        return Ok(());
 5369                    }
 5370                    serde_json::to_string(lsp_completion).unwrap().into_bytes()
 5371                }
 5372                CompletionSource::Custom | CompletionSource::BufferWord { .. } => {
 5373                    return Ok(());
 5374                }
 5375            }
 5376        };
 5377        let request = proto::ResolveCompletionDocumentation {
 5378            project_id,
 5379            language_server_id: server_id.0 as u64,
 5380            lsp_completion,
 5381            buffer_id: buffer_id.into(),
 5382        };
 5383
 5384        let response = client
 5385            .request(request)
 5386            .await
 5387            .context("completion documentation resolve proto request")?;
 5388        let resolved_lsp_completion = serde_json::from_slice(&response.lsp_completion)?;
 5389
 5390        let documentation = if response.documentation.is_empty() {
 5391            CompletionDocumentation::Undocumented
 5392        } else if response.documentation_is_markdown {
 5393            CompletionDocumentation::MultiLineMarkdown(response.documentation.into())
 5394        } else if response.documentation.lines().count() <= 1 {
 5395            CompletionDocumentation::SingleLine(response.documentation.into())
 5396        } else {
 5397            CompletionDocumentation::MultiLinePlainText(response.documentation.into())
 5398        };
 5399
 5400        let mut completions = completions.borrow_mut();
 5401        let completion = &mut completions[completion_index];
 5402        completion.documentation = Some(documentation);
 5403        if let CompletionSource::Lsp {
 5404            insert_range,
 5405            lsp_completion,
 5406            resolved,
 5407            server_id: completion_server_id,
 5408            lsp_defaults: _,
 5409        } = &mut completion.source
 5410        {
 5411            let completion_insert_range = response
 5412                .old_insert_start
 5413                .and_then(deserialize_anchor)
 5414                .zip(response.old_insert_end.and_then(deserialize_anchor));
 5415            *insert_range = completion_insert_range.map(|(start, end)| start..end);
 5416
 5417            if *resolved {
 5418                return Ok(());
 5419            }
 5420            anyhow::ensure!(
 5421                server_id == *completion_server_id,
 5422                "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
 5423            );
 5424            *lsp_completion = Box::new(resolved_lsp_completion);
 5425            *resolved = true;
 5426        }
 5427
 5428        let replace_range = response
 5429            .old_replace_start
 5430            .and_then(deserialize_anchor)
 5431            .zip(response.old_replace_end.and_then(deserialize_anchor));
 5432        if let Some((old_replace_start, old_replace_end)) = replace_range {
 5433            if !response.new_text.is_empty() {
 5434                completion.new_text = response.new_text;
 5435                completion.replace_range = old_replace_start..old_replace_end;
 5436            }
 5437        }
 5438
 5439        Ok(())
 5440    }
 5441
 5442    pub fn apply_additional_edits_for_completion(
 5443        &self,
 5444        buffer_handle: Entity<Buffer>,
 5445        completions: Rc<RefCell<Box<[Completion]>>>,
 5446        completion_index: usize,
 5447        push_to_history: bool,
 5448        cx: &mut Context<Self>,
 5449    ) -> Task<Result<Option<Transaction>>> {
 5450        if let Some((client, project_id)) = self.upstream_client() {
 5451            let buffer = buffer_handle.read(cx);
 5452            let buffer_id = buffer.remote_id();
 5453            cx.spawn(async move |_, cx| {
 5454                let request = {
 5455                    let completion = completions.borrow()[completion_index].clone();
 5456                    proto::ApplyCompletionAdditionalEdits {
 5457                        project_id,
 5458                        buffer_id: buffer_id.into(),
 5459                        completion: Some(Self::serialize_completion(&CoreCompletion {
 5460                            replace_range: completion.replace_range,
 5461                            new_text: completion.new_text,
 5462                            source: completion.source,
 5463                        })),
 5464                    }
 5465                };
 5466
 5467                if let Some(transaction) = client.request(request).await?.transaction {
 5468                    let transaction = language::proto::deserialize_transaction(transaction)?;
 5469                    buffer_handle
 5470                        .update(cx, |buffer, _| {
 5471                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 5472                        })?
 5473                        .await?;
 5474                    if push_to_history {
 5475                        buffer_handle.update(cx, |buffer, _| {
 5476                            buffer.push_transaction(transaction.clone(), Instant::now());
 5477                            buffer.finalize_last_transaction();
 5478                        })?;
 5479                    }
 5480                    Ok(Some(transaction))
 5481                } else {
 5482                    Ok(None)
 5483                }
 5484            })
 5485        } else {
 5486            let Some(server) = buffer_handle.update(cx, |buffer, cx| {
 5487                let completion = &completions.borrow()[completion_index];
 5488                let server_id = completion.source.server_id()?;
 5489                Some(
 5490                    self.language_server_for_local_buffer(buffer, server_id, cx)?
 5491                        .1
 5492                        .clone(),
 5493                )
 5494            }) else {
 5495                return Task::ready(Ok(None));
 5496            };
 5497            let snapshot = buffer_handle.read(&cx).snapshot();
 5498
 5499            cx.spawn(async move |this, cx| {
 5500                Self::resolve_completion_local(
 5501                    server.clone(),
 5502                    &snapshot,
 5503                    completions.clone(),
 5504                    completion_index,
 5505                )
 5506                .await
 5507                .context("resolving completion")?;
 5508                let completion = completions.borrow()[completion_index].clone();
 5509                let additional_text_edits = completion
 5510                    .source
 5511                    .lsp_completion(true)
 5512                    .as_ref()
 5513                    .and_then(|lsp_completion| lsp_completion.additional_text_edits.clone());
 5514                if let Some(edits) = additional_text_edits {
 5515                    let edits = this
 5516                        .update(cx, |this, cx| {
 5517                            this.as_local_mut().unwrap().edits_from_lsp(
 5518                                &buffer_handle,
 5519                                edits,
 5520                                server.server_id(),
 5521                                None,
 5522                                cx,
 5523                            )
 5524                        })?
 5525                        .await?;
 5526
 5527                    buffer_handle.update(cx, |buffer, cx| {
 5528                        buffer.finalize_last_transaction();
 5529                        buffer.start_transaction();
 5530
 5531                        for (range, text) in edits {
 5532                            let primary = &completion.replace_range;
 5533                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 5534                                && primary.end.cmp(&range.start, buffer).is_ge();
 5535                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 5536                                && range.end.cmp(&primary.end, buffer).is_ge();
 5537
 5538                            //Skip additional edits which overlap with the primary completion edit
 5539                            //https://github.com/zed-industries/zed/pull/1871
 5540                            if !start_within && !end_within {
 5541                                buffer.edit([(range, text)], None, cx);
 5542                            }
 5543                        }
 5544
 5545                        let transaction = if buffer.end_transaction(cx).is_some() {
 5546                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 5547                            if !push_to_history {
 5548                                buffer.forget_transaction(transaction.id);
 5549                            }
 5550                            Some(transaction)
 5551                        } else {
 5552                            None
 5553                        };
 5554                        Ok(transaction)
 5555                    })?
 5556                } else {
 5557                    Ok(None)
 5558                }
 5559            })
 5560        }
 5561    }
 5562
 5563    pub fn inlay_hints(
 5564        &mut self,
 5565        buffer_handle: Entity<Buffer>,
 5566        range: Range<Anchor>,
 5567        cx: &mut Context<Self>,
 5568    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 5569        let buffer = buffer_handle.read(cx);
 5570        let range_start = range.start;
 5571        let range_end = range.end;
 5572        let buffer_id = buffer.remote_id().into();
 5573        let lsp_request = InlayHints { range };
 5574
 5575        if let Some((client, project_id)) = self.upstream_client() {
 5576            let request = proto::InlayHints {
 5577                project_id,
 5578                buffer_id,
 5579                start: Some(serialize_anchor(&range_start)),
 5580                end: Some(serialize_anchor(&range_end)),
 5581                version: serialize_version(&buffer_handle.read(cx).version()),
 5582            };
 5583            cx.spawn(async move |project, cx| {
 5584                let response = client
 5585                    .request(request)
 5586                    .await
 5587                    .context("inlay hints proto request")?;
 5588                LspCommand::response_from_proto(
 5589                    lsp_request,
 5590                    response,
 5591                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 5592                    buffer_handle.clone(),
 5593                    cx.clone(),
 5594                )
 5595                .await
 5596                .context("inlay hints proto response conversion")
 5597            })
 5598        } else {
 5599            let lsp_request_task = self.request_lsp(
 5600                buffer_handle.clone(),
 5601                LanguageServerToQuery::FirstCapable,
 5602                lsp_request,
 5603                cx,
 5604            );
 5605            cx.spawn(async move |_, cx| {
 5606                buffer_handle
 5607                    .update(cx, |buffer, _| {
 5608                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 5609                    })?
 5610                    .await
 5611                    .context("waiting for inlay hint request range edits")?;
 5612                lsp_request_task.await.context("inlay hints LSP request")
 5613            })
 5614        }
 5615    }
 5616
 5617    pub fn signature_help<T: ToPointUtf16>(
 5618        &mut self,
 5619        buffer: &Entity<Buffer>,
 5620        position: T,
 5621        cx: &mut Context<Self>,
 5622    ) -> Task<Vec<SignatureHelp>> {
 5623        let position = position.to_point_utf16(buffer.read(cx));
 5624
 5625        if let Some((client, upstream_project_id)) = self.upstream_client() {
 5626            let request_task = client.request(proto::MultiLspQuery {
 5627                buffer_id: buffer.read(cx).remote_id().into(),
 5628                version: serialize_version(&buffer.read(cx).version()),
 5629                project_id: upstream_project_id,
 5630                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5631                    proto::AllLanguageServers {},
 5632                )),
 5633                request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
 5634                    GetSignatureHelp { position }.to_proto(upstream_project_id, buffer.read(cx)),
 5635                )),
 5636            });
 5637            let buffer = buffer.clone();
 5638            cx.spawn(async move |weak_project, cx| {
 5639                let Some(project) = weak_project.upgrade() else {
 5640                    return Vec::new();
 5641                };
 5642                join_all(
 5643                    request_task
 5644                        .await
 5645                        .log_err()
 5646                        .map(|response| response.responses)
 5647                        .unwrap_or_default()
 5648                        .into_iter()
 5649                        .filter_map(|lsp_response| match lsp_response.response? {
 5650                            proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
 5651                                Some(response)
 5652                            }
 5653                            unexpected => {
 5654                                debug_panic!("Unexpected response: {unexpected:?}");
 5655                                None
 5656                            }
 5657                        })
 5658                        .map(|signature_response| {
 5659                            let response = GetSignatureHelp { position }.response_from_proto(
 5660                                signature_response,
 5661                                project.clone(),
 5662                                buffer.clone(),
 5663                                cx.clone(),
 5664                            );
 5665                            async move { response.await.log_err().flatten() }
 5666                        }),
 5667                )
 5668                .await
 5669                .into_iter()
 5670                .flatten()
 5671                .collect()
 5672            })
 5673        } else {
 5674            let all_actions_task = self.request_multiple_lsp_locally(
 5675                buffer,
 5676                Some(position),
 5677                GetSignatureHelp { position },
 5678                cx,
 5679            );
 5680            cx.spawn(async move |_, _| {
 5681                all_actions_task
 5682                    .await
 5683                    .into_iter()
 5684                    .flatten()
 5685                    .filter(|help| !help.label.is_empty())
 5686                    .collect::<Vec<_>>()
 5687            })
 5688        }
 5689    }
 5690
 5691    pub fn hover(
 5692        &mut self,
 5693        buffer: &Entity<Buffer>,
 5694        position: PointUtf16,
 5695        cx: &mut Context<Self>,
 5696    ) -> Task<Vec<Hover>> {
 5697        if let Some((client, upstream_project_id)) = self.upstream_client() {
 5698            let request_task = client.request(proto::MultiLspQuery {
 5699                buffer_id: buffer.read(cx).remote_id().into(),
 5700                version: serialize_version(&buffer.read(cx).version()),
 5701                project_id: upstream_project_id,
 5702                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5703                    proto::AllLanguageServers {},
 5704                )),
 5705                request: Some(proto::multi_lsp_query::Request::GetHover(
 5706                    GetHover { position }.to_proto(upstream_project_id, buffer.read(cx)),
 5707                )),
 5708            });
 5709            let buffer = buffer.clone();
 5710            cx.spawn(async move |weak_project, cx| {
 5711                let Some(project) = weak_project.upgrade() else {
 5712                    return Vec::new();
 5713                };
 5714                join_all(
 5715                    request_task
 5716                        .await
 5717                        .log_err()
 5718                        .map(|response| response.responses)
 5719                        .unwrap_or_default()
 5720                        .into_iter()
 5721                        .filter_map(|lsp_response| match lsp_response.response? {
 5722                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5723                                Some(response)
 5724                            }
 5725                            unexpected => {
 5726                                debug_panic!("Unexpected response: {unexpected:?}");
 5727                                None
 5728                            }
 5729                        })
 5730                        .map(|hover_response| {
 5731                            let response = GetHover { position }.response_from_proto(
 5732                                hover_response,
 5733                                project.clone(),
 5734                                buffer.clone(),
 5735                                cx.clone(),
 5736                            );
 5737                            async move {
 5738                                response
 5739                                    .await
 5740                                    .log_err()
 5741                                    .flatten()
 5742                                    .and_then(remove_empty_hover_blocks)
 5743                            }
 5744                        }),
 5745                )
 5746                .await
 5747                .into_iter()
 5748                .flatten()
 5749                .collect()
 5750            })
 5751        } else {
 5752            let all_actions_task = self.request_multiple_lsp_locally(
 5753                buffer,
 5754                Some(position),
 5755                GetHover { position },
 5756                cx,
 5757            );
 5758            cx.spawn(async move |_, _| {
 5759                all_actions_task
 5760                    .await
 5761                    .into_iter()
 5762                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5763                    .collect::<Vec<Hover>>()
 5764            })
 5765        }
 5766    }
 5767
 5768    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
 5769        let language_registry = self.languages.clone();
 5770
 5771        if let Some((upstream_client, project_id)) = self.upstream_client().as_ref() {
 5772            let request = upstream_client.request(proto::GetProjectSymbols {
 5773                project_id: *project_id,
 5774                query: query.to_string(),
 5775            });
 5776            cx.foreground_executor().spawn(async move {
 5777                let response = request.await?;
 5778                let mut symbols = Vec::new();
 5779                let core_symbols = response
 5780                    .symbols
 5781                    .into_iter()
 5782                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5783                    .collect::<Vec<_>>();
 5784                populate_labels_for_symbols(core_symbols, &language_registry, None, &mut symbols)
 5785                    .await;
 5786                Ok(symbols)
 5787            })
 5788        } else if let Some(local) = self.as_local() {
 5789            struct WorkspaceSymbolsResult {
 5790                server_id: LanguageServerId,
 5791                lsp_adapter: Arc<CachedLspAdapter>,
 5792                worktree: WeakEntity<Worktree>,
 5793                worktree_abs_path: Arc<Path>,
 5794                lsp_symbols: Vec<(String, SymbolKind, lsp::Location)>,
 5795            }
 5796
 5797            let mut requests = Vec::new();
 5798            let mut requested_servers = BTreeSet::new();
 5799            'next_server: for ((worktree_id, _), server_ids) in local.language_server_ids.iter() {
 5800                let Some(worktree_handle) = self
 5801                    .worktree_store
 5802                    .read(cx)
 5803                    .worktree_for_id(*worktree_id, cx)
 5804                else {
 5805                    continue;
 5806                };
 5807                let worktree = worktree_handle.read(cx);
 5808                if !worktree.is_visible() {
 5809                    continue;
 5810                }
 5811
 5812                let mut servers_to_query = server_ids
 5813                    .difference(&requested_servers)
 5814                    .cloned()
 5815                    .collect::<BTreeSet<_>>();
 5816                for server_id in &servers_to_query {
 5817                    let (lsp_adapter, server) = match local.language_servers.get(server_id) {
 5818                        Some(LanguageServerState::Running {
 5819                            adapter, server, ..
 5820                        }) => (adapter.clone(), server),
 5821
 5822                        _ => continue 'next_server,
 5823                    };
 5824                    let supports_workspace_symbol_request =
 5825                        match server.capabilities().workspace_symbol_provider {
 5826                            Some(OneOf::Left(supported)) => supported,
 5827                            Some(OneOf::Right(_)) => true,
 5828                            None => false,
 5829                        };
 5830                    if !supports_workspace_symbol_request {
 5831                        continue 'next_server;
 5832                    }
 5833                    let worktree_abs_path = worktree.abs_path().clone();
 5834                    let worktree_handle = worktree_handle.clone();
 5835                    let server_id = server.server_id();
 5836                    requests.push(
 5837                        server
 5838                            .request::<lsp::request::WorkspaceSymbolRequest>(
 5839                                lsp::WorkspaceSymbolParams {
 5840                                    query: query.to_string(),
 5841                                    ..Default::default()
 5842                                },
 5843                            )
 5844                            .log_err()
 5845                            .map(move |response| {
 5846                                let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5847                                    lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5848                                        flat_responses.into_iter().map(|lsp_symbol| {
 5849                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5850                                        }).collect::<Vec<_>>()
 5851                                    }
 5852                                    lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5853                                        nested_responses.into_iter().filter_map(|lsp_symbol| {
 5854                                            let location = match lsp_symbol.location {
 5855                                                OneOf::Left(location) => location,
 5856                                                OneOf::Right(_) => {
 5857                                                    log::error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5858                                                    return None
 5859                                                }
 5860                                            };
 5861                                            Some((lsp_symbol.name, lsp_symbol.kind, location))
 5862                                        }).collect::<Vec<_>>()
 5863                                    }
 5864                                }).unwrap_or_default();
 5865
 5866                                WorkspaceSymbolsResult {
 5867                                    server_id,
 5868                                    lsp_adapter,
 5869                                    worktree: worktree_handle.downgrade(),
 5870                                    worktree_abs_path,
 5871                                    lsp_symbols,
 5872                                }
 5873                            }),
 5874                    );
 5875                }
 5876                requested_servers.append(&mut servers_to_query);
 5877            }
 5878
 5879            cx.spawn(async move |this, cx| {
 5880                let responses = futures::future::join_all(requests).await;
 5881                let this = match this.upgrade() {
 5882                    Some(this) => this,
 5883                    None => return Ok(Vec::new()),
 5884                };
 5885
 5886                let mut symbols = Vec::new();
 5887                for result in responses {
 5888                    let core_symbols = this.update(cx, |this, cx| {
 5889                        result
 5890                            .lsp_symbols
 5891                            .into_iter()
 5892                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5893                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5894                                let source_worktree = result.worktree.upgrade()?;
 5895                                let source_worktree_id = source_worktree.read(cx).id();
 5896
 5897                                let path;
 5898                                let worktree;
 5899                                if let Some((tree, rel_path)) =
 5900                                    this.worktree_store.read(cx).find_worktree(&abs_path, cx)
 5901                                {
 5902                                    worktree = tree;
 5903                                    path = rel_path;
 5904                                } else {
 5905                                    worktree = source_worktree.clone();
 5906                                    path = relativize_path(&result.worktree_abs_path, &abs_path);
 5907                                }
 5908
 5909                                let worktree_id = worktree.read(cx).id();
 5910                                let project_path = ProjectPath {
 5911                                    worktree_id,
 5912                                    path: path.into(),
 5913                                };
 5914                                let signature = this.symbol_signature(&project_path);
 5915                                Some(CoreSymbol {
 5916                                    source_language_server_id: result.server_id,
 5917                                    language_server_name: result.lsp_adapter.name.clone(),
 5918                                    source_worktree_id,
 5919                                    path: project_path,
 5920                                    kind: symbol_kind,
 5921                                    name: symbol_name,
 5922                                    range: range_from_lsp(symbol_location.range),
 5923                                    signature,
 5924                                })
 5925                            })
 5926                            .collect()
 5927                    })?;
 5928
 5929                    populate_labels_for_symbols(
 5930                        core_symbols,
 5931                        &language_registry,
 5932                        Some(result.lsp_adapter),
 5933                        &mut symbols,
 5934                    )
 5935                    .await;
 5936                }
 5937
 5938                Ok(symbols)
 5939            })
 5940        } else {
 5941            Task::ready(Err(anyhow!("No upstream client or local language server")))
 5942        }
 5943    }
 5944
 5945    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
 5946        let mut summary = DiagnosticSummary::default();
 5947        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 5948            summary.error_count += path_summary.error_count;
 5949            summary.warning_count += path_summary.warning_count;
 5950        }
 5951        summary
 5952    }
 5953
 5954    pub fn diagnostic_summaries<'a>(
 5955        &'a self,
 5956        include_ignored: bool,
 5957        cx: &'a App,
 5958    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 5959        self.worktree_store
 5960            .read(cx)
 5961            .visible_worktrees(cx)
 5962            .filter_map(|worktree| {
 5963                let worktree = worktree.read(cx);
 5964                Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
 5965            })
 5966            .flat_map(move |(worktree, summaries)| {
 5967                let worktree_id = worktree.id();
 5968                summaries
 5969                    .iter()
 5970                    .filter(move |(path, _)| {
 5971                        include_ignored
 5972                            || worktree
 5973                                .entry_for_path(path.as_ref())
 5974                                .map_or(false, |entry| !entry.is_ignored)
 5975                    })
 5976                    .flat_map(move |(path, summaries)| {
 5977                        summaries.iter().map(move |(server_id, summary)| {
 5978                            (
 5979                                ProjectPath {
 5980                                    worktree_id,
 5981                                    path: path.clone(),
 5982                                },
 5983                                *server_id,
 5984                                *summary,
 5985                            )
 5986                        })
 5987                    })
 5988            })
 5989    }
 5990
 5991    pub fn on_buffer_edited(
 5992        &mut self,
 5993        buffer: Entity<Buffer>,
 5994        cx: &mut Context<Self>,
 5995    ) -> Option<()> {
 5996        let language_servers: Vec<_> = buffer.update(cx, |buffer, cx| {
 5997            Some(
 5998                self.as_local()?
 5999                    .language_servers_for_buffer(buffer, cx)
 6000                    .map(|i| i.1.clone())
 6001                    .collect(),
 6002            )
 6003        })?;
 6004
 6005        let buffer = buffer.read(cx);
 6006        let file = File::from_dyn(buffer.file())?;
 6007        let abs_path = file.as_local()?.abs_path(cx);
 6008        let uri = lsp::Url::from_file_path(abs_path).unwrap();
 6009        let next_snapshot = buffer.text_snapshot();
 6010        for language_server in language_servers {
 6011            let language_server = language_server.clone();
 6012
 6013            let buffer_snapshots = self
 6014                .as_local_mut()
 6015                .unwrap()
 6016                .buffer_snapshots
 6017                .get_mut(&buffer.remote_id())
 6018                .and_then(|m| m.get_mut(&language_server.server_id()))?;
 6019            let previous_snapshot = buffer_snapshots.last()?;
 6020
 6021            let build_incremental_change = || {
 6022                buffer
 6023                    .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
 6024                    .map(|edit| {
 6025                        let edit_start = edit.new.start.0;
 6026                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 6027                        let new_text = next_snapshot
 6028                            .text_for_range(edit.new.start.1..edit.new.end.1)
 6029                            .collect();
 6030                        lsp::TextDocumentContentChangeEvent {
 6031                            range: Some(lsp::Range::new(
 6032                                point_to_lsp(edit_start),
 6033                                point_to_lsp(edit_end),
 6034                            )),
 6035                            range_length: None,
 6036                            text: new_text,
 6037                        }
 6038                    })
 6039                    .collect()
 6040            };
 6041
 6042            let document_sync_kind = language_server
 6043                .capabilities()
 6044                .text_document_sync
 6045                .as_ref()
 6046                .and_then(|sync| match sync {
 6047                    lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 6048                    lsp::TextDocumentSyncCapability::Options(options) => options.change,
 6049                });
 6050
 6051            let content_changes: Vec<_> = match document_sync_kind {
 6052                Some(lsp::TextDocumentSyncKind::FULL) => {
 6053                    vec![lsp::TextDocumentContentChangeEvent {
 6054                        range: None,
 6055                        range_length: None,
 6056                        text: next_snapshot.text(),
 6057                    }]
 6058                }
 6059                Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 6060                _ => {
 6061                    #[cfg(any(test, feature = "test-support"))]
 6062                    {
 6063                        build_incremental_change()
 6064                    }
 6065
 6066                    #[cfg(not(any(test, feature = "test-support")))]
 6067                    {
 6068                        continue;
 6069                    }
 6070                }
 6071            };
 6072
 6073            let next_version = previous_snapshot.version + 1;
 6074            buffer_snapshots.push(LspBufferSnapshot {
 6075                version: next_version,
 6076                snapshot: next_snapshot.clone(),
 6077            });
 6078
 6079            language_server
 6080                .notify::<lsp::notification::DidChangeTextDocument>(
 6081                    &lsp::DidChangeTextDocumentParams {
 6082                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 6083                            uri.clone(),
 6084                            next_version,
 6085                        ),
 6086                        content_changes,
 6087                    },
 6088                )
 6089                .log_err();
 6090        }
 6091
 6092        None
 6093    }
 6094
 6095    pub fn on_buffer_saved(
 6096        &mut self,
 6097        buffer: Entity<Buffer>,
 6098        cx: &mut Context<Self>,
 6099    ) -> Option<()> {
 6100        let file = File::from_dyn(buffer.read(cx).file())?;
 6101        let worktree_id = file.worktree_id(cx);
 6102        let abs_path = file.as_local()?.abs_path(cx);
 6103        let text_document = lsp::TextDocumentIdentifier {
 6104            uri: lsp::Url::from_file_path(abs_path).log_err()?,
 6105        };
 6106        let local = self.as_local()?;
 6107
 6108        for server in local.language_servers_for_worktree(worktree_id) {
 6109            if let Some(include_text) = include_text(server.as_ref()) {
 6110                let text = if include_text {
 6111                    Some(buffer.read(cx).text())
 6112                } else {
 6113                    None
 6114                };
 6115                server
 6116                    .notify::<lsp::notification::DidSaveTextDocument>(
 6117                        &lsp::DidSaveTextDocumentParams {
 6118                            text_document: text_document.clone(),
 6119                            text,
 6120                        },
 6121                    )
 6122                    .log_err();
 6123            }
 6124        }
 6125
 6126        let language_servers = buffer.update(cx, |buffer, cx| {
 6127            local.language_server_ids_for_buffer(buffer, cx)
 6128        });
 6129        for language_server_id in language_servers {
 6130            self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
 6131        }
 6132
 6133        None
 6134    }
 6135
 6136    pub(crate) async fn refresh_workspace_configurations(
 6137        this: &WeakEntity<Self>,
 6138        fs: Arc<dyn Fs>,
 6139        cx: &mut AsyncApp,
 6140    ) {
 6141        maybe!(async move {
 6142            let servers = this
 6143                .update(cx, |this, cx| {
 6144                    let Some(local) = this.as_local() else {
 6145                        return Vec::default();
 6146                    };
 6147                    local
 6148                        .language_server_ids
 6149                        .iter()
 6150                        .flat_map(|((worktree_id, _), server_ids)| {
 6151                            let worktree = this
 6152                                .worktree_store
 6153                                .read(cx)
 6154                                .worktree_for_id(*worktree_id, cx);
 6155                            let delegate = worktree.map(|worktree| {
 6156                                LocalLspAdapterDelegate::new(
 6157                                    local.languages.clone(),
 6158                                    &local.environment,
 6159                                    cx.weak_entity(),
 6160                                    &worktree,
 6161                                    local.http_client.clone(),
 6162                                    local.fs.clone(),
 6163                                    cx,
 6164                                )
 6165                            });
 6166
 6167                            server_ids.iter().filter_map(move |server_id| {
 6168                                let states = local.language_servers.get(server_id)?;
 6169
 6170                                match states {
 6171                                    LanguageServerState::Starting { .. } => None,
 6172                                    LanguageServerState::Running {
 6173                                        adapter, server, ..
 6174                                    } => Some((
 6175                                        adapter.adapter.clone(),
 6176                                        server.clone(),
 6177                                        delegate.clone()? as Arc<dyn LspAdapterDelegate>,
 6178                                    )),
 6179                                }
 6180                            })
 6181                        })
 6182                        .collect::<Vec<_>>()
 6183                })
 6184                .ok()?;
 6185
 6186            let toolchain_store = this.update(cx, |this, cx| this.toolchain_store(cx)).ok()?;
 6187            for (adapter, server, delegate) in servers {
 6188                let settings = LocalLspStore::workspace_configuration_for_adapter(
 6189                    adapter,
 6190                    fs.as_ref(),
 6191                    &delegate,
 6192                    toolchain_store.clone(),
 6193                    cx,
 6194                )
 6195                .await
 6196                .ok()?;
 6197
 6198                server
 6199                    .notify::<lsp::notification::DidChangeConfiguration>(
 6200                        &lsp::DidChangeConfigurationParams { settings },
 6201                    )
 6202                    .ok();
 6203            }
 6204            Some(())
 6205        })
 6206        .await;
 6207    }
 6208
 6209    fn toolchain_store(&self, cx: &App) -> Arc<dyn LanguageToolchainStore> {
 6210        if let Some(toolchain_store) = self.toolchain_store.as_ref() {
 6211            toolchain_store.read(cx).as_language_toolchain_store()
 6212        } else {
 6213            Arc::new(EmptyToolchainStore)
 6214        }
 6215    }
 6216    fn maintain_workspace_config(
 6217        fs: Arc<dyn Fs>,
 6218        external_refresh_requests: watch::Receiver<()>,
 6219        cx: &mut Context<Self>,
 6220    ) -> Task<Result<()>> {
 6221        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 6222        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 6223
 6224        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 6225            *settings_changed_tx.borrow_mut() = ();
 6226        });
 6227
 6228        let mut joint_future =
 6229            futures::stream::select(settings_changed_rx, external_refresh_requests);
 6230        cx.spawn(async move |this, cx| {
 6231            while let Some(()) = joint_future.next().await {
 6232                Self::refresh_workspace_configurations(&this, fs.clone(), cx).await;
 6233            }
 6234
 6235            drop(settings_observation);
 6236            anyhow::Ok(())
 6237        })
 6238    }
 6239
 6240    pub fn language_servers_for_local_buffer<'a>(
 6241        &'a self,
 6242        buffer: &Buffer,
 6243        cx: &mut App,
 6244    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
 6245        let local = self.as_local();
 6246        let language_server_ids = local
 6247            .map(|local| local.language_server_ids_for_buffer(buffer, cx))
 6248            .unwrap_or_default();
 6249
 6250        language_server_ids
 6251            .into_iter()
 6252            .filter_map(
 6253                move |server_id| match local?.language_servers.get(&server_id)? {
 6254                    LanguageServerState::Running {
 6255                        adapter, server, ..
 6256                    } => Some((adapter, server)),
 6257                    _ => None,
 6258                },
 6259            )
 6260    }
 6261
 6262    pub fn language_server_for_local_buffer<'a>(
 6263        &'a self,
 6264        buffer: &'a Buffer,
 6265        server_id: LanguageServerId,
 6266        cx: &'a mut App,
 6267    ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
 6268        self.as_local()?
 6269            .language_servers_for_buffer(buffer, cx)
 6270            .find(|(_, s)| s.server_id() == server_id)
 6271    }
 6272
 6273    fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
 6274        self.diagnostic_summaries.remove(&id_to_remove);
 6275        if let Some(local) = self.as_local_mut() {
 6276            let to_remove = local.remove_worktree(id_to_remove, cx);
 6277            for server in to_remove {
 6278                self.language_server_statuses.remove(&server);
 6279            }
 6280        }
 6281    }
 6282
 6283    pub fn shared(
 6284        &mut self,
 6285        project_id: u64,
 6286        downstream_client: AnyProtoClient,
 6287        _: &mut Context<Self>,
 6288    ) {
 6289        self.downstream_client = Some((downstream_client.clone(), project_id));
 6290
 6291        for (server_id, status) in &self.language_server_statuses {
 6292            downstream_client
 6293                .send(proto::StartLanguageServer {
 6294                    project_id,
 6295                    server: Some(proto::LanguageServer {
 6296                        id: server_id.0 as u64,
 6297                        name: status.name.clone(),
 6298                        worktree_id: None,
 6299                    }),
 6300                })
 6301                .log_err();
 6302        }
 6303    }
 6304
 6305    pub fn disconnected_from_host(&mut self) {
 6306        self.downstream_client.take();
 6307    }
 6308
 6309    pub fn disconnected_from_ssh_remote(&mut self) {
 6310        if let LspStoreMode::Remote(RemoteLspStore {
 6311            upstream_client, ..
 6312        }) = &mut self.mode
 6313        {
 6314            upstream_client.take();
 6315        }
 6316    }
 6317
 6318    pub(crate) fn set_language_server_statuses_from_proto(
 6319        &mut self,
 6320        language_servers: Vec<proto::LanguageServer>,
 6321    ) {
 6322        self.language_server_statuses = language_servers
 6323            .into_iter()
 6324            .map(|server| {
 6325                (
 6326                    LanguageServerId(server.id as usize),
 6327                    LanguageServerStatus {
 6328                        name: server.name,
 6329                        pending_work: Default::default(),
 6330                        has_pending_diagnostic_updates: false,
 6331                        progress_tokens: Default::default(),
 6332                    },
 6333                )
 6334            })
 6335            .collect();
 6336    }
 6337
 6338    fn register_local_language_server(
 6339        &mut self,
 6340        worktree: Entity<Worktree>,
 6341        language_server_name: LanguageServerName,
 6342        language_server_id: LanguageServerId,
 6343        cx: &mut App,
 6344    ) {
 6345        let Some(local) = self.as_local_mut() else {
 6346            return;
 6347        };
 6348        let worktree_id = worktree.read(cx).id();
 6349        let path = ProjectPath {
 6350            worktree_id,
 6351            path: Arc::from("".as_ref()),
 6352        };
 6353        let delegate = LocalLspAdapterDelegate::from_local_lsp(local, &worktree, cx);
 6354        local.lsp_tree.update(cx, |this, cx| {
 6355            for node in this.get(
 6356                path,
 6357                AdapterQuery::Adapter(&language_server_name),
 6358                delegate,
 6359                cx,
 6360            ) {
 6361                node.server_id_or_init(|disposition| {
 6362                    assert_eq!(disposition.server_name, &language_server_name);
 6363
 6364                    language_server_id
 6365                });
 6366            }
 6367        });
 6368        local
 6369            .language_server_ids
 6370            .entry((worktree_id, language_server_name))
 6371            .or_default()
 6372            .insert(language_server_id);
 6373    }
 6374
 6375    pub fn update_diagnostic_entries(
 6376        &mut self,
 6377        server_id: LanguageServerId,
 6378        abs_path: PathBuf,
 6379        version: Option<i32>,
 6380        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 6381        cx: &mut Context<Self>,
 6382    ) -> anyhow::Result<()> {
 6383        self.merge_diagnostic_entries(server_id, abs_path, version, diagnostics, |_| false, cx)
 6384    }
 6385
 6386    pub fn merge_diagnostic_entries<F: Fn(&Diagnostic) -> bool + Clone>(
 6387        &mut self,
 6388        server_id: LanguageServerId,
 6389        abs_path: PathBuf,
 6390        version: Option<i32>,
 6391        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 6392        filter: F,
 6393        cx: &mut Context<Self>,
 6394    ) -> Result<(), anyhow::Error> {
 6395        let Some((worktree, relative_path)) =
 6396            self.worktree_store.read(cx).find_worktree(&abs_path, cx)
 6397        else {
 6398            log::warn!("skipping diagnostics update, no worktree found for path {abs_path:?}");
 6399            return Ok(());
 6400        };
 6401
 6402        let project_path = ProjectPath {
 6403            worktree_id: worktree.read(cx).id(),
 6404            path: relative_path.into(),
 6405        };
 6406
 6407        if let Some(buffer) = self.buffer_store.read(cx).get_by_path(&project_path, cx) {
 6408            let snapshot = self
 6409                .as_local_mut()
 6410                .unwrap()
 6411                .buffer_snapshot_for_lsp_version(&buffer, server_id, version, cx)?;
 6412
 6413            diagnostics.extend(
 6414                buffer
 6415                    .read(cx)
 6416                    .get_diagnostics(server_id)
 6417                    .into_iter()
 6418                    .flat_map(|diag| {
 6419                        diag.iter().filter(|v| filter(&v.diagnostic)).map(|v| {
 6420                            let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
 6421                            let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
 6422                            DiagnosticEntry {
 6423                                range: start..end,
 6424                                diagnostic: v.diagnostic.clone(),
 6425                            }
 6426                        })
 6427                    }),
 6428            );
 6429
 6430            self.as_local_mut().unwrap().update_buffer_diagnostics(
 6431                &buffer,
 6432                server_id,
 6433                version,
 6434                diagnostics.clone(),
 6435                cx,
 6436            )?;
 6437        }
 6438
 6439        let updated = worktree.update(cx, |worktree, cx| {
 6440            self.update_worktree_diagnostics(
 6441                worktree.id(),
 6442                server_id,
 6443                project_path.path.clone(),
 6444                diagnostics,
 6445                cx,
 6446            )
 6447        })?;
 6448        if updated {
 6449            cx.emit(LspStoreEvent::DiagnosticsUpdated {
 6450                language_server_id: server_id,
 6451                path: project_path,
 6452            })
 6453        }
 6454        Ok(())
 6455    }
 6456
 6457    fn update_worktree_diagnostics(
 6458        &mut self,
 6459        worktree_id: WorktreeId,
 6460        server_id: LanguageServerId,
 6461        worktree_path: Arc<Path>,
 6462        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 6463        _: &mut Context<Worktree>,
 6464    ) -> Result<bool> {
 6465        let local = match &mut self.mode {
 6466            LspStoreMode::Local(local_lsp_store) => local_lsp_store,
 6467            _ => anyhow::bail!("update_worktree_diagnostics called on remote"),
 6468        };
 6469
 6470        let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
 6471        let diagnostics_for_tree = local.diagnostics.entry(worktree_id).or_default();
 6472        let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
 6473
 6474        let old_summary = summaries_by_server_id
 6475            .remove(&server_id)
 6476            .unwrap_or_default();
 6477
 6478        let new_summary = DiagnosticSummary::new(&diagnostics);
 6479        if new_summary.is_empty() {
 6480            if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
 6481                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 6482                    diagnostics_by_server_id.remove(ix);
 6483                }
 6484                if diagnostics_by_server_id.is_empty() {
 6485                    diagnostics_for_tree.remove(&worktree_path);
 6486                }
 6487            }
 6488        } else {
 6489            summaries_by_server_id.insert(server_id, new_summary);
 6490            let diagnostics_by_server_id = diagnostics_for_tree
 6491                .entry(worktree_path.clone())
 6492                .or_default();
 6493            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 6494                Ok(ix) => {
 6495                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 6496                }
 6497                Err(ix) => {
 6498                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 6499                }
 6500            }
 6501        }
 6502
 6503        if !old_summary.is_empty() || !new_summary.is_empty() {
 6504            if let Some((downstream_client, project_id)) = &self.downstream_client {
 6505                downstream_client
 6506                    .send(proto::UpdateDiagnosticSummary {
 6507                        project_id: *project_id,
 6508                        worktree_id: worktree_id.to_proto(),
 6509                        summary: Some(proto::DiagnosticSummary {
 6510                            path: worktree_path.to_proto(),
 6511                            language_server_id: server_id.0 as u64,
 6512                            error_count: new_summary.error_count as u32,
 6513                            warning_count: new_summary.warning_count as u32,
 6514                        }),
 6515                    })
 6516                    .log_err();
 6517            }
 6518        }
 6519
 6520        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 6521    }
 6522
 6523    pub fn open_buffer_for_symbol(
 6524        &mut self,
 6525        symbol: &Symbol,
 6526        cx: &mut Context<Self>,
 6527    ) -> Task<Result<Entity<Buffer>>> {
 6528        if let Some((client, project_id)) = self.upstream_client() {
 6529            let request = client.request(proto::OpenBufferForSymbol {
 6530                project_id,
 6531                symbol: Some(Self::serialize_symbol(symbol)),
 6532            });
 6533            cx.spawn(async move |this, cx| {
 6534                let response = request.await?;
 6535                let buffer_id = BufferId::new(response.buffer_id)?;
 6536                this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 6537                    .await
 6538            })
 6539        } else if let Some(local) = self.as_local() {
 6540            let Some(language_server_id) = local
 6541                .language_server_ids
 6542                .get(&(
 6543                    symbol.source_worktree_id,
 6544                    symbol.language_server_name.clone(),
 6545                ))
 6546                .and_then(|ids| {
 6547                    ids.contains(&symbol.source_language_server_id)
 6548                        .then_some(symbol.source_language_server_id)
 6549                })
 6550            else {
 6551                return Task::ready(Err(anyhow!(
 6552                    "language server for worktree and language not found"
 6553                )));
 6554            };
 6555
 6556            let worktree_abs_path = if let Some(worktree_abs_path) = self
 6557                .worktree_store
 6558                .read(cx)
 6559                .worktree_for_id(symbol.path.worktree_id, cx)
 6560                .map(|worktree| worktree.read(cx).abs_path())
 6561            {
 6562                worktree_abs_path
 6563            } else {
 6564                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 6565            };
 6566
 6567            let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
 6568            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 6569                uri
 6570            } else {
 6571                return Task::ready(Err(anyhow!("invalid symbol path")));
 6572            };
 6573
 6574            self.open_local_buffer_via_lsp(
 6575                symbol_uri,
 6576                language_server_id,
 6577                symbol.language_server_name.clone(),
 6578                cx,
 6579            )
 6580        } else {
 6581            Task::ready(Err(anyhow!("no upstream client or local store")))
 6582        }
 6583    }
 6584
 6585    pub fn open_local_buffer_via_lsp(
 6586        &mut self,
 6587        mut abs_path: lsp::Url,
 6588        language_server_id: LanguageServerId,
 6589        language_server_name: LanguageServerName,
 6590        cx: &mut Context<Self>,
 6591    ) -> Task<Result<Entity<Buffer>>> {
 6592        cx.spawn(async move |lsp_store, cx| {
 6593            // Escape percent-encoded string.
 6594            let current_scheme = abs_path.scheme().to_owned();
 6595            let _ = abs_path.set_scheme("file");
 6596
 6597            let abs_path = abs_path
 6598                .to_file_path()
 6599                .map_err(|_| anyhow!("can't convert URI to path"))?;
 6600            let p = abs_path.clone();
 6601            let yarn_worktree = lsp_store
 6602                .update(cx, move |lsp_store, cx| match lsp_store.as_local() {
 6603                    Some(local_lsp_store) => local_lsp_store.yarn.update(cx, |_, cx| {
 6604                        cx.spawn(async move |this, cx| {
 6605                            let t = this
 6606                                .update(cx, |this, cx| this.process_path(&p, &current_scheme, cx))
 6607                                .ok()?;
 6608                            t.await
 6609                        })
 6610                    }),
 6611                    None => Task::ready(None),
 6612                })?
 6613                .await;
 6614            let (worktree_root_target, known_relative_path) =
 6615                if let Some((zip_root, relative_path)) = yarn_worktree {
 6616                    (zip_root, Some(relative_path))
 6617                } else {
 6618                    (Arc::<Path>::from(abs_path.as_path()), None)
 6619                };
 6620            let (worktree, relative_path) = if let Some(result) =
 6621                lsp_store.update(cx, |lsp_store, cx| {
 6622                    lsp_store.worktree_store.update(cx, |worktree_store, cx| {
 6623                        worktree_store.find_worktree(&worktree_root_target, cx)
 6624                    })
 6625                })? {
 6626                let relative_path =
 6627                    known_relative_path.unwrap_or_else(|| Arc::<Path>::from(result.1));
 6628                (result.0, relative_path)
 6629            } else {
 6630                let worktree = lsp_store
 6631                    .update(cx, |lsp_store, cx| {
 6632                        lsp_store.worktree_store.update(cx, |worktree_store, cx| {
 6633                            worktree_store.create_worktree(&worktree_root_target, false, cx)
 6634                        })
 6635                    })?
 6636                    .await?;
 6637                if worktree.update(cx, |worktree, _| worktree.is_local())? {
 6638                    lsp_store
 6639                        .update(cx, |lsp_store, cx| {
 6640                            lsp_store.register_local_language_server(
 6641                                worktree.clone(),
 6642                                language_server_name,
 6643                                language_server_id,
 6644                                cx,
 6645                            )
 6646                        })
 6647                        .ok();
 6648                }
 6649                let worktree_root = worktree.update(cx, |worktree, _| worktree.abs_path())?;
 6650                let relative_path = if let Some(known_path) = known_relative_path {
 6651                    known_path
 6652                } else {
 6653                    abs_path.strip_prefix(worktree_root)?.into()
 6654                };
 6655                (worktree, relative_path)
 6656            };
 6657            let project_path = ProjectPath {
 6658                worktree_id: worktree.update(cx, |worktree, _| worktree.id())?,
 6659                path: relative_path,
 6660            };
 6661            lsp_store
 6662                .update(cx, |lsp_store, cx| {
 6663                    lsp_store.buffer_store().update(cx, |buffer_store, cx| {
 6664                        buffer_store.open_buffer(project_path, cx)
 6665                    })
 6666                })?
 6667                .await
 6668        })
 6669    }
 6670
 6671    fn request_multiple_lsp_locally<P, R>(
 6672        &mut self,
 6673        buffer: &Entity<Buffer>,
 6674        position: Option<P>,
 6675        request: R,
 6676        cx: &mut Context<Self>,
 6677    ) -> Task<Vec<R::Response>>
 6678    where
 6679        P: ToOffset,
 6680        R: LspCommand + Clone,
 6681        <R::LspRequest as lsp::request::Request>::Result: Send,
 6682        <R::LspRequest as lsp::request::Request>::Params: Send,
 6683    {
 6684        let Some(local) = self.as_local() else {
 6685            return Task::ready(Vec::new());
 6686        };
 6687
 6688        let snapshot = buffer.read(cx).snapshot();
 6689        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 6690
 6691        let server_ids = buffer.update(cx, |buffer, cx| {
 6692            local
 6693                .language_servers_for_buffer(buffer, cx)
 6694                .filter(|(adapter, _)| {
 6695                    scope
 6696                        .as_ref()
 6697                        .map(|scope| scope.language_allowed(&adapter.name))
 6698                        .unwrap_or(true)
 6699                })
 6700                .map(|(_, server)| server.server_id())
 6701                .collect::<Vec<_>>()
 6702        });
 6703
 6704        let mut response_results = server_ids
 6705            .into_iter()
 6706            .map(|server_id| {
 6707                self.request_lsp(
 6708                    buffer.clone(),
 6709                    LanguageServerToQuery::Other(server_id),
 6710                    request.clone(),
 6711                    cx,
 6712                )
 6713            })
 6714            .collect::<FuturesUnordered<_>>();
 6715
 6716        cx.spawn(async move |_, _| {
 6717            let mut responses = Vec::with_capacity(response_results.len());
 6718            while let Some(response_result) = response_results.next().await {
 6719                if let Some(response) = response_result.log_err() {
 6720                    responses.push(response);
 6721                }
 6722            }
 6723            responses
 6724        })
 6725    }
 6726
 6727    async fn handle_lsp_command<T: LspCommand>(
 6728        this: Entity<Self>,
 6729        envelope: TypedEnvelope<T::ProtoRequest>,
 6730        mut cx: AsyncApp,
 6731    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 6732    where
 6733        <T::LspRequest as lsp::request::Request>::Params: Send,
 6734        <T::LspRequest as lsp::request::Request>::Result: Send,
 6735    {
 6736        let sender_id = envelope.original_sender_id().unwrap_or_default();
 6737        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 6738        let buffer_handle = this.update(&mut cx, |this, cx| {
 6739            this.buffer_store.read(cx).get_existing(buffer_id)
 6740        })??;
 6741        let request = T::from_proto(
 6742            envelope.payload,
 6743            this.clone(),
 6744            buffer_handle.clone(),
 6745            cx.clone(),
 6746        )
 6747        .await?;
 6748        let response = this
 6749            .update(&mut cx, |this, cx| {
 6750                this.request_lsp(
 6751                    buffer_handle.clone(),
 6752                    LanguageServerToQuery::FirstCapable,
 6753                    request,
 6754                    cx,
 6755                )
 6756            })?
 6757            .await?;
 6758        this.update(&mut cx, |this, cx| {
 6759            Ok(T::response_to_proto(
 6760                response,
 6761                this,
 6762                sender_id,
 6763                &buffer_handle.read(cx).version(),
 6764                cx,
 6765            ))
 6766        })?
 6767    }
 6768
 6769    async fn handle_multi_lsp_query(
 6770        this: Entity<Self>,
 6771        envelope: TypedEnvelope<proto::MultiLspQuery>,
 6772        mut cx: AsyncApp,
 6773    ) -> Result<proto::MultiLspQueryResponse> {
 6774        let response_from_ssh = this.update(&mut cx, |this, _| {
 6775            let (upstream_client, project_id) = this.upstream_client()?;
 6776            let mut payload = envelope.payload.clone();
 6777            payload.project_id = project_id;
 6778
 6779            Some(upstream_client.request(payload))
 6780        })?;
 6781        if let Some(response_from_ssh) = response_from_ssh {
 6782            return response_from_ssh.await;
 6783        }
 6784
 6785        let sender_id = envelope.original_sender_id().unwrap_or_default();
 6786        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 6787        let version = deserialize_version(&envelope.payload.version);
 6788        let buffer = this.update(&mut cx, |this, cx| {
 6789            this.buffer_store.read(cx).get_existing(buffer_id)
 6790        })??;
 6791        buffer
 6792            .update(&mut cx, |buffer, _| {
 6793                buffer.wait_for_version(version.clone())
 6794            })?
 6795            .await?;
 6796        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 6797        match envelope
 6798            .payload
 6799            .strategy
 6800            .context("invalid request without the strategy")?
 6801        {
 6802            proto::multi_lsp_query::Strategy::All(_) => {
 6803                // currently, there's only one multiple language servers query strategy,
 6804                // so just ensure it's specified correctly
 6805            }
 6806        }
 6807        match envelope.payload.request {
 6808            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 6809                let get_hover =
 6810                    GetHover::from_proto(get_hover, this.clone(), buffer.clone(), cx.clone())
 6811                        .await?;
 6812                let all_hovers = this
 6813                    .update(&mut cx, |this, cx| {
 6814                        this.request_multiple_lsp_locally(
 6815                            &buffer,
 6816                            Some(get_hover.position),
 6817                            get_hover,
 6818                            cx,
 6819                        )
 6820                    })?
 6821                    .await
 6822                    .into_iter()
 6823                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 6824                this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 6825                    responses: all_hovers
 6826                        .map(|hover| proto::LspResponse {
 6827                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 6828                                GetHover::response_to_proto(
 6829                                    Some(hover),
 6830                                    project,
 6831                                    sender_id,
 6832                                    &buffer_version,
 6833                                    cx,
 6834                                ),
 6835                            )),
 6836                        })
 6837                        .collect(),
 6838                })
 6839            }
 6840            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 6841                let get_code_actions = GetCodeActions::from_proto(
 6842                    get_code_actions,
 6843                    this.clone(),
 6844                    buffer.clone(),
 6845                    cx.clone(),
 6846                )
 6847                .await?;
 6848
 6849                let all_actions = this
 6850                    .update(&mut cx, |project, cx| {
 6851                        project.request_multiple_lsp_locally(
 6852                            &buffer,
 6853                            Some(get_code_actions.range.start),
 6854                            get_code_actions,
 6855                            cx,
 6856                        )
 6857                    })?
 6858                    .await
 6859                    .into_iter();
 6860
 6861                this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 6862                    responses: all_actions
 6863                        .map(|code_actions| proto::LspResponse {
 6864                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 6865                                GetCodeActions::response_to_proto(
 6866                                    code_actions,
 6867                                    project,
 6868                                    sender_id,
 6869                                    &buffer_version,
 6870                                    cx,
 6871                                ),
 6872                            )),
 6873                        })
 6874                        .collect(),
 6875                })
 6876            }
 6877            Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
 6878                let get_signature_help = GetSignatureHelp::from_proto(
 6879                    get_signature_help,
 6880                    this.clone(),
 6881                    buffer.clone(),
 6882                    cx.clone(),
 6883                )
 6884                .await?;
 6885
 6886                let all_signatures = this
 6887                    .update(&mut cx, |project, cx| {
 6888                        project.request_multiple_lsp_locally(
 6889                            &buffer,
 6890                            Some(get_signature_help.position),
 6891                            get_signature_help,
 6892                            cx,
 6893                        )
 6894                    })?
 6895                    .await
 6896                    .into_iter();
 6897
 6898                this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 6899                    responses: all_signatures
 6900                        .map(|signature_help| proto::LspResponse {
 6901                            response: Some(
 6902                                proto::lsp_response::Response::GetSignatureHelpResponse(
 6903                                    GetSignatureHelp::response_to_proto(
 6904                                        signature_help,
 6905                                        project,
 6906                                        sender_id,
 6907                                        &buffer_version,
 6908                                        cx,
 6909                                    ),
 6910                                ),
 6911                            ),
 6912                        })
 6913                        .collect(),
 6914                })
 6915            }
 6916            Some(proto::multi_lsp_query::Request::GetCodeLens(get_code_lens)) => {
 6917                let get_code_lens = GetCodeLens::from_proto(
 6918                    get_code_lens,
 6919                    this.clone(),
 6920                    buffer.clone(),
 6921                    cx.clone(),
 6922                )
 6923                .await?;
 6924
 6925                let code_lens_actions = this
 6926                    .update(&mut cx, |project, cx| {
 6927                        project.request_multiple_lsp_locally(
 6928                            &buffer,
 6929                            None::<usize>,
 6930                            get_code_lens,
 6931                            cx,
 6932                        )
 6933                    })?
 6934                    .await
 6935                    .into_iter();
 6936
 6937                this.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 6938                    responses: code_lens_actions
 6939                        .map(|actions| proto::LspResponse {
 6940                            response: Some(proto::lsp_response::Response::GetCodeLensResponse(
 6941                                GetCodeLens::response_to_proto(
 6942                                    actions,
 6943                                    project,
 6944                                    sender_id,
 6945                                    &buffer_version,
 6946                                    cx,
 6947                                ),
 6948                            )),
 6949                        })
 6950                        .collect(),
 6951                })
 6952            }
 6953            None => anyhow::bail!("empty multi lsp query request"),
 6954        }
 6955    }
 6956
 6957    async fn handle_apply_code_action(
 6958        this: Entity<Self>,
 6959        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 6960        mut cx: AsyncApp,
 6961    ) -> Result<proto::ApplyCodeActionResponse> {
 6962        let sender_id = envelope.original_sender_id().unwrap_or_default();
 6963        let action = Self::deserialize_code_action(
 6964            envelope
 6965                .payload
 6966                .action
 6967                .ok_or_else(|| anyhow!("invalid action"))?,
 6968        )?;
 6969        let apply_code_action = this.update(&mut cx, |this, cx| {
 6970            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 6971            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 6972            anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
 6973        })??;
 6974
 6975        let project_transaction = apply_code_action.await?;
 6976        let project_transaction = this.update(&mut cx, |this, cx| {
 6977            this.buffer_store.update(cx, |buffer_store, cx| {
 6978                buffer_store.serialize_project_transaction_for_peer(
 6979                    project_transaction,
 6980                    sender_id,
 6981                    cx,
 6982                )
 6983            })
 6984        })?;
 6985        Ok(proto::ApplyCodeActionResponse {
 6986            transaction: Some(project_transaction),
 6987        })
 6988    }
 6989
 6990    async fn handle_register_buffer_with_language_servers(
 6991        this: Entity<Self>,
 6992        envelope: TypedEnvelope<proto::RegisterBufferWithLanguageServers>,
 6993        mut cx: AsyncApp,
 6994    ) -> Result<proto::Ack> {
 6995        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 6996        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
 6997        this.update(&mut cx, |this, cx| {
 6998            if let Some((upstream_client, upstream_project_id)) = this.upstream_client() {
 6999                return upstream_client.send(proto::RegisterBufferWithLanguageServers {
 7000                    project_id: upstream_project_id,
 7001                    buffer_id: buffer_id.to_proto(),
 7002                });
 7003            }
 7004
 7005            let Some(buffer) = this.buffer_store().read(cx).get(buffer_id) else {
 7006                anyhow::bail!("buffer is not open");
 7007            };
 7008
 7009            let handle = this.register_buffer_with_language_servers(&buffer, false, cx);
 7010            this.buffer_store().update(cx, |buffer_store, _| {
 7011                buffer_store.register_shared_lsp_handle(peer_id, buffer_id, handle);
 7012            });
 7013
 7014            Ok(())
 7015        })??;
 7016        Ok(proto::Ack {})
 7017    }
 7018
 7019    async fn handle_language_server_id_for_name(
 7020        lsp_store: Entity<Self>,
 7021        envelope: TypedEnvelope<proto::LanguageServerIdForName>,
 7022        mut cx: AsyncApp,
 7023    ) -> Result<proto::LanguageServerIdForNameResponse> {
 7024        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7025        let name = &envelope.payload.name;
 7026        lsp_store
 7027            .update(&mut cx, |lsp_store, cx| {
 7028                let buffer = lsp_store.buffer_store.read(cx).get_existing(buffer_id)?;
 7029                let server_id = buffer.update(cx, |buffer, cx| {
 7030                    lsp_store
 7031                        .language_servers_for_local_buffer(buffer, cx)
 7032                        .find_map(|(adapter, server)| {
 7033                            if adapter.name.0.as_ref() == name {
 7034                                Some(server.server_id())
 7035                            } else {
 7036                                None
 7037                            }
 7038                        })
 7039                });
 7040                Ok(server_id)
 7041            })?
 7042            .map(|server_id| proto::LanguageServerIdForNameResponse {
 7043                server_id: server_id.map(|id| id.to_proto()),
 7044            })
 7045    }
 7046
 7047    async fn handle_rename_project_entry(
 7048        this: Entity<Self>,
 7049        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 7050        mut cx: AsyncApp,
 7051    ) -> Result<proto::ProjectEntryResponse> {
 7052        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 7053        let (worktree_id, worktree, old_path, is_dir) = this
 7054            .update(&mut cx, |this, cx| {
 7055                this.worktree_store
 7056                    .read(cx)
 7057                    .worktree_and_entry_for_id(entry_id, cx)
 7058                    .map(|(worktree, entry)| {
 7059                        (
 7060                            worktree.read(cx).id(),
 7061                            worktree,
 7062                            entry.path.clone(),
 7063                            entry.is_dir(),
 7064                        )
 7065                    })
 7066            })?
 7067            .ok_or_else(|| anyhow!("worktree not found"))?;
 7068        let (old_abs_path, new_abs_path) = {
 7069            let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
 7070            let new_path = PathBuf::from_proto(envelope.payload.new_path.clone());
 7071            (root_path.join(&old_path), root_path.join(&new_path))
 7072        };
 7073
 7074        Self::will_rename_entry(
 7075            this.downgrade(),
 7076            worktree_id,
 7077            &old_abs_path,
 7078            &new_abs_path,
 7079            is_dir,
 7080            cx.clone(),
 7081        )
 7082        .await;
 7083        let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
 7084        this.update(&mut cx, |this, _| {
 7085            this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
 7086        })
 7087        .ok();
 7088        response
 7089    }
 7090
 7091    async fn handle_update_diagnostic_summary(
 7092        this: Entity<Self>,
 7093        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 7094        mut cx: AsyncApp,
 7095    ) -> Result<()> {
 7096        this.update(&mut cx, |this, cx| {
 7097            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 7098            if let Some(message) = envelope.payload.summary {
 7099                let project_path = ProjectPath {
 7100                    worktree_id,
 7101                    path: Arc::<Path>::from_proto(message.path),
 7102                };
 7103                let path = project_path.path.clone();
 7104                let server_id = LanguageServerId(message.language_server_id as usize);
 7105                let summary = DiagnosticSummary {
 7106                    error_count: message.error_count as usize,
 7107                    warning_count: message.warning_count as usize,
 7108                };
 7109
 7110                if summary.is_empty() {
 7111                    if let Some(worktree_summaries) =
 7112                        this.diagnostic_summaries.get_mut(&worktree_id)
 7113                    {
 7114                        if let Some(summaries) = worktree_summaries.get_mut(&path) {
 7115                            summaries.remove(&server_id);
 7116                            if summaries.is_empty() {
 7117                                worktree_summaries.remove(&path);
 7118                            }
 7119                        }
 7120                    }
 7121                } else {
 7122                    this.diagnostic_summaries
 7123                        .entry(worktree_id)
 7124                        .or_default()
 7125                        .entry(path)
 7126                        .or_default()
 7127                        .insert(server_id, summary);
 7128                }
 7129                if let Some((downstream_client, project_id)) = &this.downstream_client {
 7130                    downstream_client
 7131                        .send(proto::UpdateDiagnosticSummary {
 7132                            project_id: *project_id,
 7133                            worktree_id: worktree_id.to_proto(),
 7134                            summary: Some(proto::DiagnosticSummary {
 7135                                path: project_path.path.as_ref().to_proto(),
 7136                                language_server_id: server_id.0 as u64,
 7137                                error_count: summary.error_count as u32,
 7138                                warning_count: summary.warning_count as u32,
 7139                            }),
 7140                        })
 7141                        .log_err();
 7142                }
 7143                cx.emit(LspStoreEvent::DiagnosticsUpdated {
 7144                    language_server_id: LanguageServerId(message.language_server_id as usize),
 7145                    path: project_path,
 7146                });
 7147            }
 7148            Ok(())
 7149        })?
 7150    }
 7151
 7152    async fn handle_start_language_server(
 7153        this: Entity<Self>,
 7154        envelope: TypedEnvelope<proto::StartLanguageServer>,
 7155        mut cx: AsyncApp,
 7156    ) -> Result<()> {
 7157        let server = envelope
 7158            .payload
 7159            .server
 7160            .ok_or_else(|| anyhow!("invalid server"))?;
 7161
 7162        this.update(&mut cx, |this, cx| {
 7163            let server_id = LanguageServerId(server.id as usize);
 7164            this.language_server_statuses.insert(
 7165                server_id,
 7166                LanguageServerStatus {
 7167                    name: server.name.clone(),
 7168                    pending_work: Default::default(),
 7169                    has_pending_diagnostic_updates: false,
 7170                    progress_tokens: Default::default(),
 7171                },
 7172            );
 7173            cx.emit(LspStoreEvent::LanguageServerAdded(
 7174                server_id,
 7175                LanguageServerName(server.name.into()),
 7176                server.worktree_id.map(WorktreeId::from_proto),
 7177            ));
 7178            cx.notify();
 7179        })?;
 7180        Ok(())
 7181    }
 7182
 7183    async fn handle_update_language_server(
 7184        this: Entity<Self>,
 7185        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 7186        mut cx: AsyncApp,
 7187    ) -> Result<()> {
 7188        this.update(&mut cx, |this, cx| {
 7189            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 7190
 7191            match envelope
 7192                .payload
 7193                .variant
 7194                .ok_or_else(|| anyhow!("invalid variant"))?
 7195            {
 7196                proto::update_language_server::Variant::WorkStart(payload) => {
 7197                    this.on_lsp_work_start(
 7198                        language_server_id,
 7199                        payload.token,
 7200                        LanguageServerProgress {
 7201                            title: payload.title,
 7202                            is_disk_based_diagnostics_progress: false,
 7203                            is_cancellable: payload.is_cancellable.unwrap_or(false),
 7204                            message: payload.message,
 7205                            percentage: payload.percentage.map(|p| p as usize),
 7206                            last_update_at: cx.background_executor().now(),
 7207                        },
 7208                        cx,
 7209                    );
 7210                }
 7211
 7212                proto::update_language_server::Variant::WorkProgress(payload) => {
 7213                    this.on_lsp_work_progress(
 7214                        language_server_id,
 7215                        payload.token,
 7216                        LanguageServerProgress {
 7217                            title: None,
 7218                            is_disk_based_diagnostics_progress: false,
 7219                            is_cancellable: payload.is_cancellable.unwrap_or(false),
 7220                            message: payload.message,
 7221                            percentage: payload.percentage.map(|p| p as usize),
 7222                            last_update_at: cx.background_executor().now(),
 7223                        },
 7224                        cx,
 7225                    );
 7226                }
 7227
 7228                proto::update_language_server::Variant::WorkEnd(payload) => {
 7229                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 7230                }
 7231
 7232                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 7233                    this.disk_based_diagnostics_started(language_server_id, cx);
 7234                }
 7235
 7236                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 7237                    this.disk_based_diagnostics_finished(language_server_id, cx)
 7238                }
 7239            }
 7240
 7241            Ok(())
 7242        })?
 7243    }
 7244
 7245    async fn handle_language_server_log(
 7246        this: Entity<Self>,
 7247        envelope: TypedEnvelope<proto::LanguageServerLog>,
 7248        mut cx: AsyncApp,
 7249    ) -> Result<()> {
 7250        let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 7251        let log_type = envelope
 7252            .payload
 7253            .log_type
 7254            .map(LanguageServerLogType::from_proto)
 7255            .context("invalid language server log type")?;
 7256
 7257        let message = envelope.payload.message;
 7258
 7259        this.update(&mut cx, |_, cx| {
 7260            cx.emit(LspStoreEvent::LanguageServerLog(
 7261                language_server_id,
 7262                log_type,
 7263                message,
 7264            ));
 7265        })
 7266    }
 7267
 7268    pub fn disk_based_diagnostics_started(
 7269        &mut self,
 7270        language_server_id: LanguageServerId,
 7271        cx: &mut Context<Self>,
 7272    ) {
 7273        if let Some(language_server_status) =
 7274            self.language_server_statuses.get_mut(&language_server_id)
 7275        {
 7276            language_server_status.has_pending_diagnostic_updates = true;
 7277        }
 7278
 7279        cx.emit(LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id });
 7280        cx.emit(LspStoreEvent::LanguageServerUpdate {
 7281            language_server_id,
 7282            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 7283                Default::default(),
 7284            ),
 7285        })
 7286    }
 7287
 7288    pub fn disk_based_diagnostics_finished(
 7289        &mut self,
 7290        language_server_id: LanguageServerId,
 7291        cx: &mut Context<Self>,
 7292    ) {
 7293        if let Some(language_server_status) =
 7294            self.language_server_statuses.get_mut(&language_server_id)
 7295        {
 7296            language_server_status.has_pending_diagnostic_updates = false;
 7297        }
 7298
 7299        cx.emit(LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id });
 7300        cx.emit(LspStoreEvent::LanguageServerUpdate {
 7301            language_server_id,
 7302            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 7303                Default::default(),
 7304            ),
 7305        })
 7306    }
 7307
 7308    // After saving a buffer using a language server that doesn't provide a disk-based progress token,
 7309    // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
 7310    // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
 7311    // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
 7312    // the language server might take some time to publish diagnostics.
 7313    fn simulate_disk_based_diagnostics_events_if_needed(
 7314        &mut self,
 7315        language_server_id: LanguageServerId,
 7316        cx: &mut Context<Self>,
 7317    ) {
 7318        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
 7319
 7320        let Some(LanguageServerState::Running {
 7321            simulate_disk_based_diagnostics_completion,
 7322            adapter,
 7323            ..
 7324        }) = self
 7325            .as_local_mut()
 7326            .and_then(|local_store| local_store.language_servers.get_mut(&language_server_id))
 7327        else {
 7328            return;
 7329        };
 7330
 7331        if adapter.disk_based_diagnostics_progress_token.is_some() {
 7332            return;
 7333        }
 7334
 7335        let prev_task =
 7336            simulate_disk_based_diagnostics_completion.replace(cx.spawn(async move |this, cx| {
 7337                cx.background_executor()
 7338                    .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
 7339                    .await;
 7340
 7341                this.update(cx, |this, cx| {
 7342                    this.disk_based_diagnostics_finished(language_server_id, cx);
 7343
 7344                    if let Some(LanguageServerState::Running {
 7345                        simulate_disk_based_diagnostics_completion,
 7346                        ..
 7347                    }) = this.as_local_mut().and_then(|local_store| {
 7348                        local_store.language_servers.get_mut(&language_server_id)
 7349                    }) {
 7350                        *simulate_disk_based_diagnostics_completion = None;
 7351                    }
 7352                })
 7353                .ok();
 7354            }));
 7355
 7356        if prev_task.is_none() {
 7357            self.disk_based_diagnostics_started(language_server_id, cx);
 7358        }
 7359    }
 7360
 7361    pub fn language_server_statuses(
 7362        &self,
 7363    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
 7364        self.language_server_statuses
 7365            .iter()
 7366            .map(|(key, value)| (*key, value))
 7367    }
 7368
 7369    pub(super) fn did_rename_entry(
 7370        &self,
 7371        worktree_id: WorktreeId,
 7372        old_path: &Path,
 7373        new_path: &Path,
 7374        is_dir: bool,
 7375    ) {
 7376        maybe!({
 7377            let local_store = self.as_local()?;
 7378
 7379            let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from)?;
 7380            let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from)?;
 7381
 7382            for language_server in local_store.language_servers_for_worktree(worktree_id) {
 7383                let Some(filter) = local_store
 7384                    .language_server_paths_watched_for_rename
 7385                    .get(&language_server.server_id())
 7386                else {
 7387                    continue;
 7388                };
 7389
 7390                if filter.should_send_did_rename(&old_uri, is_dir) {
 7391                    language_server
 7392                        .notify::<DidRenameFiles>(&RenameFilesParams {
 7393                            files: vec![FileRename {
 7394                                old_uri: old_uri.clone(),
 7395                                new_uri: new_uri.clone(),
 7396                            }],
 7397                        })
 7398                        .log_err();
 7399                }
 7400            }
 7401            Some(())
 7402        });
 7403    }
 7404
 7405    pub(super) fn will_rename_entry(
 7406        this: WeakEntity<Self>,
 7407        worktree_id: WorktreeId,
 7408        old_path: &Path,
 7409        new_path: &Path,
 7410        is_dir: bool,
 7411        cx: AsyncApp,
 7412    ) -> Task<()> {
 7413        let old_uri = lsp::Url::from_file_path(old_path).ok().map(String::from);
 7414        let new_uri = lsp::Url::from_file_path(new_path).ok().map(String::from);
 7415        cx.spawn(async move |cx| {
 7416            let mut tasks = vec![];
 7417            this.update(cx, |this, cx| {
 7418                let local_store = this.as_local()?;
 7419                let old_uri = old_uri?;
 7420                let new_uri = new_uri?;
 7421                for language_server in local_store.language_servers_for_worktree(worktree_id) {
 7422                    let Some(filter) = local_store
 7423                        .language_server_paths_watched_for_rename
 7424                        .get(&language_server.server_id())
 7425                    else {
 7426                        continue;
 7427                    };
 7428                    let Some(adapter) =
 7429                        this.language_server_adapter_for_id(language_server.server_id())
 7430                    else {
 7431                        continue;
 7432                    };
 7433                    if filter.should_send_will_rename(&old_uri, is_dir) {
 7434                        let apply_edit = cx.spawn({
 7435                            let old_uri = old_uri.clone();
 7436                            let new_uri = new_uri.clone();
 7437                            let language_server = language_server.clone();
 7438                            async move |this, cx| {
 7439                                let edit = language_server
 7440                                    .request::<WillRenameFiles>(RenameFilesParams {
 7441                                        files: vec![FileRename { old_uri, new_uri }],
 7442                                    })
 7443                                    .log_err()
 7444                                    .await
 7445                                    .flatten()?;
 7446
 7447                                LocalLspStore::deserialize_workspace_edit(
 7448                                    this.upgrade()?,
 7449                                    edit,
 7450                                    false,
 7451                                    adapter.clone(),
 7452                                    language_server.clone(),
 7453                                    cx,
 7454                                )
 7455                                .await
 7456                                .ok();
 7457                                Some(())
 7458                            }
 7459                        });
 7460                        tasks.push(apply_edit);
 7461                    }
 7462                }
 7463                Some(())
 7464            })
 7465            .ok()
 7466            .flatten();
 7467            for task in tasks {
 7468                // Await on tasks sequentially so that the order of application of edits is deterministic
 7469                // (at least with regards to the order of registration of language servers)
 7470                task.await;
 7471            }
 7472        })
 7473    }
 7474
 7475    fn lsp_notify_abs_paths_changed(
 7476        &mut self,
 7477        server_id: LanguageServerId,
 7478        changes: Vec<PathEvent>,
 7479    ) {
 7480        maybe!({
 7481            let server = self.language_server_for_id(server_id)?;
 7482            let changes = changes
 7483                .into_iter()
 7484                .filter_map(|event| {
 7485                    let typ = match event.kind? {
 7486                        PathEventKind::Created => lsp::FileChangeType::CREATED,
 7487                        PathEventKind::Removed => lsp::FileChangeType::DELETED,
 7488                        PathEventKind::Changed => lsp::FileChangeType::CHANGED,
 7489                    };
 7490                    Some(lsp::FileEvent {
 7491                        uri: lsp::Url::from_file_path(&event.path).ok()?,
 7492                        typ,
 7493                    })
 7494                })
 7495                .collect::<Vec<_>>();
 7496            if !changes.is_empty() {
 7497                server
 7498                    .notify::<lsp::notification::DidChangeWatchedFiles>(
 7499                        &lsp::DidChangeWatchedFilesParams { changes },
 7500                    )
 7501                    .log_err();
 7502            }
 7503            Some(())
 7504        });
 7505    }
 7506
 7507    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
 7508        let local_lsp_store = self.as_local()?;
 7509        if let Some(LanguageServerState::Running { server, .. }) =
 7510            local_lsp_store.language_servers.get(&id)
 7511        {
 7512            Some(server.clone())
 7513        } else if let Some((_, server)) = local_lsp_store.supplementary_language_servers.get(&id) {
 7514            Some(Arc::clone(server))
 7515        } else {
 7516            None
 7517        }
 7518    }
 7519
 7520    fn on_lsp_progress(
 7521        &mut self,
 7522        progress: lsp::ProgressParams,
 7523        language_server_id: LanguageServerId,
 7524        disk_based_diagnostics_progress_token: Option<String>,
 7525        cx: &mut Context<Self>,
 7526    ) {
 7527        let token = match progress.token {
 7528            lsp::NumberOrString::String(token) => token,
 7529            lsp::NumberOrString::Number(token) => {
 7530                log::info!("skipping numeric progress token {}", token);
 7531                return;
 7532            }
 7533        };
 7534
 7535        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 7536        let language_server_status =
 7537            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 7538                status
 7539            } else {
 7540                return;
 7541            };
 7542
 7543        if !language_server_status.progress_tokens.contains(&token) {
 7544            return;
 7545        }
 7546
 7547        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 7548            .as_ref()
 7549            .map_or(false, |disk_based_token| {
 7550                token.starts_with(disk_based_token)
 7551            });
 7552
 7553        match progress {
 7554            lsp::WorkDoneProgress::Begin(report) => {
 7555                if is_disk_based_diagnostics_progress {
 7556                    self.disk_based_diagnostics_started(language_server_id, cx);
 7557                }
 7558                self.on_lsp_work_start(
 7559                    language_server_id,
 7560                    token.clone(),
 7561                    LanguageServerProgress {
 7562                        title: Some(report.title),
 7563                        is_disk_based_diagnostics_progress,
 7564                        is_cancellable: report.cancellable.unwrap_or(false),
 7565                        message: report.message.clone(),
 7566                        percentage: report.percentage.map(|p| p as usize),
 7567                        last_update_at: cx.background_executor().now(),
 7568                    },
 7569                    cx,
 7570                );
 7571            }
 7572            lsp::WorkDoneProgress::Report(report) => self.on_lsp_work_progress(
 7573                language_server_id,
 7574                token,
 7575                LanguageServerProgress {
 7576                    title: None,
 7577                    is_disk_based_diagnostics_progress,
 7578                    is_cancellable: report.cancellable.unwrap_or(false),
 7579                    message: report.message,
 7580                    percentage: report.percentage.map(|p| p as usize),
 7581                    last_update_at: cx.background_executor().now(),
 7582                },
 7583                cx,
 7584            ),
 7585            lsp::WorkDoneProgress::End(_) => {
 7586                language_server_status.progress_tokens.remove(&token);
 7587                self.on_lsp_work_end(language_server_id, token.clone(), cx);
 7588                if is_disk_based_diagnostics_progress {
 7589                    self.disk_based_diagnostics_finished(language_server_id, cx);
 7590                }
 7591            }
 7592        }
 7593    }
 7594
 7595    fn on_lsp_work_start(
 7596        &mut self,
 7597        language_server_id: LanguageServerId,
 7598        token: String,
 7599        progress: LanguageServerProgress,
 7600        cx: &mut Context<Self>,
 7601    ) {
 7602        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 7603            status.pending_work.insert(token.clone(), progress.clone());
 7604            cx.notify();
 7605        }
 7606        cx.emit(LspStoreEvent::LanguageServerUpdate {
 7607            language_server_id,
 7608            message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 7609                token,
 7610                title: progress.title,
 7611                message: progress.message,
 7612                percentage: progress.percentage.map(|p| p as u32),
 7613                is_cancellable: Some(progress.is_cancellable),
 7614            }),
 7615        })
 7616    }
 7617
 7618    fn on_lsp_work_progress(
 7619        &mut self,
 7620        language_server_id: LanguageServerId,
 7621        token: String,
 7622        progress: LanguageServerProgress,
 7623        cx: &mut Context<Self>,
 7624    ) {
 7625        let mut did_update = false;
 7626        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 7627            match status.pending_work.entry(token.clone()) {
 7628                btree_map::Entry::Vacant(entry) => {
 7629                    entry.insert(progress.clone());
 7630                    did_update = true;
 7631                }
 7632                btree_map::Entry::Occupied(mut entry) => {
 7633                    let entry = entry.get_mut();
 7634                    if (progress.last_update_at - entry.last_update_at)
 7635                        >= SERVER_PROGRESS_THROTTLE_TIMEOUT
 7636                    {
 7637                        entry.last_update_at = progress.last_update_at;
 7638                        if progress.message.is_some() {
 7639                            entry.message = progress.message.clone();
 7640                        }
 7641                        if progress.percentage.is_some() {
 7642                            entry.percentage = progress.percentage;
 7643                        }
 7644                        if progress.is_cancellable != entry.is_cancellable {
 7645                            entry.is_cancellable = progress.is_cancellable;
 7646                        }
 7647                        did_update = true;
 7648                    }
 7649                }
 7650            }
 7651        }
 7652
 7653        if did_update {
 7654            cx.emit(LspStoreEvent::LanguageServerUpdate {
 7655                language_server_id,
 7656                message: proto::update_language_server::Variant::WorkProgress(
 7657                    proto::LspWorkProgress {
 7658                        token,
 7659                        message: progress.message,
 7660                        percentage: progress.percentage.map(|p| p as u32),
 7661                        is_cancellable: Some(progress.is_cancellable),
 7662                    },
 7663                ),
 7664            })
 7665        }
 7666    }
 7667
 7668    fn on_lsp_work_end(
 7669        &mut self,
 7670        language_server_id: LanguageServerId,
 7671        token: String,
 7672        cx: &mut Context<Self>,
 7673    ) {
 7674        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 7675            if let Some(work) = status.pending_work.remove(&token) {
 7676                if !work.is_disk_based_diagnostics_progress {
 7677                    cx.emit(LspStoreEvent::RefreshInlayHints);
 7678                }
 7679            }
 7680            cx.notify();
 7681        }
 7682
 7683        cx.emit(LspStoreEvent::LanguageServerUpdate {
 7684            language_server_id,
 7685            message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd { token }),
 7686        })
 7687    }
 7688
 7689    pub async fn handle_resolve_completion_documentation(
 7690        this: Entity<Self>,
 7691        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 7692        mut cx: AsyncApp,
 7693    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 7694        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 7695
 7696        let completion = this
 7697            .read_with(&cx, |this, cx| {
 7698                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 7699                let Some(server) = this.language_server_for_id(id) else {
 7700                    return Err(anyhow!("No language server {id}"));
 7701                };
 7702
 7703                Ok(cx.background_spawn(async move {
 7704                    let can_resolve = server
 7705                        .capabilities()
 7706                        .completion_provider
 7707                        .as_ref()
 7708                        .and_then(|options| options.resolve_provider)
 7709                        .unwrap_or(false);
 7710                    if can_resolve {
 7711                        server
 7712                            .request::<lsp::request::ResolveCompletionItem>(lsp_completion)
 7713                            .await
 7714                    } else {
 7715                        anyhow::Ok(lsp_completion)
 7716                    }
 7717                }))
 7718            })??
 7719            .await?;
 7720
 7721        let mut documentation_is_markdown = false;
 7722        let lsp_completion = serde_json::to_string(&completion)?.into_bytes();
 7723        let documentation = match completion.documentation {
 7724            Some(lsp::Documentation::String(text)) => text,
 7725
 7726            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 7727                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 7728                value
 7729            }
 7730
 7731            _ => String::new(),
 7732        };
 7733
 7734        // If we have a new buffer_id, that means we're talking to a new client
 7735        // and want to check for new text_edits in the completion too.
 7736        let mut old_replace_start = None;
 7737        let mut old_replace_end = None;
 7738        let mut old_insert_start = None;
 7739        let mut old_insert_end = None;
 7740        let mut new_text = String::default();
 7741        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 7742            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 7743                let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 7744                anyhow::Ok(buffer.read(cx).snapshot())
 7745            })??;
 7746
 7747            if let Some(text_edit) = completion.text_edit.as_ref() {
 7748                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 7749
 7750                if let Some(mut edit) = edit {
 7751                    LineEnding::normalize(&mut edit.new_text);
 7752
 7753                    new_text = edit.new_text;
 7754                    old_replace_start = Some(serialize_anchor(&edit.replace_range.start));
 7755                    old_replace_end = Some(serialize_anchor(&edit.replace_range.end));
 7756                    if let Some(insert_range) = edit.insert_range {
 7757                        old_insert_start = Some(serialize_anchor(&insert_range.start));
 7758                        old_insert_end = Some(serialize_anchor(&insert_range.end));
 7759                    }
 7760                }
 7761            }
 7762        }
 7763
 7764        Ok(proto::ResolveCompletionDocumentationResponse {
 7765            documentation,
 7766            documentation_is_markdown,
 7767            old_replace_start,
 7768            old_replace_end,
 7769            new_text,
 7770            lsp_completion,
 7771            old_insert_start,
 7772            old_insert_end,
 7773        })
 7774    }
 7775
 7776    async fn handle_on_type_formatting(
 7777        this: Entity<Self>,
 7778        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 7779        mut cx: AsyncApp,
 7780    ) -> Result<proto::OnTypeFormattingResponse> {
 7781        let on_type_formatting = this.update(&mut cx, |this, cx| {
 7782            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7783            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 7784            let position = envelope
 7785                .payload
 7786                .position
 7787                .and_then(deserialize_anchor)
 7788                .ok_or_else(|| anyhow!("invalid position"))?;
 7789            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 7790                buffer,
 7791                position,
 7792                envelope.payload.trigger.clone(),
 7793                cx,
 7794            ))
 7795        })??;
 7796
 7797        let transaction = on_type_formatting
 7798            .await?
 7799            .as_ref()
 7800            .map(language::proto::serialize_transaction);
 7801        Ok(proto::OnTypeFormattingResponse { transaction })
 7802    }
 7803
 7804    async fn handle_refresh_inlay_hints(
 7805        this: Entity<Self>,
 7806        _: TypedEnvelope<proto::RefreshInlayHints>,
 7807        mut cx: AsyncApp,
 7808    ) -> Result<proto::Ack> {
 7809        this.update(&mut cx, |_, cx| {
 7810            cx.emit(LspStoreEvent::RefreshInlayHints);
 7811        })?;
 7812        Ok(proto::Ack {})
 7813    }
 7814
 7815    async fn handle_inlay_hints(
 7816        this: Entity<Self>,
 7817        envelope: TypedEnvelope<proto::InlayHints>,
 7818        mut cx: AsyncApp,
 7819    ) -> Result<proto::InlayHintsResponse> {
 7820        let sender_id = envelope.original_sender_id().unwrap_or_default();
 7821        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7822        let buffer = this.update(&mut cx, |this, cx| {
 7823            this.buffer_store.read(cx).get_existing(buffer_id)
 7824        })??;
 7825        buffer
 7826            .update(&mut cx, |buffer, _| {
 7827                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 7828            })?
 7829            .await
 7830            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 7831
 7832        let start = envelope
 7833            .payload
 7834            .start
 7835            .and_then(deserialize_anchor)
 7836            .context("missing range start")?;
 7837        let end = envelope
 7838            .payload
 7839            .end
 7840            .and_then(deserialize_anchor)
 7841            .context("missing range end")?;
 7842        let buffer_hints = this
 7843            .update(&mut cx, |lsp_store, cx| {
 7844                lsp_store.inlay_hints(buffer.clone(), start..end, cx)
 7845            })?
 7846            .await
 7847            .context("inlay hints fetch")?;
 7848
 7849        this.update(&mut cx, |project, cx| {
 7850            InlayHints::response_to_proto(
 7851                buffer_hints,
 7852                project,
 7853                sender_id,
 7854                &buffer.read(cx).version(),
 7855                cx,
 7856            )
 7857        })
 7858    }
 7859
 7860    async fn handle_resolve_inlay_hint(
 7861        this: Entity<Self>,
 7862        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 7863        mut cx: AsyncApp,
 7864    ) -> Result<proto::ResolveInlayHintResponse> {
 7865        let proto_hint = envelope
 7866            .payload
 7867            .hint
 7868            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 7869        let hint = InlayHints::proto_to_project_hint(proto_hint)
 7870            .context("resolved proto inlay hint conversion")?;
 7871        let buffer = this.update(&mut cx, |this, cx| {
 7872            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7873            this.buffer_store.read(cx).get_existing(buffer_id)
 7874        })??;
 7875        let response_hint = this
 7876            .update(&mut cx, |this, cx| {
 7877                this.resolve_inlay_hint(
 7878                    hint,
 7879                    buffer,
 7880                    LanguageServerId(envelope.payload.language_server_id as usize),
 7881                    cx,
 7882                )
 7883            })?
 7884            .await
 7885            .context("inlay hints fetch")?;
 7886        Ok(proto::ResolveInlayHintResponse {
 7887            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 7888        })
 7889    }
 7890
 7891    async fn handle_refresh_code_lens(
 7892        this: Entity<Self>,
 7893        _: TypedEnvelope<proto::RefreshCodeLens>,
 7894        mut cx: AsyncApp,
 7895    ) -> Result<proto::Ack> {
 7896        this.update(&mut cx, |_, cx| {
 7897            cx.emit(LspStoreEvent::RefreshCodeLens);
 7898        })?;
 7899        Ok(proto::Ack {})
 7900    }
 7901
 7902    async fn handle_open_buffer_for_symbol(
 7903        this: Entity<Self>,
 7904        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 7905        mut cx: AsyncApp,
 7906    ) -> Result<proto::OpenBufferForSymbolResponse> {
 7907        let peer_id = envelope.original_sender_id().unwrap_or_default();
 7908        let symbol = envelope
 7909            .payload
 7910            .symbol
 7911            .ok_or_else(|| anyhow!("invalid symbol"))?;
 7912        let symbol = Self::deserialize_symbol(symbol)?;
 7913        let symbol = this.update(&mut cx, |this, _| {
 7914            let signature = this.symbol_signature(&symbol.path);
 7915            if signature == symbol.signature {
 7916                Ok(symbol)
 7917            } else {
 7918                Err(anyhow!("invalid symbol signature"))
 7919            }
 7920        })??;
 7921        let buffer = this
 7922            .update(&mut cx, |this, cx| {
 7923                this.open_buffer_for_symbol(
 7924                    &Symbol {
 7925                        language_server_name: symbol.language_server_name,
 7926                        source_worktree_id: symbol.source_worktree_id,
 7927                        source_language_server_id: symbol.source_language_server_id,
 7928                        path: symbol.path,
 7929                        name: symbol.name,
 7930                        kind: symbol.kind,
 7931                        range: symbol.range,
 7932                        signature: symbol.signature,
 7933                        label: CodeLabel {
 7934                            text: Default::default(),
 7935                            runs: Default::default(),
 7936                            filter_range: Default::default(),
 7937                        },
 7938                    },
 7939                    cx,
 7940                )
 7941            })?
 7942            .await?;
 7943
 7944        this.update(&mut cx, |this, cx| {
 7945            let is_private = buffer
 7946                .read(cx)
 7947                .file()
 7948                .map(|f| f.is_private())
 7949                .unwrap_or_default();
 7950            if is_private {
 7951                Err(anyhow!(rpc::ErrorCode::UnsharedItem))
 7952            } else {
 7953                this.buffer_store
 7954                    .update(cx, |buffer_store, cx| {
 7955                        buffer_store.create_buffer_for_peer(&buffer, peer_id, cx)
 7956                    })
 7957                    .detach_and_log_err(cx);
 7958                let buffer_id = buffer.read(cx).remote_id().to_proto();
 7959                Ok(proto::OpenBufferForSymbolResponse { buffer_id })
 7960            }
 7961        })?
 7962    }
 7963
 7964    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 7965        let mut hasher = Sha256::new();
 7966        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 7967        hasher.update(project_path.path.to_string_lossy().as_bytes());
 7968        hasher.update(self.nonce.to_be_bytes());
 7969        hasher.finalize().as_slice().try_into().unwrap()
 7970    }
 7971
 7972    pub async fn handle_get_project_symbols(
 7973        this: Entity<Self>,
 7974        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 7975        mut cx: AsyncApp,
 7976    ) -> Result<proto::GetProjectSymbolsResponse> {
 7977        let symbols = this
 7978            .update(&mut cx, |this, cx| {
 7979                this.symbols(&envelope.payload.query, cx)
 7980            })?
 7981            .await?;
 7982
 7983        Ok(proto::GetProjectSymbolsResponse {
 7984            symbols: symbols.iter().map(Self::serialize_symbol).collect(),
 7985        })
 7986    }
 7987
 7988    pub async fn handle_restart_language_servers(
 7989        this: Entity<Self>,
 7990        envelope: TypedEnvelope<proto::RestartLanguageServers>,
 7991        mut cx: AsyncApp,
 7992    ) -> Result<proto::Ack> {
 7993        this.update(&mut cx, |this, cx| {
 7994            let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
 7995            this.restart_language_servers_for_buffers(buffers, cx);
 7996        })?;
 7997
 7998        Ok(proto::Ack {})
 7999    }
 8000
 8001    pub async fn handle_stop_language_servers(
 8002        this: Entity<Self>,
 8003        envelope: TypedEnvelope<proto::StopLanguageServers>,
 8004        mut cx: AsyncApp,
 8005    ) -> Result<proto::Ack> {
 8006        this.update(&mut cx, |this, cx| {
 8007            let buffers = this.buffer_ids_to_buffers(envelope.payload.buffer_ids.into_iter(), cx);
 8008            this.stop_language_servers_for_buffers(buffers, cx);
 8009        })?;
 8010
 8011        Ok(proto::Ack {})
 8012    }
 8013
 8014    pub async fn handle_cancel_language_server_work(
 8015        this: Entity<Self>,
 8016        envelope: TypedEnvelope<proto::CancelLanguageServerWork>,
 8017        mut cx: AsyncApp,
 8018    ) -> Result<proto::Ack> {
 8019        this.update(&mut cx, |this, cx| {
 8020            if let Some(work) = envelope.payload.work {
 8021                match work {
 8022                    proto::cancel_language_server_work::Work::Buffers(buffers) => {
 8023                        let buffers =
 8024                            this.buffer_ids_to_buffers(buffers.buffer_ids.into_iter(), cx);
 8025                        this.cancel_language_server_work_for_buffers(buffers, cx);
 8026                    }
 8027                    proto::cancel_language_server_work::Work::LanguageServerWork(work) => {
 8028                        let server_id = LanguageServerId::from_proto(work.language_server_id);
 8029                        this.cancel_language_server_work(server_id, work.token, cx);
 8030                    }
 8031                }
 8032            }
 8033        })?;
 8034
 8035        Ok(proto::Ack {})
 8036    }
 8037
 8038    fn buffer_ids_to_buffers(
 8039        &mut self,
 8040        buffer_ids: impl Iterator<Item = u64>,
 8041        cx: &mut Context<Self>,
 8042    ) -> Vec<Entity<Buffer>> {
 8043        buffer_ids
 8044            .into_iter()
 8045            .flat_map(|buffer_id| {
 8046                self.buffer_store
 8047                    .read(cx)
 8048                    .get(BufferId::new(buffer_id).log_err()?)
 8049            })
 8050            .collect::<Vec<_>>()
 8051    }
 8052
 8053    async fn handle_apply_additional_edits_for_completion(
 8054        this: Entity<Self>,
 8055        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 8056        mut cx: AsyncApp,
 8057    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 8058        let (buffer, completion) = this.update(&mut cx, |this, cx| {
 8059            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8060            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 8061            let completion = Self::deserialize_completion(
 8062                envelope
 8063                    .payload
 8064                    .completion
 8065                    .ok_or_else(|| anyhow!("invalid completion"))?,
 8066            )?;
 8067            anyhow::Ok((buffer, completion))
 8068        })??;
 8069
 8070        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 8071            this.apply_additional_edits_for_completion(
 8072                buffer,
 8073                Rc::new(RefCell::new(Box::new([Completion {
 8074                    replace_range: completion.replace_range,
 8075                    new_text: completion.new_text,
 8076                    source: completion.source,
 8077                    documentation: None,
 8078                    label: CodeLabel {
 8079                        text: Default::default(),
 8080                        runs: Default::default(),
 8081                        filter_range: Default::default(),
 8082                    },
 8083                    insert_text_mode: None,
 8084                    icon_path: None,
 8085                    confirm: None,
 8086                }]))),
 8087                0,
 8088                false,
 8089                cx,
 8090            )
 8091        })?;
 8092
 8093        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 8094            transaction: apply_additional_edits
 8095                .await?
 8096                .as_ref()
 8097                .map(language::proto::serialize_transaction),
 8098        })
 8099    }
 8100
 8101    pub fn last_formatting_failure(&self) -> Option<&str> {
 8102        self.last_formatting_failure.as_deref()
 8103    }
 8104
 8105    pub fn reset_last_formatting_failure(&mut self) {
 8106        self.last_formatting_failure = None;
 8107    }
 8108
 8109    pub fn environment_for_buffer(
 8110        &self,
 8111        buffer: &Entity<Buffer>,
 8112        cx: &mut Context<Self>,
 8113    ) -> Shared<Task<Option<HashMap<String, String>>>> {
 8114        if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
 8115            environment.update(cx, |env, cx| {
 8116                env.get_buffer_environment(buffer.clone(), self.worktree_store.clone(), cx)
 8117            })
 8118        } else {
 8119            Task::ready(None).shared()
 8120        }
 8121    }
 8122
 8123    pub fn format(
 8124        &mut self,
 8125        buffers: HashSet<Entity<Buffer>>,
 8126        target: LspFormatTarget,
 8127        push_to_history: bool,
 8128        trigger: FormatTrigger,
 8129        cx: &mut Context<Self>,
 8130    ) -> Task<anyhow::Result<ProjectTransaction>> {
 8131        let logger = zlog::scoped!("format");
 8132        if let Some(_) = self.as_local() {
 8133            zlog::trace!(logger => "Formatting locally");
 8134            let logger = zlog::scoped!(logger => "local");
 8135            let buffers = buffers
 8136                .into_iter()
 8137                .map(|buffer_handle| {
 8138                    let buffer = buffer_handle.read(cx);
 8139                    let buffer_abs_path = File::from_dyn(buffer.file())
 8140                        .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
 8141
 8142                    (buffer_handle, buffer_abs_path, buffer.remote_id())
 8143                })
 8144                .collect::<Vec<_>>();
 8145
 8146            cx.spawn(async move |lsp_store, cx| {
 8147                let mut formattable_buffers = Vec::with_capacity(buffers.len());
 8148
 8149                for (handle, abs_path, id) in buffers {
 8150                    let env = lsp_store
 8151                        .update(cx, |lsp_store, cx| {
 8152                            lsp_store.environment_for_buffer(&handle, cx)
 8153                        })?
 8154                        .await;
 8155
 8156                    let ranges = match &target {
 8157                        LspFormatTarget::Buffers => None,
 8158                        LspFormatTarget::Ranges(ranges) => {
 8159                            let Some(ranges) = ranges.get(&id) else {
 8160                                return Err(anyhow!("No format ranges provided for buffer"));
 8161                            };
 8162                            Some(ranges.clone())
 8163                        }
 8164                    };
 8165
 8166                    formattable_buffers.push(FormattableBuffer {
 8167                        handle,
 8168                        abs_path,
 8169                        env,
 8170                        ranges,
 8171                    });
 8172                }
 8173                zlog::trace!(logger => "Formatting {:?} buffers", formattable_buffers.len());
 8174
 8175                let format_timer = zlog::time!(logger => "Formatting buffers");
 8176                let result = LocalLspStore::format_locally(
 8177                    lsp_store.clone(),
 8178                    formattable_buffers,
 8179                    push_to_history,
 8180                    trigger,
 8181                    logger,
 8182                    cx,
 8183                )
 8184                .await;
 8185                format_timer.end();
 8186
 8187                zlog::trace!(logger => "Formatting completed with result {:?}", result.as_ref().map(|_| "<project-transaction>"));
 8188
 8189                lsp_store.update(cx, |lsp_store, _| {
 8190                    lsp_store.update_last_formatting_failure(&result);
 8191                })?;
 8192
 8193                result
 8194            })
 8195        } else if let Some((client, project_id)) = self.upstream_client() {
 8196            zlog::trace!(logger => "Formatting remotely");
 8197            let logger = zlog::scoped!(logger => "remote");
 8198            // Don't support formatting ranges via remote
 8199            match target {
 8200                LspFormatTarget::Buffers => {}
 8201                LspFormatTarget::Ranges(_) => {
 8202                    zlog::trace!(logger => "Ignoring unsupported remote range formatting request");
 8203                    return Task::ready(Ok(ProjectTransaction::default()));
 8204                }
 8205            }
 8206
 8207            let buffer_store = self.buffer_store();
 8208            cx.spawn(async move |lsp_store, cx| {
 8209                zlog::trace!(logger => "Sending remote format request");
 8210                let request_timer = zlog::time!(logger => "remote format request");
 8211                let result = client
 8212                    .request(proto::FormatBuffers {
 8213                        project_id,
 8214                        trigger: trigger as i32,
 8215                        buffer_ids: buffers
 8216                            .iter()
 8217                            .map(|buffer| buffer.update(cx, |buffer, _| buffer.remote_id().into()))
 8218                            .collect::<Result<_>>()?,
 8219                    })
 8220                    .await
 8221                    .and_then(|result| result.transaction.context("missing transaction"));
 8222                request_timer.end();
 8223
 8224                zlog::trace!(logger => "Remote format request resolved to {:?}", result.as_ref().map(|_| "<project_transaction>"));
 8225
 8226                lsp_store.update(cx, |lsp_store, _| {
 8227                    lsp_store.update_last_formatting_failure(&result);
 8228                })?;
 8229
 8230                let transaction_response = result?;
 8231                let _timer = zlog::time!(logger => "deserializing project transaction");
 8232                buffer_store
 8233                    .update(cx, |buffer_store, cx| {
 8234                        buffer_store.deserialize_project_transaction(
 8235                            transaction_response,
 8236                            push_to_history,
 8237                            cx,
 8238                        )
 8239                    })?
 8240                    .await
 8241            })
 8242        } else {
 8243            zlog::trace!(logger => "Not formatting");
 8244            Task::ready(Ok(ProjectTransaction::default()))
 8245        }
 8246    }
 8247
 8248    async fn handle_format_buffers(
 8249        this: Entity<Self>,
 8250        envelope: TypedEnvelope<proto::FormatBuffers>,
 8251        mut cx: AsyncApp,
 8252    ) -> Result<proto::FormatBuffersResponse> {
 8253        let sender_id = envelope.original_sender_id().unwrap_or_default();
 8254        let format = this.update(&mut cx, |this, cx| {
 8255            let mut buffers = HashSet::default();
 8256            for buffer_id in &envelope.payload.buffer_ids {
 8257                let buffer_id = BufferId::new(*buffer_id)?;
 8258                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 8259            }
 8260            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 8261            anyhow::Ok(this.format(buffers, LspFormatTarget::Buffers, false, trigger, cx))
 8262        })??;
 8263
 8264        let project_transaction = format.await?;
 8265        let project_transaction = this.update(&mut cx, |this, cx| {
 8266            this.buffer_store.update(cx, |buffer_store, cx| {
 8267                buffer_store.serialize_project_transaction_for_peer(
 8268                    project_transaction,
 8269                    sender_id,
 8270                    cx,
 8271                )
 8272            })
 8273        })?;
 8274        Ok(proto::FormatBuffersResponse {
 8275            transaction: Some(project_transaction),
 8276        })
 8277    }
 8278
 8279    async fn handle_apply_code_action_kind(
 8280        this: Entity<Self>,
 8281        envelope: TypedEnvelope<proto::ApplyCodeActionKind>,
 8282        mut cx: AsyncApp,
 8283    ) -> Result<proto::ApplyCodeActionKindResponse> {
 8284        let sender_id = envelope.original_sender_id().unwrap_or_default();
 8285        let format = this.update(&mut cx, |this, cx| {
 8286            let mut buffers = HashSet::default();
 8287            for buffer_id in &envelope.payload.buffer_ids {
 8288                let buffer_id = BufferId::new(*buffer_id)?;
 8289                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 8290            }
 8291            let kind = match envelope.payload.kind.as_str() {
 8292                "" => Ok(CodeActionKind::EMPTY),
 8293                "quickfix" => Ok(CodeActionKind::QUICKFIX),
 8294                "refactor" => Ok(CodeActionKind::REFACTOR),
 8295                "refactor.extract" => Ok(CodeActionKind::REFACTOR_EXTRACT),
 8296                "refactor.inline" => Ok(CodeActionKind::REFACTOR_INLINE),
 8297                "refactor.rewrite" => Ok(CodeActionKind::REFACTOR_REWRITE),
 8298                "source" => Ok(CodeActionKind::SOURCE),
 8299                "source.organizeImports" => Ok(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
 8300                "source.fixAll" => Ok(CodeActionKind::SOURCE_FIX_ALL),
 8301                _ => Err(anyhow!("Invalid code action kind")),
 8302            }?;
 8303            anyhow::Ok(this.apply_code_action_kind(buffers, kind, false, cx))
 8304        })??;
 8305
 8306        let project_transaction = format.await?;
 8307        let project_transaction = this.update(&mut cx, |this, cx| {
 8308            this.buffer_store.update(cx, |buffer_store, cx| {
 8309                buffer_store.serialize_project_transaction_for_peer(
 8310                    project_transaction,
 8311                    sender_id,
 8312                    cx,
 8313                )
 8314            })
 8315        })?;
 8316        Ok(proto::ApplyCodeActionKindResponse {
 8317            transaction: Some(project_transaction),
 8318        })
 8319    }
 8320
 8321    async fn shutdown_language_server(
 8322        server_state: Option<LanguageServerState>,
 8323        name: LanguageServerName,
 8324        cx: &mut AsyncApp,
 8325    ) {
 8326        let server = match server_state {
 8327            Some(LanguageServerState::Starting { startup, .. }) => {
 8328                let mut timer = cx
 8329                    .background_executor()
 8330                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 8331                    .fuse();
 8332
 8333                select! {
 8334                    server = startup.fuse() => server,
 8335                    _ = timer => {
 8336                        log::info!(
 8337                            "timeout waiting for language server {} to finish launching before stopping",
 8338                            name
 8339                        );
 8340                        None
 8341                    },
 8342                }
 8343            }
 8344
 8345            Some(LanguageServerState::Running { server, .. }) => Some(server),
 8346
 8347            None => None,
 8348        };
 8349
 8350        if let Some(server) = server {
 8351            if let Some(shutdown) = server.shutdown() {
 8352                shutdown.await;
 8353            }
 8354        }
 8355    }
 8356
 8357    // Returns a list of all of the worktrees which no longer have a language server and the root path
 8358    // for the stopped server
 8359    fn stop_local_language_server(
 8360        &mut self,
 8361        server_id: LanguageServerId,
 8362        name: LanguageServerName,
 8363        cx: &mut Context<Self>,
 8364    ) -> Task<Vec<WorktreeId>> {
 8365        let local = match &mut self.mode {
 8366            LspStoreMode::Local(local) => local,
 8367            _ => {
 8368                return Task::ready(Vec::new());
 8369            }
 8370        };
 8371
 8372        let mut orphaned_worktrees = vec![];
 8373        // Remove this server ID from all entries in the given worktree.
 8374        local.language_server_ids.retain(|(worktree, _), ids| {
 8375            if !ids.remove(&server_id) {
 8376                return true;
 8377            }
 8378
 8379            if ids.is_empty() {
 8380                orphaned_worktrees.push(*worktree);
 8381                false
 8382            } else {
 8383                true
 8384            }
 8385        });
 8386        let _ = self.language_server_statuses.remove(&server_id);
 8387        log::info!("stopping language server {name}");
 8388        self.buffer_store.update(cx, |buffer_store, cx| {
 8389            for buffer in buffer_store.buffers() {
 8390                buffer.update(cx, |buffer, cx| {
 8391                    buffer.update_diagnostics(server_id, DiagnosticSet::new([], buffer), cx);
 8392                    buffer.set_completion_triggers(server_id, Default::default(), cx);
 8393                });
 8394            }
 8395        });
 8396
 8397        for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
 8398            summaries.retain(|path, summaries_by_server_id| {
 8399                if summaries_by_server_id.remove(&server_id).is_some() {
 8400                    if let Some((client, project_id)) = self.downstream_client.clone() {
 8401                        client
 8402                            .send(proto::UpdateDiagnosticSummary {
 8403                                project_id,
 8404                                worktree_id: worktree_id.to_proto(),
 8405                                summary: Some(proto::DiagnosticSummary {
 8406                                    path: path.as_ref().to_proto(),
 8407                                    language_server_id: server_id.0 as u64,
 8408                                    error_count: 0,
 8409                                    warning_count: 0,
 8410                                }),
 8411                            })
 8412                            .log_err();
 8413                    }
 8414                    !summaries_by_server_id.is_empty()
 8415                } else {
 8416                    true
 8417                }
 8418            });
 8419        }
 8420
 8421        let local = self.as_local_mut().unwrap();
 8422        for diagnostics in local.diagnostics.values_mut() {
 8423            diagnostics.retain(|_, diagnostics_by_server_id| {
 8424                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 8425                    diagnostics_by_server_id.remove(ix);
 8426                    !diagnostics_by_server_id.is_empty()
 8427                } else {
 8428                    true
 8429                }
 8430            });
 8431        }
 8432        local.language_server_watched_paths.remove(&server_id);
 8433        let server_state = local.language_servers.remove(&server_id);
 8434        cx.notify();
 8435        cx.emit(LspStoreEvent::LanguageServerRemoved(server_id));
 8436        cx.spawn(async move |_, cx| {
 8437            Self::shutdown_language_server(server_state, name, cx).await;
 8438            orphaned_worktrees
 8439        })
 8440    }
 8441
 8442    pub fn restart_language_servers_for_buffers(
 8443        &mut self,
 8444        buffers: Vec<Entity<Buffer>>,
 8445        cx: &mut Context<Self>,
 8446    ) {
 8447        if let Some((client, project_id)) = self.upstream_client() {
 8448            let request = client.request(proto::RestartLanguageServers {
 8449                project_id,
 8450                buffer_ids: buffers
 8451                    .into_iter()
 8452                    .map(|b| b.read(cx).remote_id().to_proto())
 8453                    .collect(),
 8454            });
 8455            cx.background_spawn(request).detach_and_log_err(cx);
 8456        } else {
 8457            let stop_task = self.stop_local_language_servers_for_buffers(&buffers, cx);
 8458            cx.spawn(async move |this, cx| {
 8459                stop_task.await;
 8460                this.update(cx, |this, cx| {
 8461                    for buffer in buffers {
 8462                        this.register_buffer_with_language_servers(&buffer, true, cx);
 8463                    }
 8464                })
 8465                .ok()
 8466            })
 8467            .detach();
 8468        }
 8469    }
 8470
 8471    pub fn stop_language_servers_for_buffers(
 8472        &mut self,
 8473        buffers: Vec<Entity<Buffer>>,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        if let Some((client, project_id)) = self.upstream_client() {
 8477            let request = client.request(proto::StopLanguageServers {
 8478                project_id,
 8479                buffer_ids: buffers
 8480                    .into_iter()
 8481                    .map(|b| b.read(cx).remote_id().to_proto())
 8482                    .collect(),
 8483            });
 8484            cx.background_spawn(request).detach_and_log_err(cx);
 8485        } else {
 8486            self.stop_local_language_servers_for_buffers(&buffers, cx)
 8487                .detach();
 8488        }
 8489    }
 8490
 8491    fn stop_local_language_servers_for_buffers(
 8492        &mut self,
 8493        buffers: &[Entity<Buffer>],
 8494        cx: &mut Context<Self>,
 8495    ) -> Task<()> {
 8496        let Some(local) = self.as_local_mut() else {
 8497            return Task::ready(());
 8498        };
 8499        let language_servers_to_stop = buffers
 8500            .iter()
 8501            .flat_map(|buffer| {
 8502                buffer.update(cx, |buffer, cx| {
 8503                    local.language_server_ids_for_buffer(buffer, cx)
 8504                })
 8505            })
 8506            .collect::<BTreeSet<_>>();
 8507        local.lsp_tree.update(cx, |this, _| {
 8508            this.remove_nodes(&language_servers_to_stop);
 8509        });
 8510        let tasks = language_servers_to_stop
 8511            .into_iter()
 8512            .map(|server| {
 8513                let name = self
 8514                    .language_server_statuses
 8515                    .get(&server)
 8516                    .map(|state| state.name.as_str().into())
 8517                    .unwrap_or_else(|| LanguageServerName::from("Unknown"));
 8518                self.stop_local_language_server(server, name, cx)
 8519            })
 8520            .collect::<Vec<_>>();
 8521
 8522        cx.background_spawn(futures::future::join_all(tasks).map(|_| ()))
 8523    }
 8524
 8525    fn get_buffer<'a>(&self, abs_path: &Path, cx: &'a App) -> Option<&'a Buffer> {
 8526        let (worktree, relative_path) =
 8527            self.worktree_store.read(cx).find_worktree(&abs_path, cx)?;
 8528
 8529        let project_path = ProjectPath {
 8530            worktree_id: worktree.read(cx).id(),
 8531            path: relative_path.into(),
 8532        };
 8533
 8534        Some(
 8535            self.buffer_store()
 8536                .read(cx)
 8537                .get_by_path(&project_path, cx)?
 8538                .read(cx),
 8539        )
 8540    }
 8541
 8542    pub fn update_diagnostics(
 8543        &mut self,
 8544        language_server_id: LanguageServerId,
 8545        params: lsp::PublishDiagnosticsParams,
 8546        disk_based_sources: &[String],
 8547        cx: &mut Context<Self>,
 8548    ) -> Result<()> {
 8549        self.merge_diagnostics(
 8550            language_server_id,
 8551            params,
 8552            disk_based_sources,
 8553            |_| false,
 8554            cx,
 8555        )
 8556    }
 8557
 8558    pub fn merge_diagnostics<F: Fn(&Diagnostic) -> bool + Clone>(
 8559        &mut self,
 8560        language_server_id: LanguageServerId,
 8561        mut params: lsp::PublishDiagnosticsParams,
 8562        disk_based_sources: &[String],
 8563        filter: F,
 8564        cx: &mut Context<Self>,
 8565    ) -> Result<()> {
 8566        if !self.mode.is_local() {
 8567            anyhow::bail!("called update_diagnostics on remote");
 8568        }
 8569        let abs_path = params
 8570            .uri
 8571            .to_file_path()
 8572            .map_err(|_| anyhow!("URI is not a file"))?;
 8573        let mut diagnostics = Vec::default();
 8574        let mut primary_diagnostic_group_ids = HashMap::default();
 8575        let mut sources_by_group_id = HashMap::default();
 8576        let mut supporting_diagnostics = HashMap::default();
 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                        message: diagnostic.message.trim().to_string(),
 8626                        group_id,
 8627                        is_primary: true,
 8628                        is_disk_based,
 8629                        is_unnecessary,
 8630                        data: diagnostic.data.clone(),
 8631                    },
 8632                });
 8633                if let Some(infos) = &diagnostic.related_information {
 8634                    for info in infos {
 8635                        if info.location.uri == params.uri && !info.message.is_empty() {
 8636                            let range = range_from_lsp(info.location.range);
 8637                            diagnostics.push(DiagnosticEntry {
 8638                                range,
 8639                                diagnostic: Diagnostic {
 8640                                    source: diagnostic.source.clone(),
 8641                                    code: diagnostic.code.clone(),
 8642                                    code_description: diagnostic
 8643                                        .code_description
 8644                                        .as_ref()
 8645                                        .map(|c| c.href.clone()),
 8646                                    severity: DiagnosticSeverity::INFORMATION,
 8647                                    message: info.message.trim().to_string(),
 8648                                    group_id,
 8649                                    is_primary: false,
 8650                                    is_disk_based,
 8651                                    is_unnecessary: false,
 8652                                    data: diagnostic.data.clone(),
 8653                                },
 8654                            });
 8655                        }
 8656                    }
 8657                }
 8658            }
 8659        }
 8660
 8661        for entry in &mut diagnostics {
 8662            let diagnostic = &mut entry.diagnostic;
 8663            if !diagnostic.is_primary {
 8664                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 8665                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
 8666                    source,
 8667                    diagnostic.code.clone(),
 8668                    entry.range.clone(),
 8669                )) {
 8670                    if let Some(severity) = severity {
 8671                        diagnostic.severity = severity;
 8672                    }
 8673                    diagnostic.is_unnecessary = is_unnecessary;
 8674                }
 8675            }
 8676        }
 8677
 8678        self.merge_diagnostic_entries(
 8679            language_server_id,
 8680            abs_path,
 8681            params.version,
 8682            diagnostics,
 8683            filter,
 8684            cx,
 8685        )?;
 8686        Ok(())
 8687    }
 8688
 8689    fn insert_newly_running_language_server(
 8690        &mut self,
 8691        adapter: Arc<CachedLspAdapter>,
 8692        language_server: Arc<LanguageServer>,
 8693        server_id: LanguageServerId,
 8694        key: (WorktreeId, LanguageServerName),
 8695        workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
 8696        cx: &mut Context<Self>,
 8697    ) {
 8698        let Some(local) = self.as_local_mut() else {
 8699            return;
 8700        };
 8701        // If the language server for this key doesn't match the server id, don't store the
 8702        // server. Which will cause it to be dropped, killing the process
 8703        if local
 8704            .language_server_ids
 8705            .get(&key)
 8706            .map(|ids| !ids.contains(&server_id))
 8707            .unwrap_or(false)
 8708        {
 8709            return;
 8710        }
 8711
 8712        // Update language_servers collection with Running variant of LanguageServerState
 8713        // indicating that the server is up and running and ready
 8714        let workspace_folders = workspace_folders.lock().clone();
 8715        local.language_servers.insert(
 8716            server_id,
 8717            LanguageServerState::running(
 8718                workspace_folders,
 8719                adapter.clone(),
 8720                language_server.clone(),
 8721                None,
 8722            ),
 8723        );
 8724        if let Some(file_ops_caps) = language_server
 8725            .capabilities()
 8726            .workspace
 8727            .as_ref()
 8728            .and_then(|ws| ws.file_operations.as_ref())
 8729        {
 8730            let did_rename_caps = file_ops_caps.did_rename.as_ref();
 8731            let will_rename_caps = file_ops_caps.will_rename.as_ref();
 8732            if did_rename_caps.or(will_rename_caps).is_some() {
 8733                let watcher = RenamePathsWatchedForServer::default()
 8734                    .with_did_rename_patterns(did_rename_caps)
 8735                    .with_will_rename_patterns(will_rename_caps);
 8736                local
 8737                    .language_server_paths_watched_for_rename
 8738                    .insert(server_id, watcher);
 8739            }
 8740        }
 8741
 8742        self.language_server_statuses.insert(
 8743            server_id,
 8744            LanguageServerStatus {
 8745                name: language_server.name().to_string(),
 8746                pending_work: Default::default(),
 8747                has_pending_diagnostic_updates: false,
 8748                progress_tokens: Default::default(),
 8749            },
 8750        );
 8751
 8752        cx.emit(LspStoreEvent::LanguageServerAdded(
 8753            server_id,
 8754            language_server.name(),
 8755            Some(key.0),
 8756        ));
 8757        cx.emit(LspStoreEvent::RefreshInlayHints);
 8758
 8759        if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
 8760            downstream_client
 8761                .send(proto::StartLanguageServer {
 8762                    project_id: *project_id,
 8763                    server: Some(proto::LanguageServer {
 8764                        id: server_id.0 as u64,
 8765                        name: language_server.name().to_string(),
 8766                        worktree_id: Some(key.0.to_proto()),
 8767                    }),
 8768                })
 8769                .log_err();
 8770        }
 8771
 8772        // Tell the language server about every open buffer in the worktree that matches the language.
 8773        self.buffer_store.clone().update(cx, |buffer_store, cx| {
 8774            for buffer_handle in buffer_store.buffers() {
 8775                let buffer = buffer_handle.read(cx);
 8776                let file = match File::from_dyn(buffer.file()) {
 8777                    Some(file) => file,
 8778                    None => continue,
 8779                };
 8780                let language = match buffer.language() {
 8781                    Some(language) => language,
 8782                    None => continue,
 8783                };
 8784
 8785                if file.worktree.read(cx).id() != key.0
 8786                    || !self
 8787                        .languages
 8788                        .lsp_adapters(&language.name())
 8789                        .iter()
 8790                        .any(|a| a.name == key.1)
 8791                {
 8792                    continue;
 8793                }
 8794                // didOpen
 8795                let file = match file.as_local() {
 8796                    Some(file) => file,
 8797                    None => continue,
 8798                };
 8799
 8800                let local = self.as_local_mut().unwrap();
 8801
 8802                if local.registered_buffers.contains_key(&buffer.remote_id()) {
 8803                    let versions = local
 8804                        .buffer_snapshots
 8805                        .entry(buffer.remote_id())
 8806                        .or_default()
 8807                        .entry(server_id)
 8808                        .and_modify(|_| {
 8809                            assert!(
 8810                            false,
 8811                            "There should not be an existing snapshot for a newly inserted buffer"
 8812                        )
 8813                        })
 8814                        .or_insert_with(|| {
 8815                            vec![LspBufferSnapshot {
 8816                                version: 0,
 8817                                snapshot: buffer.text_snapshot(),
 8818                            }]
 8819                        });
 8820
 8821                    let snapshot = versions.last().unwrap();
 8822                    let version = snapshot.version;
 8823                    let initial_snapshot = &snapshot.snapshot;
 8824                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 8825                    language_server.register_buffer(
 8826                        uri,
 8827                        adapter.language_id(&language.name()),
 8828                        version,
 8829                        initial_snapshot.text(),
 8830                    );
 8831                }
 8832                buffer_handle.update(cx, |buffer, cx| {
 8833                    buffer.set_completion_triggers(
 8834                        server_id,
 8835                        language_server
 8836                            .capabilities()
 8837                            .completion_provider
 8838                            .as_ref()
 8839                            .and_then(|provider| {
 8840                                provider
 8841                                    .trigger_characters
 8842                                    .as_ref()
 8843                                    .map(|characters| characters.iter().cloned().collect())
 8844                            })
 8845                            .unwrap_or_default(),
 8846                        cx,
 8847                    )
 8848                });
 8849            }
 8850        });
 8851
 8852        cx.notify();
 8853    }
 8854
 8855    pub fn language_servers_running_disk_based_diagnostics(
 8856        &self,
 8857    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 8858        self.language_server_statuses
 8859            .iter()
 8860            .filter_map(|(id, status)| {
 8861                if status.has_pending_diagnostic_updates {
 8862                    Some(*id)
 8863                } else {
 8864                    None
 8865                }
 8866            })
 8867    }
 8868
 8869    pub(crate) fn cancel_language_server_work_for_buffers(
 8870        &mut self,
 8871        buffers: impl IntoIterator<Item = Entity<Buffer>>,
 8872        cx: &mut Context<Self>,
 8873    ) {
 8874        if let Some((client, project_id)) = self.upstream_client() {
 8875            let request = client.request(proto::CancelLanguageServerWork {
 8876                project_id,
 8877                work: Some(proto::cancel_language_server_work::Work::Buffers(
 8878                    proto::cancel_language_server_work::Buffers {
 8879                        buffer_ids: buffers
 8880                            .into_iter()
 8881                            .map(|b| b.read(cx).remote_id().to_proto())
 8882                            .collect(),
 8883                    },
 8884                )),
 8885            });
 8886            cx.background_spawn(request).detach_and_log_err(cx);
 8887        } else if let Some(local) = self.as_local() {
 8888            let servers = buffers
 8889                .into_iter()
 8890                .flat_map(|buffer| {
 8891                    buffer.update(cx, |buffer, cx| {
 8892                        local.language_server_ids_for_buffer(buffer, cx).into_iter()
 8893                    })
 8894                })
 8895                .collect::<HashSet<_>>();
 8896            for server_id in servers {
 8897                self.cancel_language_server_work(server_id, None, cx);
 8898            }
 8899        }
 8900    }
 8901
 8902    pub(crate) fn cancel_language_server_work(
 8903        &mut self,
 8904        server_id: LanguageServerId,
 8905        token_to_cancel: Option<String>,
 8906        cx: &mut Context<Self>,
 8907    ) {
 8908        if let Some(local) = self.as_local() {
 8909            let status = self.language_server_statuses.get(&server_id);
 8910            let server = local.language_servers.get(&server_id);
 8911            if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status)
 8912            {
 8913                for (token, progress) in &status.pending_work {
 8914                    if let Some(token_to_cancel) = token_to_cancel.as_ref() {
 8915                        if token != token_to_cancel {
 8916                            continue;
 8917                        }
 8918                    }
 8919                    if progress.is_cancellable {
 8920                        server
 8921                            .notify::<lsp::notification::WorkDoneProgressCancel>(
 8922                                &WorkDoneProgressCancelParams {
 8923                                    token: lsp::NumberOrString::String(token.clone()),
 8924                                },
 8925                            )
 8926                            .ok();
 8927                    }
 8928                }
 8929            }
 8930        } else if let Some((client, project_id)) = self.upstream_client() {
 8931            let request = client.request(proto::CancelLanguageServerWork {
 8932                project_id,
 8933                work: Some(
 8934                    proto::cancel_language_server_work::Work::LanguageServerWork(
 8935                        proto::cancel_language_server_work::LanguageServerWork {
 8936                            language_server_id: server_id.to_proto(),
 8937                            token: token_to_cancel,
 8938                        },
 8939                    ),
 8940                ),
 8941            });
 8942            cx.background_spawn(request).detach_and_log_err(cx);
 8943        }
 8944    }
 8945
 8946    fn register_supplementary_language_server(
 8947        &mut self,
 8948        id: LanguageServerId,
 8949        name: LanguageServerName,
 8950        server: Arc<LanguageServer>,
 8951        cx: &mut Context<Self>,
 8952    ) {
 8953        if let Some(local) = self.as_local_mut() {
 8954            local
 8955                .supplementary_language_servers
 8956                .insert(id, (name.clone(), server));
 8957            cx.emit(LspStoreEvent::LanguageServerAdded(id, name, None));
 8958        }
 8959    }
 8960
 8961    fn unregister_supplementary_language_server(
 8962        &mut self,
 8963        id: LanguageServerId,
 8964        cx: &mut Context<Self>,
 8965    ) {
 8966        if let Some(local) = self.as_local_mut() {
 8967            local.supplementary_language_servers.remove(&id);
 8968            cx.emit(LspStoreEvent::LanguageServerRemoved(id));
 8969        }
 8970    }
 8971
 8972    pub(crate) fn supplementary_language_servers(
 8973        &self,
 8974    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
 8975        self.as_local().into_iter().flat_map(|local| {
 8976            local
 8977                .supplementary_language_servers
 8978                .iter()
 8979                .map(|(id, (name, _))| (*id, name.clone()))
 8980        })
 8981    }
 8982
 8983    pub fn language_server_adapter_for_id(
 8984        &self,
 8985        id: LanguageServerId,
 8986    ) -> Option<Arc<CachedLspAdapter>> {
 8987        self.as_local()
 8988            .and_then(|local| local.language_servers.get(&id))
 8989            .and_then(|language_server_state| match language_server_state {
 8990                LanguageServerState::Running { adapter, .. } => Some(adapter.clone()),
 8991                _ => None,
 8992            })
 8993    }
 8994
 8995    pub(super) fn update_local_worktree_language_servers(
 8996        &mut self,
 8997        worktree_handle: &Entity<Worktree>,
 8998        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 8999        cx: &mut Context<Self>,
 9000    ) {
 9001        if changes.is_empty() {
 9002            return;
 9003        }
 9004
 9005        let Some(local) = self.as_local() else { return };
 9006
 9007        local.prettier_store.update(cx, |prettier_store, cx| {
 9008            prettier_store.update_prettier_settings(&worktree_handle, changes, cx)
 9009        });
 9010
 9011        let worktree_id = worktree_handle.read(cx).id();
 9012        let mut language_server_ids = local
 9013            .language_server_ids
 9014            .iter()
 9015            .flat_map(|((server_worktree, _), server_ids)| {
 9016                server_ids
 9017                    .iter()
 9018                    .filter_map(|server_id| server_worktree.eq(&worktree_id).then(|| *server_id))
 9019            })
 9020            .collect::<Vec<_>>();
 9021        language_server_ids.sort();
 9022        language_server_ids.dedup();
 9023
 9024        let abs_path = worktree_handle.read(cx).abs_path();
 9025        for server_id in &language_server_ids {
 9026            if let Some(LanguageServerState::Running { server, .. }) =
 9027                local.language_servers.get(server_id)
 9028            {
 9029                if let Some(watched_paths) = local
 9030                    .language_server_watched_paths
 9031                    .get(server_id)
 9032                    .and_then(|paths| paths.worktree_paths.get(&worktree_id))
 9033                {
 9034                    let params = lsp::DidChangeWatchedFilesParams {
 9035                        changes: changes
 9036                            .iter()
 9037                            .filter_map(|(path, _, change)| {
 9038                                if !watched_paths.is_match(path) {
 9039                                    return None;
 9040                                }
 9041                                let typ = match change {
 9042                                    PathChange::Loaded => return None,
 9043                                    PathChange::Added => lsp::FileChangeType::CREATED,
 9044                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 9045                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 9046                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 9047                                };
 9048                                Some(lsp::FileEvent {
 9049                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 9050                                    typ,
 9051                                })
 9052                            })
 9053                            .collect(),
 9054                    };
 9055                    if !params.changes.is_empty() {
 9056                        server
 9057                            .notify::<lsp::notification::DidChangeWatchedFiles>(&params)
 9058                            .log_err();
 9059                    }
 9060                }
 9061            }
 9062        }
 9063    }
 9064
 9065    pub fn wait_for_remote_buffer(
 9066        &mut self,
 9067        id: BufferId,
 9068        cx: &mut Context<Self>,
 9069    ) -> Task<Result<Entity<Buffer>>> {
 9070        self.buffer_store.update(cx, |buffer_store, cx| {
 9071            buffer_store.wait_for_remote_buffer(id, cx)
 9072        })
 9073    }
 9074
 9075    fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
 9076        proto::Symbol {
 9077            language_server_name: symbol.language_server_name.0.to_string(),
 9078            source_worktree_id: symbol.source_worktree_id.to_proto(),
 9079            language_server_id: symbol.source_language_server_id.to_proto(),
 9080            worktree_id: symbol.path.worktree_id.to_proto(),
 9081            path: symbol.path.path.as_ref().to_proto(),
 9082            name: symbol.name.clone(),
 9083            kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
 9084            start: Some(proto::PointUtf16 {
 9085                row: symbol.range.start.0.row,
 9086                column: symbol.range.start.0.column,
 9087            }),
 9088            end: Some(proto::PointUtf16 {
 9089                row: symbol.range.end.0.row,
 9090                column: symbol.range.end.0.column,
 9091            }),
 9092            signature: symbol.signature.to_vec(),
 9093        }
 9094    }
 9095
 9096    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9097        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9098        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9099        let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
 9100        let path = ProjectPath {
 9101            worktree_id,
 9102            path: Arc::<Path>::from_proto(serialized_symbol.path),
 9103        };
 9104
 9105        let start = serialized_symbol
 9106            .start
 9107            .ok_or_else(|| anyhow!("invalid start"))?;
 9108        let end = serialized_symbol
 9109            .end
 9110            .ok_or_else(|| anyhow!("invalid end"))?;
 9111        Ok(CoreSymbol {
 9112            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9113            source_worktree_id,
 9114            source_language_server_id: LanguageServerId::from_proto(
 9115                serialized_symbol.language_server_id,
 9116            ),
 9117            path,
 9118            name: serialized_symbol.name,
 9119            range: Unclipped(PointUtf16::new(start.row, start.column))
 9120                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9121            kind,
 9122            signature: serialized_symbol
 9123                .signature
 9124                .try_into()
 9125                .map_err(|_| anyhow!("invalid signature"))?,
 9126        })
 9127    }
 9128
 9129    pub(crate) fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
 9130        let mut serialized_completion = proto::Completion {
 9131            old_replace_start: Some(serialize_anchor(&completion.replace_range.start)),
 9132            old_replace_end: Some(serialize_anchor(&completion.replace_range.end)),
 9133            new_text: completion.new_text.clone(),
 9134            ..proto::Completion::default()
 9135        };
 9136        match &completion.source {
 9137            CompletionSource::Lsp {
 9138                insert_range,
 9139                server_id,
 9140                lsp_completion,
 9141                lsp_defaults,
 9142                resolved,
 9143            } => {
 9144                let (old_insert_start, old_insert_end) = insert_range
 9145                    .as_ref()
 9146                    .map(|range| (serialize_anchor(&range.start), serialize_anchor(&range.end)))
 9147                    .unzip();
 9148
 9149                serialized_completion.old_insert_start = old_insert_start;
 9150                serialized_completion.old_insert_end = old_insert_end;
 9151                serialized_completion.source = proto::completion::Source::Lsp as i32;
 9152                serialized_completion.server_id = server_id.0 as u64;
 9153                serialized_completion.lsp_completion = serde_json::to_vec(lsp_completion).unwrap();
 9154                serialized_completion.lsp_defaults = lsp_defaults
 9155                    .as_deref()
 9156                    .map(|lsp_defaults| serde_json::to_vec(lsp_defaults).unwrap());
 9157                serialized_completion.resolved = *resolved;
 9158            }
 9159            CompletionSource::BufferWord {
 9160                word_range,
 9161                resolved,
 9162            } => {
 9163                serialized_completion.source = proto::completion::Source::BufferWord as i32;
 9164                serialized_completion.buffer_word_start = Some(serialize_anchor(&word_range.start));
 9165                serialized_completion.buffer_word_end = Some(serialize_anchor(&word_range.end));
 9166                serialized_completion.resolved = *resolved;
 9167            }
 9168            CompletionSource::Custom => {
 9169                serialized_completion.source = proto::completion::Source::Custom as i32;
 9170                serialized_completion.resolved = true;
 9171            }
 9172        }
 9173
 9174        serialized_completion
 9175    }
 9176
 9177    pub(crate) fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
 9178        let old_replace_start = completion
 9179            .old_replace_start
 9180            .and_then(deserialize_anchor)
 9181            .context("invalid old start")?;
 9182        let old_replace_end = completion
 9183            .old_replace_end
 9184            .and_then(deserialize_anchor)
 9185            .context("invalid old end")?;
 9186        let insert_range = {
 9187            match completion.old_insert_start.zip(completion.old_insert_end) {
 9188                Some((start, end)) => {
 9189                    let start = deserialize_anchor(start).context("invalid insert old start")?;
 9190                    let end = deserialize_anchor(end).context("invalid insert old end")?;
 9191                    Some(start..end)
 9192                }
 9193                None => None,
 9194            }
 9195        };
 9196        Ok(CoreCompletion {
 9197            replace_range: old_replace_start..old_replace_end,
 9198            new_text: completion.new_text,
 9199            source: match proto::completion::Source::from_i32(completion.source) {
 9200                Some(proto::completion::Source::Custom) => CompletionSource::Custom,
 9201                Some(proto::completion::Source::Lsp) => CompletionSource::Lsp {
 9202                    insert_range,
 9203                    server_id: LanguageServerId::from_proto(completion.server_id),
 9204                    lsp_completion: serde_json::from_slice(&completion.lsp_completion)?,
 9205                    lsp_defaults: completion
 9206                        .lsp_defaults
 9207                        .as_deref()
 9208                        .map(serde_json::from_slice)
 9209                        .transpose()?,
 9210                    resolved: completion.resolved,
 9211                },
 9212                Some(proto::completion::Source::BufferWord) => {
 9213                    let word_range = completion
 9214                        .buffer_word_start
 9215                        .and_then(deserialize_anchor)
 9216                        .context("invalid buffer word start")?
 9217                        ..completion
 9218                            .buffer_word_end
 9219                            .and_then(deserialize_anchor)
 9220                            .context("invalid buffer word end")?;
 9221                    CompletionSource::BufferWord {
 9222                        word_range,
 9223                        resolved: completion.resolved,
 9224                    }
 9225                }
 9226                _ => anyhow::bail!("Unexpected completion source {}", completion.source),
 9227            },
 9228        })
 9229    }
 9230
 9231    pub(crate) fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
 9232        let (kind, lsp_action) = match &action.lsp_action {
 9233            LspAction::Action(code_action) => (
 9234                proto::code_action::Kind::Action as i32,
 9235                serde_json::to_vec(code_action).unwrap(),
 9236            ),
 9237            LspAction::Command(command) => (
 9238                proto::code_action::Kind::Command as i32,
 9239                serde_json::to_vec(command).unwrap(),
 9240            ),
 9241            LspAction::CodeLens(code_lens) => (
 9242                proto::code_action::Kind::CodeLens as i32,
 9243                serde_json::to_vec(code_lens).unwrap(),
 9244            ),
 9245        };
 9246
 9247        proto::CodeAction {
 9248            server_id: action.server_id.0 as u64,
 9249            start: Some(serialize_anchor(&action.range.start)),
 9250            end: Some(serialize_anchor(&action.range.end)),
 9251            lsp_action,
 9252            kind,
 9253            resolved: action.resolved,
 9254        }
 9255    }
 9256
 9257    pub(crate) fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
 9258        let start = action
 9259            .start
 9260            .and_then(deserialize_anchor)
 9261            .context("invalid start")?;
 9262        let end = action
 9263            .end
 9264            .and_then(deserialize_anchor)
 9265            .context("invalid end")?;
 9266        let lsp_action = match proto::code_action::Kind::from_i32(action.kind) {
 9267            Some(proto::code_action::Kind::Action) => {
 9268                LspAction::Action(serde_json::from_slice(&action.lsp_action)?)
 9269            }
 9270            Some(proto::code_action::Kind::Command) => {
 9271                LspAction::Command(serde_json::from_slice(&action.lsp_action)?)
 9272            }
 9273            Some(proto::code_action::Kind::CodeLens) => {
 9274                LspAction::CodeLens(serde_json::from_slice(&action.lsp_action)?)
 9275            }
 9276            None => anyhow::bail!("Unknown action kind {}", action.kind),
 9277        };
 9278        Ok(CodeAction {
 9279            server_id: LanguageServerId(action.server_id as usize),
 9280            range: start..end,
 9281            resolved: action.resolved,
 9282            lsp_action,
 9283        })
 9284    }
 9285
 9286    fn update_last_formatting_failure<T>(&mut self, formatting_result: &anyhow::Result<T>) {
 9287        match &formatting_result {
 9288            Ok(_) => self.last_formatting_failure = None,
 9289            Err(error) => {
 9290                let error_string = format!("{error:#}");
 9291                log::error!("Formatting failed: {error_string}");
 9292                self.last_formatting_failure
 9293                    .replace(error_string.lines().join(" "));
 9294            }
 9295        }
 9296    }
 9297}
 9298
 9299fn resolve_word_completion(snapshot: &BufferSnapshot, completion: &mut Completion) {
 9300    let CompletionSource::BufferWord {
 9301        word_range,
 9302        resolved,
 9303    } = &mut completion.source
 9304    else {
 9305        return;
 9306    };
 9307    if *resolved {
 9308        return;
 9309    }
 9310
 9311    if completion.new_text
 9312        != snapshot
 9313            .text_for_range(word_range.clone())
 9314            .collect::<String>()
 9315    {
 9316        return;
 9317    }
 9318
 9319    let mut offset = 0;
 9320    for chunk in snapshot.chunks(word_range.clone(), true) {
 9321        let end_offset = offset + chunk.text.len();
 9322        if let Some(highlight_id) = chunk.syntax_highlight_id {
 9323            completion
 9324                .label
 9325                .runs
 9326                .push((offset..end_offset, highlight_id));
 9327        }
 9328        offset = end_offset;
 9329    }
 9330    *resolved = true;
 9331}
 9332
 9333impl EventEmitter<LspStoreEvent> for LspStore {}
 9334
 9335fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
 9336    hover
 9337        .contents
 9338        .retain(|hover_block| !hover_block.text.trim().is_empty());
 9339    if hover.contents.is_empty() {
 9340        None
 9341    } else {
 9342        Some(hover)
 9343    }
 9344}
 9345
 9346async fn populate_labels_for_completions(
 9347    new_completions: Vec<CoreCompletion>,
 9348    language: Option<Arc<Language>>,
 9349    lsp_adapter: Option<Arc<CachedLspAdapter>>,
 9350    completions: &mut Vec<Completion>,
 9351) {
 9352    let lsp_completions = new_completions
 9353        .iter()
 9354        .filter_map(|new_completion| {
 9355            if let Some(lsp_completion) = new_completion.source.lsp_completion(true) {
 9356                Some(lsp_completion.into_owned())
 9357            } else {
 9358                None
 9359            }
 9360        })
 9361        .collect::<Vec<_>>();
 9362
 9363    let mut labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
 9364        lsp_adapter
 9365            .labels_for_completions(&lsp_completions, language)
 9366            .await
 9367            .log_err()
 9368            .unwrap_or_default()
 9369    } else {
 9370        Vec::new()
 9371    }
 9372    .into_iter()
 9373    .fuse();
 9374
 9375    for completion in new_completions {
 9376        match completion.source.lsp_completion(true) {
 9377            Some(lsp_completion) => {
 9378                let documentation = if let Some(docs) = lsp_completion.documentation.clone() {
 9379                    Some(docs.into())
 9380                } else {
 9381                    None
 9382                };
 9383
 9384                let mut label = labels.next().flatten().unwrap_or_else(|| {
 9385                    CodeLabel::fallback_for_completion(&lsp_completion, language.as_deref())
 9386                });
 9387                ensure_uniform_list_compatible_label(&mut label);
 9388                completions.push(Completion {
 9389                    label,
 9390                    documentation,
 9391                    replace_range: completion.replace_range,
 9392                    new_text: completion.new_text,
 9393                    insert_text_mode: lsp_completion.insert_text_mode,
 9394                    source: completion.source,
 9395                    icon_path: None,
 9396                    confirm: None,
 9397                });
 9398            }
 9399            None => {
 9400                let mut label = CodeLabel::plain(completion.new_text.clone(), None);
 9401                ensure_uniform_list_compatible_label(&mut label);
 9402                completions.push(Completion {
 9403                    label,
 9404                    documentation: None,
 9405                    replace_range: completion.replace_range,
 9406                    new_text: completion.new_text,
 9407                    source: completion.source,
 9408                    insert_text_mode: None,
 9409                    icon_path: None,
 9410                    confirm: None,
 9411                });
 9412            }
 9413        }
 9414    }
 9415}
 9416
 9417#[derive(Debug)]
 9418pub enum LanguageServerToQuery {
 9419    /// Query language servers in order of users preference, up until one capable of handling the request is found.
 9420    FirstCapable,
 9421    /// Query a specific language server.
 9422    Other(LanguageServerId),
 9423}
 9424
 9425#[derive(Default)]
 9426struct RenamePathsWatchedForServer {
 9427    did_rename: Vec<RenameActionPredicate>,
 9428    will_rename: Vec<RenameActionPredicate>,
 9429}
 9430
 9431impl RenamePathsWatchedForServer {
 9432    fn with_did_rename_patterns(
 9433        mut self,
 9434        did_rename: Option<&FileOperationRegistrationOptions>,
 9435    ) -> Self {
 9436        if let Some(did_rename) = did_rename {
 9437            self.did_rename = did_rename
 9438                .filters
 9439                .iter()
 9440                .filter_map(|filter| filter.try_into().log_err())
 9441                .collect();
 9442        }
 9443        self
 9444    }
 9445    fn with_will_rename_patterns(
 9446        mut self,
 9447        will_rename: Option<&FileOperationRegistrationOptions>,
 9448    ) -> Self {
 9449        if let Some(will_rename) = will_rename {
 9450            self.will_rename = will_rename
 9451                .filters
 9452                .iter()
 9453                .filter_map(|filter| filter.try_into().log_err())
 9454                .collect();
 9455        }
 9456        self
 9457    }
 9458
 9459    fn should_send_did_rename(&self, path: &str, is_dir: bool) -> bool {
 9460        self.did_rename.iter().any(|pred| pred.eval(path, is_dir))
 9461    }
 9462    fn should_send_will_rename(&self, path: &str, is_dir: bool) -> bool {
 9463        self.will_rename.iter().any(|pred| pred.eval(path, is_dir))
 9464    }
 9465}
 9466
 9467impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
 9468    type Error = globset::Error;
 9469    fn try_from(ops: &FileOperationFilter) -> Result<Self, globset::Error> {
 9470        Ok(Self {
 9471            kind: ops.pattern.matches.clone(),
 9472            glob: GlobBuilder::new(&ops.pattern.glob)
 9473                .case_insensitive(
 9474                    ops.pattern
 9475                        .options
 9476                        .as_ref()
 9477                        .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
 9478                )
 9479                .build()?
 9480                .compile_matcher(),
 9481        })
 9482    }
 9483}
 9484struct RenameActionPredicate {
 9485    glob: GlobMatcher,
 9486    kind: Option<FileOperationPatternKind>,
 9487}
 9488
 9489impl RenameActionPredicate {
 9490    // Returns true if language server should be notified
 9491    fn eval(&self, path: &str, is_dir: bool) -> bool {
 9492        self.kind.as_ref().map_or(true, |kind| {
 9493            let expected_kind = if is_dir {
 9494                FileOperationPatternKind::Folder
 9495            } else {
 9496                FileOperationPatternKind::File
 9497            };
 9498            kind == &expected_kind
 9499        }) && self.glob.is_match(path)
 9500    }
 9501}
 9502
 9503#[derive(Default)]
 9504struct LanguageServerWatchedPaths {
 9505    worktree_paths: HashMap<WorktreeId, GlobSet>,
 9506    abs_paths: HashMap<Arc<Path>, (GlobSet, Task<()>)>,
 9507}
 9508
 9509#[derive(Default)]
 9510struct LanguageServerWatchedPathsBuilder {
 9511    worktree_paths: HashMap<WorktreeId, GlobSet>,
 9512    abs_paths: HashMap<Arc<Path>, GlobSet>,
 9513}
 9514
 9515impl LanguageServerWatchedPathsBuilder {
 9516    fn watch_worktree(&mut self, worktree_id: WorktreeId, glob_set: GlobSet) {
 9517        self.worktree_paths.insert(worktree_id, glob_set);
 9518    }
 9519    fn watch_abs_path(&mut self, path: Arc<Path>, glob_set: GlobSet) {
 9520        self.abs_paths.insert(path, glob_set);
 9521    }
 9522    fn build(
 9523        self,
 9524        fs: Arc<dyn Fs>,
 9525        language_server_id: LanguageServerId,
 9526        cx: &mut Context<LspStore>,
 9527    ) -> LanguageServerWatchedPaths {
 9528        let project = cx.weak_entity();
 9529
 9530        const LSP_ABS_PATH_OBSERVE: Duration = Duration::from_millis(100);
 9531        let abs_paths = self
 9532            .abs_paths
 9533            .into_iter()
 9534            .map(|(abs_path, globset)| {
 9535                let task = cx.spawn({
 9536                    let abs_path = abs_path.clone();
 9537                    let fs = fs.clone();
 9538
 9539                    let lsp_store = project.clone();
 9540                    async move |_, cx| {
 9541                        maybe!(async move {
 9542                            let mut push_updates = fs.watch(&abs_path, LSP_ABS_PATH_OBSERVE).await;
 9543                            while let Some(update) = push_updates.0.next().await {
 9544                                let action = lsp_store
 9545                                    .update(cx, |this, _| {
 9546                                        let Some(local) = this.as_local() else {
 9547                                            return ControlFlow::Break(());
 9548                                        };
 9549                                        let Some(watcher) = local
 9550                                            .language_server_watched_paths
 9551                                            .get(&language_server_id)
 9552                                        else {
 9553                                            return ControlFlow::Break(());
 9554                                        };
 9555                                        let (globs, _) = watcher.abs_paths.get(&abs_path).expect(
 9556                                            "Watched abs path is not registered with a watcher",
 9557                                        );
 9558                                        let matching_entries = update
 9559                                            .into_iter()
 9560                                            .filter(|event| globs.is_match(&event.path))
 9561                                            .collect::<Vec<_>>();
 9562                                        this.lsp_notify_abs_paths_changed(
 9563                                            language_server_id,
 9564                                            matching_entries,
 9565                                        );
 9566                                        ControlFlow::Continue(())
 9567                                    })
 9568                                    .ok()?;
 9569
 9570                                if action.is_break() {
 9571                                    break;
 9572                                }
 9573                            }
 9574                            Some(())
 9575                        })
 9576                        .await;
 9577                    }
 9578                });
 9579                (abs_path, (globset, task))
 9580            })
 9581            .collect();
 9582        LanguageServerWatchedPaths {
 9583            worktree_paths: self.worktree_paths,
 9584            abs_paths,
 9585        }
 9586    }
 9587}
 9588
 9589struct LspBufferSnapshot {
 9590    version: i32,
 9591    snapshot: TextBufferSnapshot,
 9592}
 9593
 9594/// A prompt requested by LSP server.
 9595#[derive(Clone, Debug)]
 9596pub struct LanguageServerPromptRequest {
 9597    pub level: PromptLevel,
 9598    pub message: String,
 9599    pub actions: Vec<MessageActionItem>,
 9600    pub lsp_name: String,
 9601    pub(crate) response_channel: Sender<MessageActionItem>,
 9602}
 9603
 9604impl LanguageServerPromptRequest {
 9605    pub async fn respond(self, index: usize) -> Option<()> {
 9606        if let Some(response) = self.actions.into_iter().nth(index) {
 9607            self.response_channel.send(response).await.ok()
 9608        } else {
 9609            None
 9610        }
 9611    }
 9612}
 9613impl PartialEq for LanguageServerPromptRequest {
 9614    fn eq(&self, other: &Self) -> bool {
 9615        self.message == other.message && self.actions == other.actions
 9616    }
 9617}
 9618
 9619#[derive(Clone, Debug, PartialEq)]
 9620pub enum LanguageServerLogType {
 9621    Log(MessageType),
 9622    Trace(Option<String>),
 9623}
 9624
 9625impl LanguageServerLogType {
 9626    pub fn to_proto(&self) -> proto::language_server_log::LogType {
 9627        match self {
 9628            Self::Log(log_type) => {
 9629                let message_type = match *log_type {
 9630                    MessageType::ERROR => 1,
 9631                    MessageType::WARNING => 2,
 9632                    MessageType::INFO => 3,
 9633                    MessageType::LOG => 4,
 9634                    other => {
 9635                        log::warn!("Unknown lsp log message type: {:?}", other);
 9636                        4
 9637                    }
 9638                };
 9639                proto::language_server_log::LogType::LogMessageType(message_type)
 9640            }
 9641            Self::Trace(message) => {
 9642                proto::language_server_log::LogType::LogTrace(proto::LspLogTrace {
 9643                    message: message.clone(),
 9644                })
 9645            }
 9646        }
 9647    }
 9648
 9649    pub fn from_proto(log_type: proto::language_server_log::LogType) -> Self {
 9650        match log_type {
 9651            proto::language_server_log::LogType::LogMessageType(message_type) => {
 9652                Self::Log(match message_type {
 9653                    1 => MessageType::ERROR,
 9654                    2 => MessageType::WARNING,
 9655                    3 => MessageType::INFO,
 9656                    4 => MessageType::LOG,
 9657                    _ => MessageType::LOG,
 9658                })
 9659            }
 9660            proto::language_server_log::LogType::LogTrace(trace) => Self::Trace(trace.message),
 9661        }
 9662    }
 9663}
 9664
 9665pub enum LanguageServerState {
 9666    Starting {
 9667        startup: Task<Option<Arc<LanguageServer>>>,
 9668        /// List of language servers that will be added to the workspace once it's initialization completes.
 9669        pending_workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
 9670    },
 9671
 9672    Running {
 9673        adapter: Arc<CachedLspAdapter>,
 9674        server: Arc<LanguageServer>,
 9675        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 9676    },
 9677}
 9678
 9679impl LanguageServerState {
 9680    fn add_workspace_folder(&self, uri: Url) {
 9681        match self {
 9682            LanguageServerState::Starting {
 9683                pending_workspace_folders,
 9684                ..
 9685            } => {
 9686                pending_workspace_folders.lock().insert(uri);
 9687            }
 9688            LanguageServerState::Running { server, .. } => {
 9689                server.add_workspace_folder(uri);
 9690            }
 9691        }
 9692    }
 9693    fn _remove_workspace_folder(&self, uri: Url) {
 9694        match self {
 9695            LanguageServerState::Starting {
 9696                pending_workspace_folders,
 9697                ..
 9698            } => {
 9699                pending_workspace_folders.lock().remove(&uri);
 9700            }
 9701            LanguageServerState::Running { server, .. } => server.remove_workspace_folder(uri),
 9702        }
 9703    }
 9704    fn running(
 9705        workspace_folders: BTreeSet<Url>,
 9706        adapter: Arc<CachedLspAdapter>,
 9707        server: Arc<LanguageServer>,
 9708        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 9709    ) -> Self {
 9710        server.set_workspace_folders(workspace_folders);
 9711        Self::Running {
 9712            adapter,
 9713            server,
 9714            simulate_disk_based_diagnostics_completion,
 9715        }
 9716    }
 9717}
 9718
 9719impl std::fmt::Debug for LanguageServerState {
 9720    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 9721        match self {
 9722            LanguageServerState::Starting { .. } => {
 9723                f.debug_struct("LanguageServerState::Starting").finish()
 9724            }
 9725            LanguageServerState::Running { .. } => {
 9726                f.debug_struct("LanguageServerState::Running").finish()
 9727            }
 9728        }
 9729    }
 9730}
 9731
 9732#[derive(Clone, Debug, Serialize)]
 9733pub struct LanguageServerProgress {
 9734    pub is_disk_based_diagnostics_progress: bool,
 9735    pub is_cancellable: bool,
 9736    pub title: Option<String>,
 9737    pub message: Option<String>,
 9738    pub percentage: Option<usize>,
 9739    #[serde(skip_serializing)]
 9740    pub last_update_at: Instant,
 9741}
 9742
 9743#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 9744pub struct DiagnosticSummary {
 9745    pub error_count: usize,
 9746    pub warning_count: usize,
 9747}
 9748
 9749impl DiagnosticSummary {
 9750    pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 9751        let mut this = Self {
 9752            error_count: 0,
 9753            warning_count: 0,
 9754        };
 9755
 9756        for entry in diagnostics {
 9757            if entry.diagnostic.is_primary {
 9758                match entry.diagnostic.severity {
 9759                    DiagnosticSeverity::ERROR => this.error_count += 1,
 9760                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 9761                    _ => {}
 9762                }
 9763            }
 9764        }
 9765
 9766        this
 9767    }
 9768
 9769    pub fn is_empty(&self) -> bool {
 9770        self.error_count == 0 && self.warning_count == 0
 9771    }
 9772
 9773    pub fn to_proto(
 9774        &self,
 9775        language_server_id: LanguageServerId,
 9776        path: &Path,
 9777    ) -> proto::DiagnosticSummary {
 9778        proto::DiagnosticSummary {
 9779            path: path.to_proto(),
 9780            language_server_id: language_server_id.0 as u64,
 9781            error_count: self.error_count as u32,
 9782            warning_count: self.warning_count as u32,
 9783        }
 9784    }
 9785}
 9786
 9787#[derive(Clone, Debug)]
 9788pub enum CompletionDocumentation {
 9789    /// There is no documentation for this completion.
 9790    Undocumented,
 9791    /// A single line of documentation.
 9792    SingleLine(SharedString),
 9793    /// Multiple lines of plain text documentation.
 9794    MultiLinePlainText(SharedString),
 9795    /// Markdown documentation.
 9796    MultiLineMarkdown(SharedString),
 9797}
 9798
 9799impl From<lsp::Documentation> for CompletionDocumentation {
 9800    fn from(docs: lsp::Documentation) -> Self {
 9801        match docs {
 9802            lsp::Documentation::String(text) => {
 9803                if text.lines().count() <= 1 {
 9804                    CompletionDocumentation::SingleLine(text.into())
 9805                } else {
 9806                    CompletionDocumentation::MultiLinePlainText(text.into())
 9807                }
 9808            }
 9809
 9810            lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value }) => match kind {
 9811                lsp::MarkupKind::PlainText => {
 9812                    if value.lines().count() <= 1 {
 9813                        CompletionDocumentation::SingleLine(value.into())
 9814                    } else {
 9815                        CompletionDocumentation::MultiLinePlainText(value.into())
 9816                    }
 9817                }
 9818
 9819                lsp::MarkupKind::Markdown => {
 9820                    CompletionDocumentation::MultiLineMarkdown(value.into())
 9821                }
 9822            },
 9823        }
 9824    }
 9825}
 9826
 9827fn glob_literal_prefix(glob: &Path) -> PathBuf {
 9828    glob.components()
 9829        .take_while(|component| match component {
 9830            path::Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '{', '}']),
 9831            _ => true,
 9832        })
 9833        .collect()
 9834}
 9835
 9836pub struct SshLspAdapter {
 9837    name: LanguageServerName,
 9838    binary: LanguageServerBinary,
 9839    initialization_options: Option<String>,
 9840    code_action_kinds: Option<Vec<CodeActionKind>>,
 9841}
 9842
 9843impl SshLspAdapter {
 9844    pub fn new(
 9845        name: LanguageServerName,
 9846        binary: LanguageServerBinary,
 9847        initialization_options: Option<String>,
 9848        code_action_kinds: Option<String>,
 9849    ) -> Self {
 9850        Self {
 9851            name,
 9852            binary,
 9853            initialization_options,
 9854            code_action_kinds: code_action_kinds
 9855                .as_ref()
 9856                .and_then(|c| serde_json::from_str(c).ok()),
 9857        }
 9858    }
 9859}
 9860
 9861#[async_trait(?Send)]
 9862impl LspAdapter for SshLspAdapter {
 9863    fn name(&self) -> LanguageServerName {
 9864        self.name.clone()
 9865    }
 9866
 9867    async fn initialization_options(
 9868        self: Arc<Self>,
 9869        _: &dyn Fs,
 9870        _: &Arc<dyn LspAdapterDelegate>,
 9871    ) -> Result<Option<serde_json::Value>> {
 9872        let Some(options) = &self.initialization_options else {
 9873            return Ok(None);
 9874        };
 9875        let result = serde_json::from_str(options)?;
 9876        Ok(result)
 9877    }
 9878
 9879    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 9880        self.code_action_kinds.clone()
 9881    }
 9882
 9883    async fn check_if_user_installed(
 9884        &self,
 9885        _: &dyn LspAdapterDelegate,
 9886        _: Arc<dyn LanguageToolchainStore>,
 9887        _: &AsyncApp,
 9888    ) -> Option<LanguageServerBinary> {
 9889        Some(self.binary.clone())
 9890    }
 9891
 9892    async fn cached_server_binary(
 9893        &self,
 9894        _: PathBuf,
 9895        _: &dyn LspAdapterDelegate,
 9896    ) -> Option<LanguageServerBinary> {
 9897        None
 9898    }
 9899
 9900    async fn fetch_latest_server_version(
 9901        &self,
 9902        _: &dyn LspAdapterDelegate,
 9903    ) -> Result<Box<dyn 'static + Send + Any>> {
 9904        anyhow::bail!("SshLspAdapter does not support fetch_latest_server_version")
 9905    }
 9906
 9907    async fn fetch_server_binary(
 9908        &self,
 9909        _: Box<dyn 'static + Send + Any>,
 9910        _: PathBuf,
 9911        _: &dyn LspAdapterDelegate,
 9912    ) -> Result<LanguageServerBinary> {
 9913        anyhow::bail!("SshLspAdapter does not support fetch_server_binary")
 9914    }
 9915}
 9916
 9917pub fn language_server_settings<'a>(
 9918    delegate: &'a dyn LspAdapterDelegate,
 9919    language: &LanguageServerName,
 9920    cx: &'a App,
 9921) -> Option<&'a LspSettings> {
 9922    language_server_settings_for(
 9923        SettingsLocation {
 9924            worktree_id: delegate.worktree_id(),
 9925            path: delegate.worktree_root_path(),
 9926        },
 9927        language,
 9928        cx,
 9929    )
 9930}
 9931
 9932pub(crate) fn language_server_settings_for<'a>(
 9933    location: SettingsLocation<'a>,
 9934    language: &LanguageServerName,
 9935    cx: &'a App,
 9936) -> Option<&'a LspSettings> {
 9937    ProjectSettings::get(Some(location), cx).lsp.get(language)
 9938}
 9939
 9940pub struct LocalLspAdapterDelegate {
 9941    lsp_store: WeakEntity<LspStore>,
 9942    worktree: worktree::Snapshot,
 9943    fs: Arc<dyn Fs>,
 9944    http_client: Arc<dyn HttpClient>,
 9945    language_registry: Arc<LanguageRegistry>,
 9946    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
 9947}
 9948
 9949impl LocalLspAdapterDelegate {
 9950    pub fn new(
 9951        language_registry: Arc<LanguageRegistry>,
 9952        environment: &Entity<ProjectEnvironment>,
 9953        lsp_store: WeakEntity<LspStore>,
 9954        worktree: &Entity<Worktree>,
 9955        http_client: Arc<dyn HttpClient>,
 9956        fs: Arc<dyn Fs>,
 9957        cx: &mut App,
 9958    ) -> Arc<Self> {
 9959        let load_shell_env_task = environment.update(cx, |env, cx| {
 9960            env.get_worktree_environment(worktree.clone(), cx)
 9961        });
 9962
 9963        Arc::new(Self {
 9964            lsp_store,
 9965            worktree: worktree.read(cx).snapshot(),
 9966            fs,
 9967            http_client,
 9968            language_registry,
 9969            load_shell_env_task,
 9970        })
 9971    }
 9972
 9973    fn from_local_lsp(
 9974        local: &LocalLspStore,
 9975        worktree: &Entity<Worktree>,
 9976        cx: &mut App,
 9977    ) -> Arc<Self> {
 9978        Self::new(
 9979            local.languages.clone(),
 9980            &local.environment,
 9981            local.weak.clone(),
 9982            worktree,
 9983            local.http_client.clone(),
 9984            local.fs.clone(),
 9985            cx,
 9986        )
 9987    }
 9988}
 9989
 9990#[async_trait]
 9991impl LspAdapterDelegate for LocalLspAdapterDelegate {
 9992    fn show_notification(&self, message: &str, cx: &mut App) {
 9993        self.lsp_store
 9994            .update(cx, |_, cx| {
 9995                cx.emit(LspStoreEvent::Notification(message.to_owned()))
 9996            })
 9997            .ok();
 9998    }
 9999
10000    fn http_client(&self) -> Arc<dyn HttpClient> {
10001        self.http_client.clone()
10002    }
10003
10004    fn worktree_id(&self) -> WorktreeId {
10005        self.worktree.id()
10006    }
10007
10008    fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool {
10009        self.worktree.entry_for_path(path).map_or(false, |entry| {
10010            is_dir.map_or(true, |is_required_to_be_dir| {
10011                is_required_to_be_dir == entry.is_dir()
10012            })
10013        })
10014    }
10015
10016    fn worktree_root_path(&self) -> &Path {
10017        self.worktree.abs_path().as_ref()
10018    }
10019
10020    async fn shell_env(&self) -> HashMap<String, String> {
10021        let task = self.load_shell_env_task.clone();
10022        task.await.unwrap_or_default()
10023    }
10024
10025    async fn npm_package_installed_version(
10026        &self,
10027        package_name: &str,
10028    ) -> Result<Option<(PathBuf, String)>> {
10029        let local_package_directory = self.worktree_root_path();
10030        let node_modules_directory = local_package_directory.join("node_modules");
10031
10032        if let Some(version) =
10033            read_package_installed_version(node_modules_directory.clone(), package_name).await?
10034        {
10035            return Ok(Some((node_modules_directory, version)));
10036        }
10037        let Some(npm) = self.which("npm".as_ref()).await else {
10038            log::warn!(
10039                "Failed to find npm executable for {:?}",
10040                local_package_directory
10041            );
10042            return Ok(None);
10043        };
10044
10045        let env = self.shell_env().await;
10046        let output = util::command::new_smol_command(&npm)
10047            .args(["root", "-g"])
10048            .envs(env)
10049            .current_dir(local_package_directory)
10050            .output()
10051            .await?;
10052        let global_node_modules =
10053            PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
10054
10055        if let Some(version) =
10056            read_package_installed_version(global_node_modules.clone(), package_name).await?
10057        {
10058            return Ok(Some((global_node_modules, version)));
10059        }
10060        return Ok(None);
10061    }
10062
10063    #[cfg(not(target_os = "windows"))]
10064    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10065        let worktree_abs_path = self.worktree.abs_path();
10066        let shell_path = self.shell_env().await.get("PATH").cloned();
10067        which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
10068    }
10069
10070    #[cfg(target_os = "windows")]
10071    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10072        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10073        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10074        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10075        which::which(command).ok()
10076    }
10077
10078    async fn try_exec(&self, command: LanguageServerBinary) -> Result<()> {
10079        let working_dir = self.worktree_root_path();
10080        let output = util::command::new_smol_command(&command.path)
10081            .args(command.arguments)
10082            .envs(command.env.clone().unwrap_or_default())
10083            .current_dir(working_dir)
10084            .output()
10085            .await?;
10086
10087        if output.status.success() {
10088            return Ok(());
10089        }
10090        Err(anyhow!(
10091            "{}, stdout: {:?}, stderr: {:?}",
10092            output.status,
10093            String::from_utf8_lossy(&output.stdout),
10094            String::from_utf8_lossy(&output.stderr)
10095        ))
10096    }
10097
10098    fn update_status(&self, server_name: LanguageServerName, status: language::BinaryStatus) {
10099        self.language_registry
10100            .update_lsp_status(server_name, status);
10101    }
10102
10103    fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>> {
10104        self.language_registry
10105            .all_lsp_adapters()
10106            .into_iter()
10107            .map(|adapter| adapter.adapter.clone() as Arc<dyn LspAdapter>)
10108            .collect()
10109    }
10110
10111    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>> {
10112        let dir = self.language_registry.language_server_download_dir(name)?;
10113
10114        if !dir.exists() {
10115            smol::fs::create_dir_all(&dir)
10116                .await
10117                .context("failed to create container directory")
10118                .log_err()?;
10119        }
10120
10121        Some(dir)
10122    }
10123
10124    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10125        let entry = self
10126            .worktree
10127            .entry_for_path(&path)
10128            .with_context(|| format!("no worktree entry for path {path:?}"))?;
10129        let abs_path = self
10130            .worktree
10131            .absolutize(&entry.path)
10132            .with_context(|| format!("cannot absolutize path {path:?}"))?;
10133
10134        self.fs.load(&abs_path).await
10135    }
10136}
10137
10138async fn populate_labels_for_symbols(
10139    symbols: Vec<CoreSymbol>,
10140    language_registry: &Arc<LanguageRegistry>,
10141    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10142    output: &mut Vec<Symbol>,
10143) {
10144    #[allow(clippy::mutable_key_type)]
10145    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10146
10147    let mut unknown_paths = BTreeSet::new();
10148    for symbol in symbols {
10149        let language = language_registry
10150            .language_for_file_path(&symbol.path.path)
10151            .await
10152            .ok()
10153            .or_else(|| {
10154                unknown_paths.insert(symbol.path.path.clone());
10155                None
10156            });
10157        symbols_by_language
10158            .entry(language)
10159            .or_default()
10160            .push(symbol);
10161    }
10162
10163    for unknown_path in unknown_paths {
10164        log::info!(
10165            "no language found for symbol path {}",
10166            unknown_path.display()
10167        );
10168    }
10169
10170    let mut label_params = Vec::new();
10171    for (language, mut symbols) in symbols_by_language {
10172        label_params.clear();
10173        label_params.extend(
10174            symbols
10175                .iter_mut()
10176                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10177        );
10178
10179        let mut labels = Vec::new();
10180        if let Some(language) = language {
10181            let lsp_adapter = lsp_adapter.clone().or_else(|| {
10182                language_registry
10183                    .lsp_adapters(&language.name())
10184                    .first()
10185                    .cloned()
10186            });
10187            if let Some(lsp_adapter) = lsp_adapter {
10188                labels = lsp_adapter
10189                    .labels_for_symbols(&label_params, &language)
10190                    .await
10191                    .log_err()
10192                    .unwrap_or_default();
10193            }
10194        }
10195
10196        for ((symbol, (name, _)), label) in symbols
10197            .into_iter()
10198            .zip(label_params.drain(..))
10199            .zip(labels.into_iter().chain(iter::repeat(None)))
10200        {
10201            output.push(Symbol {
10202                language_server_name: symbol.language_server_name,
10203                source_worktree_id: symbol.source_worktree_id,
10204                source_language_server_id: symbol.source_language_server_id,
10205                path: symbol.path,
10206                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10207                name,
10208                kind: symbol.kind,
10209                range: symbol.range,
10210                signature: symbol.signature,
10211            });
10212        }
10213    }
10214}
10215
10216fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
10217    match server.capabilities().text_document_sync.as_ref()? {
10218        lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
10219            lsp::TextDocumentSyncKind::NONE => None,
10220            lsp::TextDocumentSyncKind::FULL => Some(true),
10221            lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
10222            _ => None,
10223        },
10224        lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
10225            lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
10226                if *supported {
10227                    Some(true)
10228                } else {
10229                    None
10230                }
10231            }
10232            lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
10233                Some(save_options.include_text.unwrap_or(false))
10234            }
10235        },
10236    }
10237}
10238
10239/// Completion items are displayed in a `UniformList`.
10240/// Usually, those items are single-line strings, but in LSP responses,
10241/// completion items `label`, `detail` and `label_details.description` may contain newlines or long spaces.
10242/// Many language plugins construct these items by joining these parts together, and we may use `CodeLabel::fallback_for_completion` that uses `label` at least.
10243/// 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,
10244/// breaking the completions menu presentation.
10245///
10246/// 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.
10247fn ensure_uniform_list_compatible_label(label: &mut CodeLabel) {
10248    let mut new_text = String::with_capacity(label.text.len());
10249    let mut offset_map = vec![0; label.text.len() + 1];
10250    let mut last_char_was_space = false;
10251    let mut new_idx = 0;
10252    let mut chars = label.text.char_indices().fuse();
10253    let mut newlines_removed = false;
10254
10255    while let Some((idx, c)) = chars.next() {
10256        offset_map[idx] = new_idx;
10257
10258        match c {
10259            '\n' if last_char_was_space => {
10260                newlines_removed = true;
10261            }
10262            '\t' | ' ' if last_char_was_space => {}
10263            '\n' if !last_char_was_space => {
10264                new_text.push(' ');
10265                new_idx += 1;
10266                last_char_was_space = true;
10267                newlines_removed = true;
10268            }
10269            ' ' | '\t' => {
10270                new_text.push(' ');
10271                new_idx += 1;
10272                last_char_was_space = true;
10273            }
10274            _ => {
10275                new_text.push(c);
10276                new_idx += c.len_utf8();
10277                last_char_was_space = false;
10278            }
10279        }
10280    }
10281    offset_map[label.text.len()] = new_idx;
10282
10283    // Only modify the label if newlines were removed.
10284    if !newlines_removed {
10285        return;
10286    }
10287
10288    let last_index = new_idx;
10289    let mut run_ranges_errors = Vec::new();
10290    label.runs.retain_mut(|(range, _)| {
10291        match offset_map.get(range.start) {
10292            Some(&start) => range.start = start,
10293            None => {
10294                run_ranges_errors.push(range.clone());
10295                return false;
10296            }
10297        }
10298
10299        match offset_map.get(range.end) {
10300            Some(&end) => range.end = end,
10301            None => {
10302                run_ranges_errors.push(range.clone());
10303                range.end = last_index;
10304            }
10305        }
10306        true
10307    });
10308    if !run_ranges_errors.is_empty() {
10309        log::error!(
10310            "Completion label has errors in its run ranges: {run_ranges_errors:?}, label text: {}",
10311            label.text
10312        );
10313    }
10314
10315    let mut wrong_filter_range = None;
10316    if label.filter_range == (0..label.text.len()) {
10317        label.filter_range = 0..new_text.len();
10318    } else {
10319        let mut original_filter_range = Some(label.filter_range.clone());
10320        match offset_map.get(label.filter_range.start) {
10321            Some(&start) => label.filter_range.start = start,
10322            None => {
10323                wrong_filter_range = original_filter_range.take();
10324                label.filter_range.start = last_index;
10325            }
10326        }
10327
10328        match offset_map.get(label.filter_range.end) {
10329            Some(&end) => label.filter_range.end = end,
10330            None => {
10331                wrong_filter_range = original_filter_range.take();
10332                label.filter_range.end = last_index;
10333            }
10334        }
10335    }
10336    if let Some(wrong_filter_range) = wrong_filter_range {
10337        log::error!(
10338            "Completion label has an invalid filter range: {wrong_filter_range:?}, label text: {}",
10339            label.text
10340        );
10341    }
10342
10343    label.text = new_text;
10344}
10345
10346#[cfg(test)]
10347mod tests {
10348    use language::HighlightId;
10349
10350    use super::*;
10351
10352    #[test]
10353    fn test_glob_literal_prefix() {
10354        assert_eq!(glob_literal_prefix(Path::new("**/*.js")), Path::new(""));
10355        assert_eq!(
10356            glob_literal_prefix(Path::new("node_modules/**/*.js")),
10357            Path::new("node_modules")
10358        );
10359        assert_eq!(
10360            glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10361            Path::new("foo")
10362        );
10363        assert_eq!(
10364            glob_literal_prefix(Path::new("foo/bar/baz.js")),
10365            Path::new("foo/bar/baz.js")
10366        );
10367
10368        #[cfg(target_os = "windows")]
10369        {
10370            assert_eq!(glob_literal_prefix(Path::new("**\\*.js")), Path::new(""));
10371            assert_eq!(
10372                glob_literal_prefix(Path::new("node_modules\\**/*.js")),
10373                Path::new("node_modules")
10374            );
10375            assert_eq!(
10376                glob_literal_prefix(Path::new("foo/{bar,baz}.js")),
10377                Path::new("foo")
10378            );
10379            assert_eq!(
10380                glob_literal_prefix(Path::new("foo\\bar\\baz.js")),
10381                Path::new("foo/bar/baz.js")
10382            );
10383        }
10384    }
10385
10386    #[test]
10387    fn test_multi_len_chars_normalization() {
10388        let mut label = CodeLabel {
10389            text: "myElˇ (parameter) myElˇ: {\n    foo: string;\n}".to_string(),
10390            runs: vec![(0..6, HighlightId(1))],
10391            filter_range: 0..6,
10392        };
10393        ensure_uniform_list_compatible_label(&mut label);
10394        assert_eq!(
10395            label,
10396            CodeLabel {
10397                text: "myElˇ (parameter) myElˇ: { foo: string; }".to_string(),
10398                runs: vec![(0..6, HighlightId(1))],
10399                filter_range: 0..6,
10400            }
10401        );
10402    }
10403}