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