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