lsp_store.rs

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