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