lsp_store.rs

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