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