lsp_store.rs

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