lsp_store.rs

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