lsp_store.rs

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