lsp_store.rs

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