lsp_store.rs

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