lsp_store.rs

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