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