lsp_store.rs

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