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