lsp_store.rs

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