Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Properly invalidate LSP data for outdated excerpts (#66264)
Kirill Bulatov1663af412c62
diff --git a/crates/editor/src/code_lens.rs b/crates/editor/src/code_lens.rsindex c1e42961bd4..1f6263b489f 100644--- a/crates/editor/src/code_lens.rs+++ b/crates/editor/src/code_lens.rs@@ -1,7 +1,7 @@use std::sync::Arc;use collections::{HashMap, HashSet};-use futures::{StreamExt as _, future::join_all, stream::FuturesUnordered};+use futures::{StreamExt as _, stream::FuturesUnordered};use gpui::{MouseButton, SharedString, Task, TaskExt, WeakEntity};use itertools::Itertools;use language::{BufferId, ClientCommand};@@ -13,7 +13,7 @@ use text::ToOffset as _;use ui::{Context, Window, div, prelude::*};use crate::{- Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, SelectionEffects,+ Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, LspDataKind, SelectionEffects,actions::ToggleCodeLens,display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},hover_links::HoverLink,@@ -224,72 +224,54 @@ impl Editor {return;};- let buffers_to_query = self- .visible_buffers(cx)- .into_iter()- .filter(|buffer| self.is_lsp_relevant(buffer.read(cx).file(), cx))- .chain(for_buffer.and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id)))- .filter(|editor_buffer| {- let editor_buffer_id = editor_buffer.read(cx).remote_id();- for_buffer.is_none_or(|buffer_id| buffer_id == editor_buffer_id)- && self.registered_buffers.contains_key(&editor_buffer_id)- })- .unique_by(|buffer| buffer.read(cx).remote_id())- .collect::<Vec<_>>();-+ let buffers_to_query = self.lsp_data_buffers(for_buffer, cx);if buffers_to_query.is_empty() {return;}-- let project = project.downgrade();- self.refresh_code_lens_task = cx.spawn(async move |editor, cx| {- cx.background_executor()- .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)- .await;-- let Some(tasks_per_buffer) = project- .update(cx, |project, cx| {- project.lsp_store().update(cx, |lsp_store, cx| {- buffers_to_query- .into_iter()- .map(|buffer| {- let buffer_id = buffer.read(cx).remote_id();- let task = lsp_store.code_lens_actions(&buffer, cx);- async move { (buffer_id, task.await) }+ self.spawn_lsp_data_tasks(+ LspDataKind::CodeLens,+ for_buffer,+ buffers_to_query,+ cx,+ |buffer, cx| {+ let buffer_id = buffer.read(cx).remote_id();+ let project = project.downgrade();+ cx.spawn(async move |editor, cx| {+ cx.background_executor()+ .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)+ .await;++ let Some(task) = project+ .update(cx, |project, cx| {+ project.lsp_store().update(cx, |lsp_store, cx| {+ lsp_store.code_lens_actions(&buffer, cx)})- .collect::<Vec<_>>()- })- })- .ok()- else {- return;- };-- let code_lens_per_buffer = join_all(tasks_per_buffer).await;- if code_lens_per_buffer.is_empty() {- return;- }-- editor- .update(cx, |editor, cx| {- let snapshot = editor.buffer().read(cx).snapshot(cx);- for (buffer_id, result) in code_lens_per_buffer {- let actions = match result {- Ok(Some(actions)) => actions,- Ok(None) => continue,- Err(e) => {- log::error!(- "Failed to fetch code lenses for buffer {buffer_id:?}: {e:#}"- );- continue;- }- };- editor.apply_lens_actions_for_buffer(buffer_id, actions, &snapshot, cx);- }- editor.resolve_visible_code_lenses(cx);+ })+ .ok()+ else {+ return;+ };++ let actions = match task.await {+ Ok(Some(actions)) => actions,+ Ok(None) => return,+ Err(error) => {+ log::error!(+ "Failed to fetch code lenses for buffer {buffer_id:?}: {error:#}"+ );+ return;+ }+ };+ editor+ .update(cx, |editor, cx| {+ let snapshot = editor.buffer().read(cx).snapshot(cx);+ editor.apply_lens_actions_for_buffer(buffer_id, actions, &snapshot, cx);+ editor.resolve_visible_code_lenses(cx);+ })+ .ok();})- .ok();- });+ },+ );}/// Reconcile blocks for `buffer_id` against the latest `actions`.@@ -543,6 +525,46 @@ impl Editor {});}+ pub(super) fn remove_invalid_code_lenses(+ &mut self,+ buffer_ids: &[BufferId],+ buffers_removed: bool,+ snapshot: &MultiBufferSnapshot,+ cx: &mut Context<Self>,+ ) {+ let Some(code_lens) = self.code_lens.as_mut() else {+ return;+ };+ let mut blocks_to_remove = HashSet::default();+ for buffer_id in buffer_ids {+ if snapshot.buffer_for_id(*buffer_id).is_none() {+ code_lens.actions.remove(buffer_id);+ }+ let Some(blocks) = code_lens.blocks.get_mut(buffer_id) else {+ continue;+ };+ blocks.retain(|block| {+ let valid = !buffers_removed+ && block.anchor.raw_text_anchor().is_none_or(|text_anchor| {+ snapshot.anchor_in_excerpt(text_anchor).is_some()+ });+ if !valid {+ blocks_to_remove.insert(block.block_id);+ }+ valid+ });+ if blocks.is_empty() {+ code_lens.blocks.remove(buffer_id);+ }+ }+ if code_lens.actions.is_empty() {+ code_lens.resolve_task = Task::ready(());+ }+ if !blocks_to_remove.is_empty() {+ self.remove_blocks(blocks_to_remove, None, cx);+ }+ }+pub(super) fn clear_code_lenses(&mut self, cx: &mut Context<Self>) {if let Some(code_lens) = self.code_lens.take() {let all_blocks = code_lens@@ -556,7 +578,7 @@ impl Editor {}cx.notify();}- self.refresh_code_lens_task = Task::ready(());+ self.clear_lsp_data_tasks(LspDataKind::CodeLens);}}@@ -723,20 +745,23 @@ mod tests {};use collections::HashSet;- use futures::StreamExt;- use gpui::TestAppContext;+ use futures::{FutureExt as _, StreamExt, channel::oneshot};+ use gpui::{AppContext as _, TestAppContext};use indoc::indoc;+ use language::{Capability, FakeLspAdapter, rust_lang};use settings::CodeLens;use util::path;- use multi_buffer::{MultiBufferRow, ToPoint as _};+ use multi_buffer::{MultiBuffer, MultiBufferRow, PathKey, ToPoint as _};use text::Point;use super::{CODE_LENS_SEPARATOR, displayed_title};use crate::{- Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT,+ DisplayRow, Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT,+ display_map::Block,editor_tests::{init_test, update_test_editor_settings},- test::editor_lsp_test_context::EditorLspTestContext,+ scroll::ScrollAnchor,+ test::{build_editor_with_project, editor_lsp_test_context::EditorLspTestContext},};#[gpui::test]@@ -1837,6 +1862,279 @@ mod tests {HashSet::from_iter([70, 80, 90]),"Only newly visible lenses at the bottom should be resolved, not middle ones");++ editor.update_in(cx, |editor, window, cx| {+ let anchor = editor+ .buffer()+ .read(cx)+ .snapshot(cx)+ .anchor_before(Point::new(50, 0));+ editor.set_scroll_anchor_remote(+ ScrollAnchor {+ offset: gpui::Point::default(),+ anchor,+ },+ window,+ cx,+ );+ });+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();++ let after_remote_scroll_resolved = resolved_lines+ .lock()+ .unwrap()+ .drain(..)+ .collect::<HashSet<_>>();+ assert_eq!(after_remote_scroll_resolved, HashSet::from_iter([50, 60]));+ }++ #[gpui::test]+ async fn test_code_lens_multibuffer_excerpt_changes(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ update_test_editor_settings(cx, &|settings| {+ settings.code_lens = Some(CodeLens::On);+ });++ let fs = project::FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/dir"),+ serde_json::json!({+ "a.rs": "fn first() {}\nfn second() {}\nfn third() {}",+ "b.rs": "fn first() {}\nfn second() {}\nfn third() {}",+ }),+ )+ .await;+ let project = project::Project::test(fs, [path!("/dir").as_ref()], cx).await;+ let languages = project.read_with(cx, |project, _| project.languages().clone());+ languages.add(rust_lang());+ let (resolve_sender, resolve_receiver) = oneshot::channel::<()>();+ let resolve_receiver = resolve_receiver.shared();+ let mut servers = languages.register_fake_lsp(+ "Rust",+ FakeLspAdapter {+ capabilities: lsp::ServerCapabilities {+ code_lens_provider: Some(lsp::CodeLensOptions {+ resolve_provider: Some(true),+ }),+ ..lsp::ServerCapabilities::default()+ },+ initializer: Some(Box::new(move |server| {+ server.set_request_handler::<lsp::request::CodeLensRequest, _, _>(+ |_, _| async move {+ Ok(Some(+ (0..3)+ .map(|row| lsp::CodeLens {+ range: lsp::Range::new(+ lsp::Position::new(row, 0),+ lsp::Position::new(row, 10),+ ),+ command: (row != 1).then(|| lsp::Command {+ title: format!("row {row} references"),+ command: "references".to_owned(),+ arguments: None,+ }),+ data: None,+ })+ .collect(),+ ))+ },+ );+ let resolve_receiver = resolve_receiver.clone();+ server.set_request_handler::<lsp::request::CodeLensResolve, _, _>(+ move |lens, _| {+ let resolve_receiver = resolve_receiver.clone();+ async move {+ resolve_receiver.await.unwrap();+ Ok(lens)+ }+ },+ );+ })),+ ..FakeLspAdapter::default()+ },+ );+ let first_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();+ let second_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/b.rs"), cx)+ })+ .await+ .unwrap();+ let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));+ let (editor, cx) = cx.add_window_view(|window, cx| {+ build_editor_with_project(project, multibuffer.clone(), window, cx)+ });+ multibuffer.update(cx, |multibuffer, cx| {+ for (index, buffer) in [&first_buffer, &second_buffer].into_iter().enumerate() {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(index as u64),+ buffer.clone(),+ [Point::new(0, 0)..Point::new(2, 13)],+ 0,+ cx,+ );+ }+ });+ let _server = servers.next().await.unwrap();+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(+ code_lens_assertion_text(editor, cx),+ indoc! {"+ Lenses: row 0 references+ Line 1: fn first() {}++ Lenses: <placeholder>+ Line 2: fn second() {}++ Lenses: row 2 references+ Line 3: fn third() {}++ Lenses: row 0 references+ Line 4: fn first() {}++ Lenses: <placeholder>+ Line 5: fn second() {}++ Lenses: row 2 references+ Line 6: fn third() {}+ "},+ );+ assert_code_lens_block_count(editor, 6, cx);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(0),+ first_buffer.clone(),+ [Point::new(2, 0)..Point::new(2, 13)],+ 0,+ cx,+ );+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(+ code_lens_assertion_text(editor, cx),+ indoc! {"+ Lenses: row 2 references+ Line 1: fn third() {}++ Lenses: row 0 references+ Line 2: fn first() {}++ Lenses: <placeholder>+ Line 3: fn second() {}++ Lenses: row 2 references+ Line 4: fn third() {}+ "},+ );+ assert_code_lens_block_count(editor, 4, cx);+ });++ resolve_sender.send(()).unwrap();+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(+ code_lens_assertion_text(editor, cx),+ indoc! {"+ Lenses: row 2 references+ Line 1: fn third() {}++ Lenses: row 0 references+ Line 2: fn first() {}++ Lenses: 0 references+ Line 3: fn second() {}++ Lenses: row 2 references+ Line 4: fn third() {}+ "},+ );+ assert_code_lens_block_count(editor, 4, cx);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(2),+ second_buffer.clone(),+ [Point::new(0, 0)..Point::new(2, 13)],+ 0,+ cx,+ );+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_code_lens_block_count(editor, 1, cx);+ });+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_code_lens_block_count(editor, 4, cx);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.remove_excerpts_for_buffer(first_buffer.read(cx).remote_id(), cx);+ });+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_code_lens_block_count(editor, 3, cx);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(0),+ first_buffer.clone(),+ [Point::new(0, 0)..Point::new(2, 13)],+ 0,+ cx,+ );+ });+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_code_lens_block_count(editor, 6, cx);+ });++ multibuffer.update(cx, |multibuffer, cx| multibuffer.clear(cx));+ cx.run_until_parked();+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_code_lens_block_count(editor, 0, cx);+ assert_eq!(editor.code_lens.as_ref().unwrap().actions.len(), 0);+ });+ }++ fn assert_code_lens_block_count(editor: &Editor, expected: usize, cx: &mut ui::App) {+ assert_eq!(+ editor+ .code_lens+ .as_ref()+ .unwrap()+ .blocks+ .values()+ .map(Vec::len)+ .sum::<usize>(),+ expected,+ );+ assert_eq!(+ editor+ .display_snapshot(cx)+ .blocks_in_range(DisplayRow(0)..DisplayRow(u32::MAX))+ .filter(|(_, block)| matches!(block, Block::Custom(_)))+ .count(),+ expected,+ );}fn code_lens_assertion_text(editor: &Editor, cx: &ui::App) -> String {diff --git a/crates/editor/src/diagnostics.rs b/crates/editor/src/diagnostics.rsindex 315ca8ede64..987649907a7 100644--- a/crates/editor/src/diagnostics.rs+++ b/crates/editor/src/diagnostics.rs@@ -544,6 +544,32 @@ impl Editor {});}+ pub(super) fn remove_invalid_inline_diagnostics(+ &mut self,+ buffer_ids: &[BufferId],+ buffers_removed: bool,+ snapshot: &MultiBufferSnapshot,+ cx: &mut Context<Self>,+ ) {+ if self.inline_diagnostics.is_empty() {+ return;+ }+ let buffer_ids = buffer_ids.iter().copied().collect::<HashSet<_>>();+ let previous_len = self.inline_diagnostics.len();+ self.inline_diagnostics.retain(|(anchor, _)| {+ anchor+ .buffer_id()+ .is_none_or(|buffer_id| !buffer_ids.contains(&buffer_id))+ || !buffers_removed+ && anchor+ .raw_text_anchor()+ .is_none_or(|text_anchor| snapshot.anchor_in_excerpt(text_anchor).is_some())+ });+ if self.inline_diagnostics.len() != previous_len {+ cx.notify();+ }+ }+pub(super) fn pull_diagnostics(&mut self,buffer_id: BufferId,@@ -566,23 +592,32 @@ impl Editor {let project = self.project()?.downgrade();let buffer = self.buffer().read(cx).buffer(buffer_id)?;- self.pull_diagnostics_task = cx.spawn(async move |_, cx| {- cx.background_executor().timer(debounce).await;- if let Ok(task) = project.update(cx, |project, cx| {- project.lsp_store().update(cx, |lsp_store, cx| {- lsp_store.pull_diagnostics_for_buffer(buffer, cx)- })- }) {- task.await.log_err();- }- project- .update(cx, |project, cx| {- project.lsp_store().update(cx, |lsp_store, cx| {- lsp_store.pull_document_diagnostics_for_buffer_edit(buffer_id, cx);- })+ self.spawn_lsp_data_tasks(+ LspDataKind::PullDiagnostics,+ Some(buffer_id),+ vec![buffer],+ cx,+ |buffer, cx| {+ let project = project.clone();+ cx.spawn(async move |_, cx| {+ cx.background_executor().timer(debounce).await;+ if let Ok(task) = project.update(cx, |project, cx| {+ project.lsp_store().update(cx, |lsp_store, cx| {+ lsp_store.pull_diagnostics_for_buffer(buffer, cx)+ })+ }) {+ task.await.log_err();+ }+ project+ .update(cx, |project, cx| {+ project.lsp_store().update(cx, |lsp_store, cx| {+ lsp_store.pull_document_diagnostics_for_buffer_edit(buffer_id, cx);+ })+ })+ .log_err();})- .log_err();- });+ },+ );Some(())}@@ -613,18 +648,21 @@ impl Editor {#[cfg(test)]mod tests {use crate::{+ Editor,actions::{ToggleCodeLens, ToggleDiagnostics, ToggleInlayHints, ToggleInlineDiagnostics,ToggleSemanticHighlights,},editor_tests::init_test,- test::editor_test_context::EditorTestContext,+ test::{build_editor_with_project, editor_test_context::EditorTestContext},};- use gpui::{Action, TestAppContext, UpdateGlobal};+ use gpui::{Action, AppContext as _, TestAppContext, UpdateGlobal};use indoc::indoc;- use language::DiagnosticSourceKind;+ use language::{Capability, DiagnosticSourceKind, Point};use lsp::LanguageServerId;- use project::project_settings::DiagnosticSeverity;+ use multi_buffer::{MultiBuffer, PathKey, ToPoint as _};+ use project::{FakeFs, Project, project_settings::DiagnosticSeverity};+ use serde_json::json;use settings::{DelayMs, SettingsStore};use std::sync::{Arc,@@ -917,4 +955,127 @@ mod tests {);});}++ #[gpui::test]+ async fn test_inline_diagnostics_removed_with_excerpts(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ cx.update(|cx| {+ SettingsStore::update_global(cx, |store, cx| {+ store.update_user_settings(cx, |settings| {+ let inline = settings+ .diagnostics+ .get_or_insert_default()+ .inline+ .get_or_insert_default();+ inline.enabled = Some(true);+ inline.update_debounce_ms = Some(DelayMs(0));+ });+ });+ });+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/dir"),+ json!({+ "a.rs": "one\ntwo\nthree",+ "b.rs": "four",+ }),+ )+ .await;+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;+ let first_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();+ let second_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/b.rs"), cx)+ })+ .await+ .unwrap();+ let multibuffer = cx.new(|cx| {+ let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(0),+ first_buffer.clone(),+ [Point::new(0, 0)..Point::new(2, 5)],+ 0,+ cx,+ );+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(1),+ second_buffer.clone(),+ [Point::new(0, 0)..Point::new(0, 4)],+ 0,+ cx,+ );+ multibuffer+ });+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());+ let (editor, cx) = cx.add_window_view(|window, cx| {+ build_editor_with_project(project, multibuffer.clone(), window, cx)+ });+ lsp_store.update(cx, |lsp_store, cx| {+ for (path, row) in [(path!("/dir/a.rs"), 2), (path!("/dir/b.rs"), 0)] {+ lsp_store+ .update_diagnostics(+ LanguageServerId(0),+ lsp::PublishDiagnosticsParams {+ uri: lsp::Uri::from_file_path(path).unwrap(),+ version: None,+ diagnostics: vec![lsp::Diagnostic {+ range: lsp::Range::new(+ lsp::Position::new(row, 0),+ lsp::Position::new(row, 3),+ ),+ severity: Some(lsp::DiagnosticSeverity::ERROR),+ message: lsp::DiagnosticMessage::from(format!("error in {path}")),+ ..lsp::Diagnostic::default()+ }],+ },+ None,+ DiagnosticSourceKind::Pushed,+ &[],+ cx,+ )+ .unwrap();+ }+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(inline_diagnostic_rows(editor, cx), vec![2, 3]);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(0),+ first_buffer.clone(),+ [Point::new(0, 0)..Point::new(0, 3)],+ 0,+ cx,+ );+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(inline_diagnostic_rows(editor, cx), vec![1]);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.remove_excerpts_for_buffer(second_buffer.read(cx).remote_id(), cx);+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(inline_diagnostic_rows(editor, cx), Vec::<u32>::new());+ });+ }++ fn inline_diagnostic_rows(editor: &Editor, cx: &gpui::App) -> Vec<u32> {+ let snapshot = editor.buffer().read(cx).snapshot(cx);+ editor+ .inline_diagnostics+ .iter()+ .map(|(anchor, _)| anchor.to_point(&snapshot).row)+ .collect()+ }}diff --git a/crates/editor/src/document_colors.rs b/crates/editor/src/document_colors.rsindex d413d3c1ca9..cc7619caadc 100644--- a/crates/editor/src/document_colors.rs+++ b/crates/editor/src/document_colors.rs@@ -1,12 +1,10 @@use std::{cmp, ops::Range};use collections::HashMap;-use futures::future::join_all;-use gpui::{Hsla, Rgba};-use itertools::Itertools;-use language::range_from_lsp;-use multi_buffer::Anchor;-use project::{DocumentColor, InlayId};+use gpui::{Entity, Hsla, Rgba, Task, WeakEntity};+use language::{Buffer, range_from_lsp};+use multi_buffer::{Anchor, MultiBufferSnapshot};+use project::{DocumentColor, InlayId, Project};use settings::Settings as _;use text::{Bias, BufferId};use ui::{App, Context, Window};@@ -14,8 +12,8 @@ use util::post_inc;use crate::{DisplayPoint, Editor, EditorSettings, EditorSnapshot, InlaySplice,- LSP_REQUEST_DEBOUNCE_TIMEOUT, RangeToAnchorExt, editor_settings::DocumentColorsRenderMode,- inlays::Inlay,+ LSP_REQUEST_DEBOUNCE_TIMEOUT, LspDataKind, RangeToAnchorExt,+ editor_settings::DocumentColorsRenderMode, inlays::Inlay,};#[derive(Debug)]@@ -109,6 +107,41 @@ impl LspColorData {true}+ fn remove_invalid_colors(+ &mut self,+ buffer_id: BufferId,+ buffers_removed: bool,+ snapshot: &MultiBufferSnapshot,+ ) -> Vec<InlayId> {+ let Some(buffer_colors) = self.buffer_colors.get(&buffer_id) else {+ return Vec::new();+ };+ let (valid_colors, invalid_colors) = buffer_colors+ .colors+ .iter()+ .cloned()+ .partition::<Vec<_>, _>(|(range, _, _)| {+ !buffers_removed+ && [range.start, range.end].iter().all(|anchor| {+ anchor.raw_text_anchor().is_none_or(|text_anchor| {+ snapshot.anchor_in_excerpt(text_anchor).is_some()+ })+ })+ });+ if invalid_colors.is_empty() {+ return Vec::new();+ }+ if valid_colors.is_empty() {+ self.buffer_colors.remove(&buffer_id);+ } else {+ self.set_colors(buffer_id, valid_colors);+ }+ invalid_colors+ .into_iter()+ .map(|(_, _, inlay_id)| inlay_id)+ .collect()+ }+pub fn editor_display_highlights(&self,snapshot: &EditorSnapshot,@@ -159,47 +192,66 @@ impl Editor {return;}- let buffers_to_query = self- .visible_buffers(cx)- .into_iter()- .filter(|buffer| self.is_lsp_relevant(buffer.read(cx).file(), cx))- .chain(buffer_id.and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id)))- .filter(|editor_buffer| {- let editor_buffer_id = editor_buffer.read(cx).remote_id();- buffer_id.is_none_or(|buffer_id| buffer_id == editor_buffer_id)- && self.registered_buffers.contains_key(&editor_buffer_id)+ let project = project.downgrade();+ let buffers_to_query = self.lsp_data_buffers(buffer_id, cx);+ self.spawn_lsp_data_tasks(+ LspDataKind::DocumentColors,+ buffer_id,+ buffers_to_query,+ cx,+ |buffer, cx| Self::fetch_document_colors(project.clone(), buffer, cx),+ );+ }++ pub(super) fn remove_invalid_document_colors(+ &mut self,+ buffer_ids: &[BufferId],+ buffers_removed: bool,+ snapshot: &MultiBufferSnapshot,+ cx: &mut Context<Self>,+ ) {+ let Some(colors) = &mut self.colors else {+ return;+ };+ let invalid_inlays = buffer_ids+ .iter()+ .flat_map(|buffer_id| {+ colors.remove_invalid_colors(*buffer_id, buffers_removed, snapshot)})- .unique_by(|buffer| buffer.read(cx).remote_id()).collect::<Vec<_>>();+ if invalid_inlays.is_empty() {+ return;+ }+ if colors.render_mode == DocumentColorsRenderMode::Inlay {+ self.splice_inlays(&invalid_inlays, Vec::new(), cx);+ }+ cx.notify();+ }- let project = project.downgrade();- self.refresh_colors_task = cx.spawn(async move |editor, cx| {+ fn fetch_document_colors(+ project: WeakEntity<Project>,+ buffer: Entity<Buffer>,+ cx: &mut Context<Self>,+ ) -> Task<()> {+ cx.spawn(async move |editor, cx| {cx.background_executor().timer(LSP_REQUEST_DEBOUNCE_TIMEOUT).await;- let Some(all_colors_task) = project+ let Some((buffer_snapshot, colors_task)) = project.update(cx, |project, cx| {project.lsp_store().update(cx, |lsp_store, cx| {- buffers_to_query- .into_iter()- .filter_map(|buffer| {- let buffer_snapshot = buffer.read(cx).snapshot();- let colors_task = lsp_store.document_colors(buffer, cx)?;- Some(async move { (buffer_snapshot, colors_task.await) })- })- .collect::<Vec<_>>()+ let buffer_snapshot = buffer.read(cx).snapshot();+ Some((buffer_snapshot, lsp_store.document_colors(buffer, cx)?))})}).ok()+ .flatten()else {return;};- let all_colors = join_all(all_colors_task).await;- if all_colors.is_empty() {- return;- }+ let colors = colors_task.await;let Some(multi_buffer_snapshot) = editor.update(cx, |editor, cx| editor.buffer.read(cx).snapshot(cx)).ok()@@ -209,52 +261,49 @@ impl Editor {let mut new_editor_colors: HashMap<BufferId, Vec<(Range<Anchor>, DocumentColor)>> =HashMap::default();- for (buffer_snapshot, colors) in all_colors {- match colors {- Ok(colors) => {- if colors.colors.is_empty() {- new_editor_colors+ match colors {+ Ok(colors) => {+ if colors.colors.is_empty() {+ new_editor_colors+ .entry(buffer_snapshot.remote_id())+ .or_insert_with(Vec::new)+ .clear();+ } else {+ for color in colors.colors {+ let color_range = range_from_lsp(color.lsp_range);+ let color_start = color_range.start;+ let color_end = color_range.end;++ let Some(range) = multi_buffer_snapshot+ .buffer_anchor_range_to_anchor_range(+ buffer_snapshot.anchor_range_outside(+ buffer_snapshot.clip_point_utf16(color_start, Bias::Left)+ ..buffer_snapshot+ .clip_point_utf16(color_end, Bias::Right),+ ),+ )+ else {+ continue;+ };++ let new_buffer_colors = new_editor_colors.entry(buffer_snapshot.remote_id())- .or_insert_with(Vec::new)- .clear();- } else {- for color in colors.colors {- let color_range = range_from_lsp(color.lsp_range);- let color_start = color_range.start;- let color_end = color_range.end;-- let Some(range) = multi_buffer_snapshot- .buffer_anchor_range_to_anchor_range(- buffer_snapshot.anchor_range_outside(- buffer_snapshot- .clip_point_utf16(color_start, Bias::Left)- ..buffer_snapshot- .clip_point_utf16(color_end, Bias::Right),- ),- )- else {- continue;- };-- let new_buffer_colors = new_editor_colors- .entry(buffer_snapshot.remote_id())- .or_insert_with(Vec::new);-- let (Ok(i) | Err(i)) =- new_buffer_colors.binary_search_by(|(probe, _)| {- probe- .start- .cmp(&range.start, &multi_buffer_snapshot)- .then_with(|| {- probe.end.cmp(&range.end, &multi_buffer_snapshot)- })- });- new_buffer_colors.insert(i, (range, color));- }+ .or_insert_with(Vec::new);++ let (Ok(i) | Err(i)) =+ new_buffer_colors.binary_search_by(|(probe, _)| {+ probe+ .start+ .cmp(&range.start, &multi_buffer_snapshot)+ .then_with(|| {+ probe.end.cmp(&range.end, &multi_buffer_snapshot)+ })+ });+ new_buffer_colors.insert(i, (range, color));}}- Err(e) => log::error!("Failed to retrieve document colors: {e}"),}+ Err(e) => log::error!("Failed to retrieve document colors: {e}"),}editor@@ -373,7 +422,7 @@ impl Editor {}}).ok();- });+ })}}diff --git a/crates/editor/src/document_links.rs b/crates/editor/src/document_links.rsindex a906a2d160c..ba6f93b12f6 100644--- a/crates/editor/src/document_links.rs+++ b/crates/editor/src/document_links.rs@@ -1,7 +1,6 @@use collections::HashMap;use futures::future::join_all;use gpui::{App, Entity, Task};-use itertools::Itertools;use language::{Buffer, BufferSnapshot};use lsp::LanguageServerId;use project::lsp_store::{BufferDocumentLinks, LspDocumentLink, ResolvedDocumentLink};@@ -9,12 +8,11 @@ use settings::Settings;use text::BufferId;use ui::Context;-use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, editor_settings::EditorSettings};+use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, LspDataKind, editor_settings::EditorSettings};pub(super) struct LspDocumentLinks {pub(super) enabled: bool,pub(super) per_buffer: HashMap<BufferId, BufferDocumentLinks>,- pub(super) refresh_task: Task<()>,}impl LspDocumentLinks {@@ -22,7 +20,6 @@ impl LspDocumentLinks {Self {enabled: EditorSettings::get_global(cx).lsp_document_links,per_buffer: HashMap::default(),- refresh_task: Task::ready(()),}}}@@ -40,65 +37,45 @@ impl Editor {return;};- let buffers_to_query = self- .visible_buffers(cx)- .into_iter()- .filter(|buffer| self.is_lsp_relevant(buffer.read(cx).file(), cx))- .chain(for_buffer.and_then(|id| self.buffer.read(cx).buffer(id)))- .filter(|buffer| {- let id = buffer.read(cx).remote_id();- for_buffer.is_none_or(|target| target == id)- && self.registered_buffers.contains_key(&id)- })- .unique_by(|buffer| buffer.read(cx).remote_id())- .collect::<Vec<_>>();- if buffers_to_query.is_empty() {- self.lsp_document_links.refresh_task = Task::ready(());- return;- }-- self.lsp_document_links.refresh_task = cx.spawn(async move |editor, cx| {- cx.background_executor()- .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)- .await;-- let Some(tasks_for_buffers) = project- .update(cx, |project, cx| {- project.lsp_store().update(cx, |lsp_store, cx| {- buffers_to_query- .into_iter()- .map(|buffer| {- let buffer_id = buffer.read(cx).remote_id();- let task = lsp_store.fetch_document_links(&buffer, cx);- async move { (buffer_id, task.await) }- })- .collect::<Vec<_>>()- })- })- .ok()- else {- return;- };+ let buffers_to_query = self.lsp_data_buffers(for_buffer, cx);+ self.spawn_lsp_data_tasks(+ LspDataKind::DocumentLinks,+ for_buffer,+ buffers_to_query,+ cx,+ |buffer, cx| {+ let project = project.clone();+ let buffer_id = buffer.read(cx).remote_id();+ cx.spawn(async move |editor, cx| {+ cx.background_executor()+ .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)+ .await;- let new_links_for_buffers = join_all(tasks_for_buffers).await;- editor- .update(cx, |editor, _| {- for (buffer_id, links) in new_links_for_buffers {- let Some(links) = links else {- continue;- };- if links.is_empty() {- editor.lsp_document_links.per_buffer.remove(&buffer_id);- } else {- editor- .lsp_document_links- .per_buffer- .insert(buffer_id, links);- }- }+ let Ok(task) = project.update(cx, |project, cx| {+ project.lsp_store().update(cx, |lsp_store, cx| {+ lsp_store.fetch_document_links(&buffer, cx)+ })+ }) else {+ return;+ };+ let Some(links) = task.await else {+ return;+ };+ editor+ .update(cx, |editor, _| {+ if links.is_empty() {+ editor.lsp_document_links.per_buffer.remove(&buffer_id);+ } else {+ editor+ .lsp_document_links+ .per_buffer+ .insert(buffer_id, links);+ }+ })+ .ok();})- .ok();- });+ },+ );}/// Returns a task yielding the resolved document links covering `position`diff --git a/crates/editor/src/document_symbols.rs b/crates/editor/src/document_symbols.rsindex c86b2452323..97c4019fcfe 100644--- a/crates/editor/src/document_symbols.rs+++ b/crates/editor/src/document_symbols.rs@@ -1,8 +1,5 @@use std::ops::Range;-use collections::HashMap;-use futures::FutureExt;-use futures::future::join_all;use gpui::{App, Context, HighlightStyle, Task};use itertools::Itertools as _;use language::language_settings::LanguageSettings;@@ -17,7 +14,7 @@ use unicode_segmentation::UnicodeSegmentation as _;use util::maybe;use crate::display_map::DisplaySnapshot;-use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT};+use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, LspDataKind};impl Editor {/// Returns all document outline items for a buffer, using LSP or@@ -33,9 +30,15 @@ impl Editor {};if lsp_symbols_enabled(buffer.read(cx), cx) {- let refresh_task = self.refresh_document_symbols_task.clone();+ let refresh_task = self+ .lsp_data_tasks+ .get(&buffer_id)+ .and_then(|tasks| tasks.get(&LspDataKind::DocumentSymbols))+ .cloned();cx.spawn(async move |editor, cx| {- refresh_task.await;+ if let Some(refresh_task) = refresh_task {+ refresh_task.await;+ }editor.read_with(cx, |editor, _| {editor@@ -188,46 +191,37 @@ impl Editor {return;}- self.refresh_document_symbols_task = cx- .spawn(async move |editor, cx| {- cx.background_executor()- .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)- .await;-- let Some(tasks) = project- .update(cx, |project, cx| {+ self.spawn_lsp_data_tasks(+ LspDataKind::DocumentSymbols,+ for_buffer,+ buffers_to_query,+ cx,+ |buffer, cx| {+ let project = project.clone();+ let buffer_id = buffer.read(cx).remote_id();+ cx.spawn(async move |editor, cx| {+ cx.background_executor()+ .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)+ .await;++ let Ok(task) = project.update(cx, |project, cx| {project.lsp_store().update(cx, |lsp_store, cx| {- buffers_to_query- .into_iter()- .map(|buffer| {- let buffer_id = buffer.read(cx).remote_id();- let task = lsp_store.fetch_document_symbols(&buffer, cx);- async move { (buffer_id, task.await) }- })- .collect::<Vec<_>>()+ lsp_store.fetch_document_symbols(&buffer, cx)})- })- .ok()- else {- return;- };-- let results = join_all(tasks).await.into_iter().collect::<HashMap<_, _>>();- editor- .update(cx, |editor, cx| {- let syntax = cx.theme().syntax().clone();- let display_snapshot =- editor.display_map.update(cx, |map, cx| map.snapshot(cx));- let mut highlighted_results = results;- for (buffer_id, items) in highlighted_results.iter_mut() {- let language = editor- .buffer- .read(cx)- .buffer(*buffer_id)- .and_then(|buffer| buffer.read(cx).language().cloned());- for item in items {+ }) else {+ return;+ };++ let mut items = task.await;+ editor+ .update(cx, |editor, cx| {+ let syntax = cx.theme().syntax().clone();+ let display_snapshot =+ editor.display_map.update(cx, |map, cx| map.snapshot(cx));+ let language = buffer.read(cx).language().cloned();+ for item in &mut items {if let Some(highlights) =- highlights_from_buffer(&display_snapshot, &item, &syntax)+ highlights_from_buffer(&display_snapshot, item, &syntax){item.highlight_ranges = highlights;} else if let Some(language) = &language {@@ -235,13 +229,13 @@ impl Editor {highlight_ranges_from_text(&item.text, language, &syntax);}}- }- editor.lsp_document_symbols.extend(highlighted_results);- editor.refresh_outline_symbols_at_cursor(cx);- })- .ok();- })- .shared();+ editor.lsp_document_symbols.insert(buffer_id, items);+ editor.refresh_outline_symbols_at_cursor(cx);+ })+ .ok();+ })+ },+ );}}diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex e112f71ba75..1be08b38ffe 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -930,6 +930,16 @@ struct GutterHoverButton {is_active: bool,}+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+enum LspDataKind {+ PullDiagnostics,+ DocumentColors,+ DocumentLinks,+ FoldingRanges,+ CodeLens,+ DocumentSymbols,+}+enum CodeActionsForSelection {None,Fetching(Shared<Task<Option<ActionFetchReady>>>),@@ -1173,7 +1183,8 @@ pub struct Editor {/// Counter for generating unique comment IDs.next_review_comment_id: usize,hovered_diff_hunk_row: Option<DisplayRow>,- pull_diagnostics_task: Task<()>,+ lsp_data_tasks: HashMap<BufferId, HashMap<LspDataKind, Shared<Task<()>>>>,+ offscreen_lsp_data_tasks: HashMap<LspDataKind, (BufferId, Task<()>)>,in_project_search: bool,previous_search_ranges: Option<Arc<[Range<Anchor>]>>,breadcrumb_header: Option<String>,@@ -1199,10 +1210,7 @@ pub struct Editor {colors: Option<LspColorData>,code_lens: Option<CodeLensState>,post_scroll_update: Task<()>,- refresh_colors_task: Task<()>,- refresh_code_lens_task: Task<()>,use_document_folding_ranges: bool,- refresh_folding_ranges_task: Task<()>,inlay_hints: Option<LspInlayHintData>,folding_newlines: Task<()>,select_next_options: Option<SelectSearchOptions>,@@ -1215,7 +1223,6 @@ pub struct Editor {bracket_fetched_tree_sitter_chunks: HashMap<Range<text::Anchor>, HashSet<Range<BufferRow>>>,semantic_token_state: SemanticTokenState,pub(crate) refresh_matching_bracket_highlights_task: Task<()>,- refresh_document_symbols_task: Shared<Task<()>>,lsp_document_links: LspDocumentLinks,lsp_document_symbols: HashMap<BufferId, Vec<OutlineItem<text::Anchor>>>,refresh_outline_symbols_at_cursor_at_cursor_task: Task<()>,@@ -2561,13 +2568,11 @@ impl Editor {}).unwrap_or_default(),runnables: RunnableData::new(),- pull_diagnostics_task: Task::ready(()),+ lsp_data_tasks: HashMap::default(),+ offscreen_lsp_data_tasks: HashMap::default(),colors: None,code_lens: None,- refresh_colors_task: Task::ready(()),- refresh_code_lens_task: Task::ready(()),use_document_folding_ranges: false,- refresh_folding_ranges_task: Task::ready(()),inlay_hints: None,next_color_inlay_id: 0,post_scroll_update: Task::ready(()),@@ -2604,7 +2609,6 @@ impl Editor {bracket_fetched_tree_sitter_chunks: HashMap::default(),number_deleted_lines: false,refresh_matching_bracket_highlights_task: Task::ready(()),- refresh_document_symbols_task: Task::ready(()).shared(),lsp_document_links: LspDocumentLinks::new(cx),lsp_document_symbols: HashMap::default(),refresh_outline_symbols_at_cursor_at_cursor_task: Task::ready(()),@@ -2660,9 +2664,8 @@ impl Editor {new_anchor.offset,);});-- editor.update_data_on_scroll(true, window, cx);}+ editor.update_data_on_scroll(true, window, cx);editor.refresh_sticky_headers(&editor.snapshot(window, cx), cx);}EditorEvent::Edited { .. } => {@@ -10166,6 +10169,7 @@ impl Editor {}self.refresh_document_highlights(cx);let buffer_id = buffer.read(cx).remote_id();+ self.remove_invalid_lsp_data(&[buffer_id], false, cx);if self.buffer.read(cx).diff_for(buffer_id).is_none()&& let Some(project) = self.project.clone(){@@ -10189,6 +10193,7 @@ impl Editor {});}multi_buffer::Event::BuffersRemoved { removed_buffer_ids } => {+ self.remove_invalid_lsp_data(removed_buffer_ids, true, cx);if let Some(inlay_hints) = &mut self.inlay_hints {inlay_hints.remove_inlay_chunk_data(removed_buffer_ids);}@@ -10478,7 +10483,7 @@ impl Editor {self.refresh_document_links(None, cx);} else {self.lsp_document_links.per_buffer.clear();- self.lsp_document_links.refresh_task = Task::ready(());+ self.clear_lsp_data_tasks(LspDataKind::DocumentLinks);}}@@ -11435,6 +11440,110 @@ impl Editor {self.refresh_document_symbols(for_buffer, cx);}+ fn lsp_data_buffers(+ &self,+ for_buffer: Option<BufferId>,+ cx: &mut Context<Self>,+ ) -> Vec<Entity<Buffer>> {+ self.visible_buffers(cx)+ .into_iter()+ .filter(|buffer| self.is_lsp_relevant(buffer.read(cx).file(), cx))+ .chain(for_buffer.and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id)))+ .filter(|buffer| {+ let buffer_id = buffer.read(cx).remote_id();+ for_buffer.is_none_or(|for_buffer| for_buffer == buffer_id)+ && self.registered_buffers.contains_key(&buffer_id)+ })+ .unique_by(|buffer| buffer.read(cx).remote_id())+ .collect()+ }++ fn is_buffer_visible(&self, buffer_id: BufferId, cx: &mut Context<Self>) -> bool {+ self.buffer.read(cx).is_singleton()+ || self+ .visible_buffers(cx)+ .iter()+ .any(|buffer| buffer.read(cx).remote_id() == buffer_id)+ }++ fn spawn_lsp_data_tasks(+ &mut self,+ kind: LspDataKind,+ for_buffer: Option<BufferId>,+ buffers: Vec<Entity<Buffer>>,+ cx: &mut Context<Self>,+ spawn: impl Fn(Entity<Buffer>, &mut Context<Self>) -> Task<()>,+ ) {+ let Some(buffer_id) = for_buffer else {+ self.clear_lsp_data_tasks(kind);+ for buffer in buffers {+ let buffer_id = buffer.read(cx).remote_id();+ let task = spawn(buffer, cx).shared();+ self.insert_lsp_data_task(kind, buffer_id, task);+ }+ return;+ };++ if let Some(tasks) = self.lsp_data_tasks.get_mut(&buffer_id) {+ tasks.remove(&kind);+ }+ if self+ .offscreen_lsp_data_tasks+ .get(&kind)+ .is_some_and(|(task_buffer_id, _)| *task_buffer_id == buffer_id)+ {+ self.offscreen_lsp_data_tasks.remove(&kind);+ }+ let is_visible = self.is_buffer_visible(buffer_id, cx);+ for buffer in buffers {+ let task = spawn(buffer, cx);+ if is_visible {+ self.insert_lsp_data_task(kind, buffer_id, task.shared());+ } else {+ self.offscreen_lsp_data_tasks+ .insert(kind, (buffer_id, task));+ }+ }+ }++ fn insert_lsp_data_task(+ &mut self,+ kind: LspDataKind,+ buffer_id: BufferId,+ task: Shared<Task<()>>,+ ) {+ self.lsp_data_tasks+ .entry(buffer_id)+ .or_default()+ .insert(kind, task);+ }++ fn clear_lsp_data_tasks(&mut self, kind: LspDataKind) {+ for tasks in self.lsp_data_tasks.values_mut() {+ tasks.remove(&kind);+ }+ self.offscreen_lsp_data_tasks.remove(&kind);+ }++ fn remove_invalid_lsp_data(+ &mut self,+ buffer_ids: &[BufferId],+ buffers_removed: bool,+ cx: &mut Context<Self>,+ ) {+ let snapshot = self.buffer.read(cx).snapshot(cx);+ for buffer_id in buffer_ids {+ if snapshot.buffer_for_id(*buffer_id).is_none() {+ self.lsp_data_tasks.remove(buffer_id);+ self.offscreen_lsp_data_tasks+ .retain(|_, (task_buffer_id, _)| task_buffer_id != buffer_id);+ }+ }+ self.remove_invalid_code_lenses(buffer_ids, buffers_removed, &snapshot, cx);+ self.remove_invalid_inline_diagnostics(buffer_ids, buffers_removed, &snapshot, cx);+ self.remove_invalid_document_colors(buffer_ids, buffers_removed, &snapshot, cx);+ }+fn is_eligible_for_language_detection(buffer: &Buffer) -> bool {buffer.file().is_none()&& buffer.content_language_detection_enabled()diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rsindex eab8daac46e..c8da5a119f7 100644--- a/crates/editor/src/editor_tests.rs+++ b/crates/editor/src/editor_tests.rs@@ -28149,11 +28149,21 @@ async fn test_go_to_symbol_after_edit(cx: &mut TestAppContext) {cx.set_state("padding\nˇ\n");let (ready, pending) = oneshot::channel();let navigation = cx.update_editor(|editor, window, cx| {- editor.refresh_document_symbols_task = cx- .background_spawn(async move {+ let buffer_id = editor+ .buffer+ .read(cx)+ .as_singleton()+ .unwrap()+ .read(cx)+ .remote_id();+ editor.insert_lsp_data_task(+ LspDataKind::DocumentSymbols,+ buffer_id,+ cx.background_spawn(async move {pending.await.expect("symbol refresh should complete");})- .shared();+ .shared(),+ );editor.go_to_symbol_by_offset(window, cx, direction)});cx.run_until_parked();@@ -42797,6 +42807,285 @@ async fn test_pulling_diagnostics(cx: &mut TestAppContext) {ensure_result_id(Some(SharedString::new(final_requests.to_string())), cx);}+#[gpui::test]+async fn test_lsp_data_for_every_multibuffer_buffer(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ update_test_language_settings(cx, &|settings| {+ settings.defaults.document_folding_ranges = Some(settings::DocumentFoldingRanges::On);+ settings.defaults.document_symbols = Some(settings::DocumentSymbols::On);+ });+ update_test_editor_settings(cx, &|settings| {+ settings.lsp_document_colors = Some(settings::DocumentColorsRenderMode::Border);+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/dir"),+ json!({+ "a.rs": "fn a() {}\nfn b() {}\nfn c() {}",+ "b.rs": "fn d() {}",+ }),+ )+ .await;+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());+ language_registry.add(rust_lang());+ let requests = Arc::new(Mutex::new(Vec::new()));+ let mut fake_servers = language_registry.register_fake_lsp(+ "Rust",+ FakeLspAdapter {+ capabilities: lsp::ServerCapabilities {+ color_provider: Some(lsp::ColorProviderCapability::Simple(true)),+ folding_range_provider: Some(lsp::FoldingRangeProviderCapability::Simple(true)),+ document_link_provider: Some(lsp::DocumentLinkOptions {+ resolve_provider: None,+ work_done_progress_options: lsp::WorkDoneProgressOptions::default(),+ }),+ document_symbol_provider: Some(lsp::OneOf::Left(true)),+ diagnostic_provider: Some(lsp::DiagnosticServerCapabilities::Options(+ lsp::DiagnosticOptions::default(),+ )),+ ..lsp::ServerCapabilities::default()+ },+ initializer: Some(Box::new({+ let requests = requests.clone();+ move |server| {+ record_lsp_requests::<lsp::request::DocumentColor>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |file_name| {+ let row = if file_name == "a.rs" { 2 } else { 0 };+ vec![lsp::ColorInformation {+ range: lsp::Range::new(+ lsp::Position::new(row, 0),+ lsp::Position::new(row, 2),+ ),+ color: lsp::Color {+ red: 1.0,+ green: 0.0,+ blue: 0.0,+ alpha: 1.0,+ },+ }]+ },+ );+ record_lsp_requests::<lsp::request::FoldingRangeRequest>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| Some(Vec::new()),+ );+ record_lsp_requests::<lsp::request::DocumentLinkRequest>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| Some(Vec::new()),+ );+ record_lsp_requests::<lsp::request::DocumentSymbolRequest>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| Some(lsp::DocumentSymbolResponse::Flat(Vec::new())),+ );+ record_lsp_requests::<lsp::request::DocumentDiagnosticRequest>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| {+ lsp::DocumentDiagnosticReportResult::Report(+ lsp::DocumentDiagnosticReport::Full(+ lsp::RelatedFullDocumentDiagnosticReport::default(),+ ),+ )+ },+ );+ }+ })),+ ..FakeLspAdapter::default()+ },+ );+ let first_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();+ let second_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/b.rs"), cx)+ })+ .await+ .unwrap();+ let multibuffer = cx.new(|_| MultiBuffer::new(ReadWrite));+ let (editor, cx) = cx.add_window_view(|window, cx| {+ build_editor_with_project(project, multibuffer.clone(), window, cx)+ });+ multibuffer.update(cx, |multibuffer, cx| {+ for (index, buffer) in [&first_buffer, &second_buffer].into_iter().enumerate() {+ let max_point = buffer.read(cx).max_point();+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(index as u64),+ buffer.clone(),+ [Point::zero()..max_point],+ 0,+ cx,+ );+ }+ });+ let _server = fake_servers.next().await.unwrap();+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();++ let mut requested = requests.lock().drain(..).collect::<Vec<_>>();+ requested.sort();+ requested.dedup();+ assert_eq!(+ requested,+ [+ "textDocument/diagnostic",+ "textDocument/documentColor",+ "textDocument/documentLink",+ "textDocument/documentSymbol",+ "textDocument/foldingRange",+ ]+ .into_iter()+ .flat_map(|method| ["a.rs", "b.rs"].map(|file_name| (method, file_name.to_string())))+ .collect::<Vec<_>>(),+ );+ editor.update_in(cx, |editor, window, cx| {+ assert_eq!(document_color_rows(editor, window, cx), vec![2, 3]);+ });++ multibuffer.update(cx, |multibuffer, cx| {+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(0),+ first_buffer.clone(),+ [Point::zero()..Point::new(0, 9)],+ 0,+ cx,+ );+ });+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ editor.update_in(cx, |editor, window, cx| {+ assert_eq!(document_color_rows(editor, window, cx), vec![1]);+ });+}++#[gpui::test]+async fn test_lsp_data_for_offscreen_multibuffer_edits(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/dir"),+ json!({+ "a.rs": "fn a() {}\n".repeat(200),+ "b.rs": "fn b() {}",+ "c.rs": "fn c() {}",+ }),+ )+ .await;+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());+ language_registry.add(rust_lang());+ let requests = Arc::new(Mutex::new(Vec::new()));+ let mut fake_servers = language_registry.register_fake_lsp(+ "Rust",+ FakeLspAdapter {+ capabilities: lsp::ServerCapabilities {+ color_provider: Some(lsp::ColorProviderCapability::Simple(true)),+ diagnostic_provider: Some(lsp::DiagnosticServerCapabilities::Options(+ lsp::DiagnosticOptions::default(),+ )),+ ..lsp::ServerCapabilities::default()+ },+ initializer: Some(Box::new({+ let requests = requests.clone();+ move |server| {+ record_lsp_requests::<lsp::request::DocumentColor>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| Vec::new(),+ );+ record_lsp_requests::<lsp::request::DocumentDiagnosticRequest>(+ server,+ &requests,+ |params| params.text_document.uri.clone(),+ |_| {+ lsp::DocumentDiagnosticReportResult::Report(+ lsp::DocumentDiagnosticReport::Full(+ lsp::RelatedFullDocumentDiagnosticReport::default(),+ ),+ )+ },+ );+ }+ })),+ ..FakeLspAdapter::default()+ },+ );+ let first_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();+ let second_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/b.rs"), cx)+ })+ .await+ .unwrap();+ let third_buffer = project+ .update(cx, |project, cx| {+ project.open_local_buffer(path!("/dir/c.rs"), cx)+ })+ .await+ .unwrap();+ let multibuffer = cx.new(|_| MultiBuffer::new(ReadWrite));+ let (_editor, cx) = cx.add_window_view(|window, cx| {+ build_editor_with_project(project, multibuffer.clone(), window, cx)+ });+ multibuffer.update(cx, |multibuffer, cx| {+ for (index, buffer) in [&first_buffer, &second_buffer, &third_buffer]+ .into_iter()+ .enumerate()+ {+ let max_point = buffer.read(cx).max_point();+ multibuffer.set_excerpts_for_path(+ PathKey::sorted(index as u64),+ buffer.clone(),+ [Point::zero()..max_point],+ 0,+ cx,+ );+ }+ });+ let _server = fake_servers.next().await.unwrap();+ cx.executor().advance_clock(Duration::from_millis(500));+ cx.run_until_parked();+ requests.lock().clear();++ for buffer in [&second_buffer, &third_buffer] {+ buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "x")], None, cx));+ }+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.run_until_parked();++ let mut requested = requests.lock().drain(..).collect::<Vec<_>>();+ requested.sort();+ requested.dedup();+ assert_eq!(+ requested,+ vec![+ ("textDocument/diagnostic", "c.rs".to_string()),+ ("textDocument/documentColor", "c.rs".to_string()),+ ]+ );+}+#[gpui::test]async fn test_add_selection_after_moving_with_multiple_cursors(cx: &mut TestAppContext) {// Regression test for issue #11671@@ -51100,3 +51389,42 @@ async fn assert_on_type_formatting_request_position(cx.assert_editor_state(expected_state);assert!(request.next().await.is_some());}++fn record_lsp_requests<R>(+ server: &lsp::FakeLanguageServer,+ requests: &Arc<Mutex<Vec<(&'static str, String)>>>,+ uri: fn(&R::Params) -> lsp::Uri,+ response: fn(&str) -> R::Result,+) where+ R: 'static + lsp::request::Request,+ R::Params: 'static + Send,+ R::Result: 'static + Send,+{+ let requests = requests.clone();+ server.set_request_handler::<R, _, _>(move |params, _| {+ let uri = uri(¶ms).to_string();+ let file_name = uri.rsplit('/').next().unwrap_or_default().to_string();+ let result = response(&file_name);+ requests.lock().push((R::METHOD, file_name));+ async move { Ok(result) }+ });+}++fn document_color_rows(+ editor: &mut Editor,+ window: &mut Window,+ cx: &mut Context<Editor>,+) -> Vec<u32> {+ let snapshot = editor.snapshot(window, cx);+ let Some(colors) = editor.colors.as_ref() else {+ return Vec::new();+ };+ let mut rows = colors+ .editor_display_highlights(&snapshot)+ .1+ .into_iter()+ .map(|(range, _)| range.start.to_point(&snapshot.display_snapshot).row)+ .collect::<Vec<_>>();+ rows.sort();+ rows+}diff --git a/crates/editor/src/folding_ranges.rs b/crates/editor/src/folding_ranges.rsindex 6c1db5f3ee9..e9e245b3c0f 100644--- a/crates/editor/src/folding_ranges.rs+++ b/crates/editor/src/folding_ranges.rs@@ -1,10 +1,8 @@-use futures::future::join_all;-use itertools::Itertools;use language::language_settings::LanguageSettings;use text::BufferId;use ui::{Context, Window};-use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT};+use crate::{Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, LspDataKind};impl Editor {pub(super) fn refresh_folding_ranges(@@ -21,62 +19,47 @@ impl Editor {};let buffers_to_query = self- .visible_buffers(cx)+ .lsp_data_buffers(for_buffer, cx).into_iter()- .filter(|buffer| self.is_lsp_relevant(buffer.read(cx).file(), cx))- .chain(for_buffer.and_then(|id| self.buffer.read(cx).buffer(id))).filter(|buffer| {- let id = buffer.read(cx).remote_id();- (for_buffer.is_none_or(|target| target == id))- && self.registered_buffers.contains_key(&id)- && LanguageSettings::for_buffer(buffer.read(cx), cx)- .document_folding_ranges- .enabled()+ LanguageSettings::for_buffer(buffer.read(cx), cx)+ .document_folding_ranges+ .enabled()})- .unique_by(|buffer| buffer.read(cx).remote_id())- .collect::<Vec<_>>();-- self.refresh_folding_ranges_task = cx.spawn(async move |editor, cx| {- cx.background_executor()- .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)- .await;-- let Some(tasks) = editor- .update(cx, |_, cx| {- let project = project.upgrade()?;- Some(project.read(cx).lsp_store().update(cx, |lsp_store, cx| {- buffers_to_query- .into_iter()- .map(|buffer| {- let buffer_id = buffer.read(cx).remote_id();- let task = lsp_store.fetch_folding_ranges(&buffer, cx);- async move { (buffer_id, task.await) }- })- .collect::<Vec<_>>()- }))- })- .ok()- .flatten()- else {- return;- };-- let results = join_all(tasks).await;- if results.is_empty() {- return;- }-- editor- .update(cx, |editor, cx| {- editor.display_map.update(cx, |display_map, cx| {- for (buffer_id, ranges) in results {- display_map.set_lsp_folding_ranges(buffer_id, ranges, cx);- }- });- cx.notify();+ .collect();+ self.spawn_lsp_data_tasks(+ LspDataKind::FoldingRanges,+ for_buffer,+ buffers_to_query,+ cx,+ |buffer, cx| {+ let project = project.clone();+ let buffer_id = buffer.read(cx).remote_id();+ cx.spawn(async move |editor, cx| {+ cx.background_executor()+ .timer(LSP_REQUEST_DEBOUNCE_TIMEOUT)+ .await;++ let Ok(task) = project.update(cx, |project, cx| {+ project.lsp_store().update(cx, |lsp_store, cx| {+ lsp_store.fetch_folding_ranges(&buffer, cx)+ })+ }) else {+ return;+ };+ let ranges = task.await;++ editor+ .update(cx, |editor, cx| {+ editor.display_map.update(cx, |display_map, cx| {+ display_map.set_lsp_folding_ranges(buffer_id, ranges, cx);+ });+ cx.notify();+ })+ .ok();})- .ok();- });+ },+ );}pub fn document_folding_ranges_enabled(&self, cx: &ui::App) -> bool {@@ -124,7 +107,7 @@ impl Editor {#[cfg(test)]mod tests {- use futures::StreamExt as _;+ use futures::{FutureExt as _, StreamExt as _, channel::oneshot};use gpui::TestAppContext;use lsp::FoldingRange;use multi_buffer::MultiBufferRow;@@ -132,6 +115,7 @@ mod tests {use settings::DocumentFoldingRanges;use crate::{+ LSP_REQUEST_DEBOUNCE_TIMEOUT,editor_tests::{init_test, update_test_language_settings},test::editor_lsp_test_context::EditorLspTestContext,};@@ -331,6 +315,55 @@ mod tests {});}+ #[gpui::test]+ async fn test_lsp_folding_ranges_toggling_off_drops_pending_response(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ update_test_language_settings(cx, &|settings| {+ settings.defaults.document_folding_ranges = Some(DocumentFoldingRanges::On);+ });+ let mut cx = EditorLspTestContext::new_rust(+ lsp::ServerCapabilities {+ folding_range_provider: Some(lsp::FoldingRangeProviderCapability::Simple(true)),+ ..lsp::ServerCapabilities::default()+ },+ cx,+ )+ .await;+ let (response_sender, response_receiver) = oneshot::channel::<()>();+ let response_receiver = response_receiver.shared();+ let mut folding_request = cx+ .set_request_handler::<lsp::request::FoldingRangeRequest, _, _>(move |_, _, _| {+ let response_receiver = response_receiver.clone();+ async move {+ response_receiver.await.ok();+ Ok(Some(vec![FoldingRange {+ start_line: 0,+ start_character: Some(10),+ end_line: 2,+ end_character: Some(1),+ kind: None,+ collapsed_text: None,+ }]))+ }+ });++ cx.set_state("ˇfn main() {\n println!(\"hello\");\n}\n");+ cx.executor()+ .advance_clock(LSP_REQUEST_DEBOUNCE_TIMEOUT * 2);+ cx.run_until_parked();+ update_test_language_settings(&mut cx.cx.cx, &|settings| {+ settings.defaults.document_folding_ranges = Some(DocumentFoldingRanges::Off);+ });+ cx.run_until_parked();+ response_sender.send(()).unwrap();+ assert!(folding_request.next().await.is_some());+ cx.run_until_parked();++ cx.editor.read_with(&cx.cx.cx, |editor, cx| {+ assert!(!editor.document_folding_ranges_enabled(cx));+ });+ }+#[gpui::test]async fn test_lsp_folding_ranges_nested_folds(cx: &mut TestAppContext) {init_test(cx, |_| {});