Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Avoid flickering when displaying code lens (#55075)

Kirill Bulatov10922d7fadcf
diff --git a/crates/editor/src/code_lens.rs b/crates/editor/src/code_lens.rs
index e93757cb3a0..c123eceea3d 100644
--- a/crates/editor/src/code_lens.rs
+++ b/crates/editor/src/code_lens.rs
@@ -14,7 +14,7 @@ use ui::{Context, Window, div, prelude::*};
use crate::{
Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, SelectionEffects,
actions::ToggleCodeLens,
- display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId},
+ display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},
hover_links::HoverLink,
};
@@ -31,147 +31,28 @@ struct CodeLensItem {
action: CodeAction,
}
+pub(super) struct CodeLensBlock {
+ block_id: CustomBlockId,
+ anchor: Anchor,
+ line: CodeLensLine,
+}
+
pub(super) struct CodeLensState {
- pub(super) block_ids: HashMap<BufferId, Vec<CustomBlockId>>,
+ pub(super) blocks: HashMap<BufferId, Vec<CodeLensBlock>>,
+ actions: HashMap<BufferId, Vec<CodeAction>>,
resolve_task: Task<()>,
}
impl Default for CodeLensState {
fn default() -> Self {
Self {
- block_ids: HashMap::default(),
+ blocks: HashMap::default(),
+ actions: HashMap::default(),
resolve_task: Task::ready(()),
}
}
}
-impl CodeLensState {
- fn all_block_ids(&self) -> HashSet<CustomBlockId> {
- self.block_ids.values().flatten().copied().collect()
- }
-}
-
-fn group_lenses_by_row(
- lenses: Vec<(Anchor, CodeLensItem)>,
- snapshot: &MultiBufferSnapshot,
-) -> impl Iterator<Item = CodeLensLine> {
- lenses
- .into_iter()
- .into_group_map_by(|(position, _)| {
- let row = position.to_point(snapshot).row;
- MultiBufferRow(row)
- })
- .into_iter()
- .sorted_by_key(|(row, _)| *row)
- .filter_map(|(row, entries)| {
- let position = entries.first()?.0;
- let items = entries.into_iter().map(|(_, item)| item).collect();
- let indent_column = snapshot.indent_size_for_line(row).len;
- Some(CodeLensLine {
- position,
- indent_column,
- items,
- })
- })
-}
-
-fn render_code_lens_line(
- lens: CodeLensLine,
- editor: WeakEntity<Editor>,
-) -> impl Fn(&mut crate::display_map::BlockContext) -> gpui::AnyElement {
- move |cx| {
- let mut children = Vec::with_capacity((2 * lens.items.len()).saturating_sub(1));
- let text_style = &cx.editor_style.text;
- let font = text_style.font();
- let font_size = text_style.font_size.to_pixels(cx.window.rem_size()) * 0.9;
-
- for (i, item) in lens.items.iter().enumerate() {
- if i > 0 {
- children.push(
- div()
- .font(font.clone())
- .text_size(font_size)
- .text_color(cx.app.theme().colors().text_muted)
- .child(" | ")
- .into_any_element(),
- );
- }
-
- let title = item.title.clone();
- let action = item.action.clone();
- let editor_handle = editor.clone();
- let position = lens.position;
-
- children.push(
- div()
- .id(ElementId::from(i))
- .font(font.clone())
- .text_size(font_size)
- .text_color(cx.app.theme().colors().text_muted)
- .cursor_pointer()
- .hover(|style| style.text_color(cx.app.theme().colors().text))
- .child(title.clone())
- .on_mouse_down(MouseButton::Left, |_, _, cx| {
- cx.stop_propagation();
- })
- .on_mouse_down(MouseButton::Right, |_, _, cx| {
- cx.stop_propagation();
- })
- .on_click({
- move |_event, window, cx| {
- if let Some(editor) = editor_handle.upgrade() {
- editor.update(cx, |editor, cx| {
- editor.change_selections(
- SelectionEffects::default(),
- window,
- cx,
- |s| {
- s.select_anchor_ranges([position..position]);
- },
- );
-
- let action = action.clone();
- if let Some(workspace) = editor.workspace() {
- if try_handle_client_command(
- &action, editor, &workspace, window, cx,
- ) {
- return;
- }
-
- let project = workspace.read(cx).project().clone();
- if let Some(buffer) = editor
- .buffer()
- .read(cx)
- .buffer(action.range.start.buffer_id)
- {
- project
- .update(cx, |project, cx| {
- project
- .apply_code_action(buffer, action, true, cx)
- })
- .detach_and_log_err(cx);
- }
- }
- });
- }
- }
- })
- .into_any_element(),
- );
- }
-
- div()
- .id(cx.block_id)
- .pl(cx.margins.gutter.full_width() + cx.em_width * (lens.indent_column as f32 + 0.5))
- .h_full()
- .flex()
- .flex_row()
- .items_end()
- .children(children)
- .into_any_element()
- }
-}
-
pub(super) fn try_handle_client_command(
action: &CodeAction,
editor: &mut Editor,
@@ -345,94 +226,169 @@ impl Editor {
return;
}
- let Ok(multi_buffer_snapshot) =
- editor.update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
- else {
- return;
- };
-
- let mut new_lenses_per_buffer = HashMap::default();
- for (buffer_id, result) in results {
- 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;
- }
- };
- let individual_lenses = actions
- .into_iter()
- .filter_map(|action| {
- let title = match &action.lsp_action {
- project::LspAction::CodeLens(lens) => lens
- .command
- .as_ref()
- .map(|cmd| SharedString::from(&cmd.title)),
- _ => None,
- }?;
- let position =
- multi_buffer_snapshot.anchor_in_excerpt(action.range.start)?;
- Some((position, CodeLensItem { title, action }))
- })
- .collect();
- new_lenses_per_buffer.insert(
- buffer_id,
- group_lenses_by_row(individual_lenses, &multi_buffer_snapshot)
- .collect::<Vec<_>>(),
- );
- }
-
editor
.update(cx, |editor, cx| {
- let code_lens = editor.code_lens.get_or_insert_with(CodeLensState::default);
- let mut blocks_to_remove = HashSet::default();
- for buffer_id in new_lenses_per_buffer.keys() {
- if let Some(old_ids) = code_lens.block_ids.remove(buffer_id) {
- blocks_to_remove.extend(old_ids);
- }
- }
- if !blocks_to_remove.is_empty() {
- editor.remove_blocks(blocks_to_remove, None, cx);
- }
-
- let editor_handle = cx.entity().downgrade();
- for (buffer_id, lens_lines) in new_lenses_per_buffer {
- if lens_lines.is_empty() {
- continue;
- }
- let blocks = lens_lines
- .into_iter()
- .map(|lens_line| {
- let position = lens_line.position;
- BlockProperties {
- placement: BlockPlacement::Above(position),
- height: Some(1),
- style: BlockStyle::Flex,
- render: Arc::new(render_code_lens_line(
- lens_line,
- editor_handle.clone(),
- )),
- priority: 0,
- }
- })
- .collect::<Vec<_>>();
- let block_ids = editor.insert_blocks(blocks, None, cx);
- editor
- .code_lens
- .get_or_insert_with(CodeLensState::default)
- .block_ids
- .entry(buffer_id)
- .or_default()
- .extend(block_ids);
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ for (buffer_id, result) in results {
+ 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();
});
}
+ /// Reconciles the set of blocks for `buffer_id` with `actions`. For each
+ /// existing block at row `R`:
+ /// - if the new fetch has no lens at `R` → remove the block (the lens is
+ /// gone, e.g. the function was deleted);
+ /// - if the new fetch has a titled lens at `R` whose rendered text
+ /// differs from the block's current line → swap the renderer in place
+ /// via [`Editor::replace_blocks`];
+ /// - if the new fetch has a titled lens at `R` with the same rendered
+ /// text → keep the block as-is;
+ /// - if the new fetch has a lens at `R` but no `command` yet (the server
+ /// sent a shallow response that needs a separate `resolve`) → keep the
+ /// block as-is. The previously rendered (resolved) content stays on
+ /// screen until the next viewport-driven `resolve` produces a new
+ /// title; only then does the comparison-and-replace happen. This is
+ /// what keeps the post-edit screen from flickering for shallow servers
+ /// like `rust-analyzer`.
+ ///
+ /// Rows present in the new fetch with a title but no existing block get
+ /// a fresh block inserted.
+ fn apply_lens_actions_for_buffer(
+ &mut self,
+ buffer_id: BufferId,
+ actions: Vec<CodeAction>,
+ snapshot: &MultiBufferSnapshot,
+ cx: &mut Context<Self>,
+ ) {
+ let mut rows_with_any_lens = HashSet::default();
+ let mut titled_lenses = Vec::new();
+ for action in &actions {
+ let Some(position) = snapshot.anchor_in_excerpt(action.range.start) else {
+ continue;
+ };
+
+ rows_with_any_lens.insert(MultiBufferRow(position.to_point(snapshot).row));
+ if let project::LspAction::CodeLens(lens) = &action.lsp_action {
+ if let Some(title) = lens
+ .command
+ .as_ref()
+ .map(|cmd| SharedString::from(&cmd.title))
+ {
+ titled_lenses.push((
+ position,
+ CodeLensItem {
+ title,
+ action: action.clone(),
+ },
+ ));
+ }
+ }
+ }
+
+ let mut new_lines_by_row = group_lenses_by_row(titled_lenses, snapshot)
+ .map(|line| (MultiBufferRow(line.position.to_point(snapshot).row), line))
+ .collect::<HashMap<_, _>>();
+
+ let editor_handle = cx.entity().downgrade();
+ let code_lens = self.code_lens.get_or_insert_with(CodeLensState::default);
+ let old_blocks = code_lens.blocks.remove(&buffer_id).unwrap_or_default();
+
+ let mut kept_blocks = Vec::new();
+ let mut renderers_to_replace = HashMap::default();
+ let mut blocks_to_remove = HashSet::default();
+ let mut covered_rows = HashSet::default();
+
+ for old in old_blocks {
+ let row = MultiBufferRow(old.anchor.to_point(snapshot).row);
+ if !rows_with_any_lens.contains(&row) {
+ blocks_to_remove.insert(old.block_id);
+ continue;
+ }
+ covered_rows.insert(row);
+ let Some(new_line) = new_lines_by_row.remove(&row) else {
+ kept_blocks.push(old);
+ continue;
+ };
+ if rendered_text_matches(&old.line, &new_line) {
+ kept_blocks.push(old);
+ } else {
+ let mut updated = old;
+ updated.line = new_line.clone();
+ renderers_to_replace.insert(
+ updated.block_id,
+ build_code_lens_renderer(new_line, editor_handle.clone()),
+ );
+ kept_blocks.push(updated);
+ }
+ }
+
+ let mut to_insert = Vec::new();
+ for (row, new_line) in new_lines_by_row {
+ if covered_rows.contains(&row) {
+ continue;
+ }
+ let anchor = new_line.position;
+ let props = BlockProperties {
+ placement: BlockPlacement::Above(anchor),
+ height: Some(1),
+ style: BlockStyle::Flex,
+ render: build_code_lens_renderer(new_line.clone(), editor_handle.clone()),
+ priority: 0,
+ };
+ to_insert.push((props, anchor, new_line));
+ }
+
+ if !blocks_to_remove.is_empty() {
+ self.remove_blocks(blocks_to_remove, None, cx);
+ }
+ if !renderers_to_replace.is_empty() {
+ self.replace_blocks(renderers_to_replace, None, cx);
+ }
+ if !to_insert.is_empty() {
+ let mut props = Vec::with_capacity(to_insert.len());
+ let mut metadata = Vec::with_capacity(to_insert.len());
+ for (p, anchor, line) in to_insert {
+ props.push(p);
+ metadata.push((anchor, line));
+ }
+ let block_ids = self.insert_blocks(props, None, cx);
+ for (block_id, (anchor, line)) in block_ids.into_iter().zip(metadata) {
+ kept_blocks.push(CodeLensBlock {
+ block_id,
+ anchor,
+ line,
+ });
+ }
+ }
+
+ let code_lens = self.code_lens.get_or_insert_with(CodeLensState::default);
+ if actions.is_empty() {
+ code_lens.actions.remove(&buffer_id);
+ } else {
+ code_lens.actions.insert(buffer_id, actions);
+ }
+ if kept_blocks.is_empty() {
+ code_lens.blocks.remove(&buffer_id);
+ } else {
+ code_lens.blocks.insert(buffer_id, kept_blocks);
+ }
+ cx.notify();
+ }
+
pub fn supports_code_lens(&self, cx: &ui::App) -> bool {
let Some(project) = self.project.as_ref() else {
return false;
@@ -502,7 +458,7 @@ impl Editor {
let code_lens = self.code_lens.get_or_insert_with(CodeLensState::default);
code_lens.resolve_task = cx.spawn(async move |editor, cx| {
- let resolved_code_lens = join_all(
+ let resolved_per_buffer = join_all(
resolve_tasks
.into_iter()
.map(|(buffer_id, task)| async move { (buffer_id, task.await) }),
@@ -510,65 +466,42 @@ impl Editor {
.await;
editor
.update(cx, |editor, cx| {
- editor.insert_resolved_code_lens_blocks(resolved_code_lens, cx);
- })
- .ok();
- });
- }
-
- fn insert_resolved_code_lens_blocks(
- &mut self,
- resolved_code_lens: Vec<(BufferId, Vec<CodeAction>)>,
- cx: &mut Context<Self>,
- ) {
- let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
- let editor_handle = cx.entity().downgrade();
-
- for (buffer_id, actions) in resolved_code_lens {
- let lenses = actions
- .into_iter()
- .filter_map(|action| {
- let title = match &action.lsp_action {
- project::LspAction::CodeLens(lens) => lens
- .command
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ for (buffer_id, newly_resolved) in resolved_per_buffer {
+ if newly_resolved.is_empty() {
+ continue;
+ }
+ let Some(mut actions) = editor
+ .code_lens
.as_ref()
- .map(|cmd| SharedString::from(&cmd.title)),
- _ => None,
- }?;
- let position = multi_buffer_snapshot.anchor_in_excerpt(action.range.start)?;
- Some((position, CodeLensItem { title, action }))
- })
- .collect();
-
- let blocks = group_lenses_by_row(lenses, &multi_buffer_snapshot)
- .map(|lens_line| {
- let position = lens_line.position;
- BlockProperties {
- placement: BlockPlacement::Above(position),
- height: Some(1),
- style: BlockStyle::Flex,
- render: Arc::new(render_code_lens_line(lens_line, editor_handle.clone())),
- priority: 0,
+ .and_then(|state| state.actions.get(&buffer_id))
+ .cloned()
+ else {
+ continue;
+ };
+ for resolved in newly_resolved {
+ if let Some(unresolved) = actions.iter_mut().find(|action| {
+ action.server_id == resolved.server_id
+ && action.range == resolved.range
+ }) {
+ *unresolved = resolved;
+ }
+ }
+ editor.apply_lens_actions_for_buffer(buffer_id, actions, &snapshot, cx);
}
})
- .collect::<Vec<_>>();
-
- if !blocks.is_empty() {
- let block_ids = self.insert_blocks(blocks, None, cx);
- self.code_lens
- .get_or_insert_with(CodeLensState::default)
- .block_ids
- .entry(buffer_id)
- .or_default()
- .extend(block_ids);
- }
- }
- cx.notify();
+ .ok();
+ });
}
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.all_block_ids();
+ let all_blocks = code_lens
+ .blocks
+ .into_values()
+ .flatten()
+ .map(|block| block.block_id)
+ .collect::<HashSet<_>>();
if !all_blocks.is_empty() {
self.remove_blocks(all_blocks, None, cx);
}
@@ -578,6 +511,138 @@ impl Editor {
}
}
+/// Whether two lens lines would render the same on screen — same indent
+/// and same titles in the same order. Used to skip recreating a renderer
+/// (and thus a click handler) when nothing about the displayed line
+/// changed; the captured [`CodeAction`] inside the existing renderer keeps
+/// pointing at the right spot because its anchors track buffer edits.
+fn rendered_text_matches(a: &CodeLensLine, b: &CodeLensLine) -> bool {
+ a.indent_column == b.indent_column
+ && a.items.len() == b.items.len()
+ && a.items
+ .iter()
+ .zip(&b.items)
+ .all(|(x, y)| x.title == y.title)
+}
+
+fn group_lenses_by_row(
+ lenses: Vec<(Anchor, CodeLensItem)>,
+ snapshot: &MultiBufferSnapshot,
+) -> impl Iterator<Item = CodeLensLine> {
+ lenses
+ .into_iter()
+ .into_group_map_by(|(position, _)| {
+ let row = position.to_point(snapshot).row;
+ MultiBufferRow(row)
+ })
+ .into_iter()
+ .sorted_by_key(|(row, _)| *row)
+ .filter_map(|(row, entries)| {
+ let position = entries.first()?.0;
+ let items = entries.into_iter().map(|(_, item)| item).collect();
+ let indent_column = snapshot.indent_size_for_line(row).len;
+ Some(CodeLensLine {
+ position,
+ indent_column,
+ items,
+ })
+ })
+}
+
+fn build_code_lens_renderer(line: CodeLensLine, editor: WeakEntity<Editor>) -> RenderBlock {
+ Arc::new(move |cx| {
+ let mut children = Vec::with_capacity((2 * line.items.len()).saturating_sub(1));
+ let text_style = &cx.editor_style.text;
+ let font = text_style.font();
+ let font_size = text_style.font_size.to_pixels(cx.window.rem_size()) * 0.9;
+
+ for (i, item) in line.items.iter().enumerate() {
+ if i > 0 {
+ children.push(
+ div()
+ .font(font.clone())
+ .text_size(font_size)
+ .text_color(cx.app.theme().colors().text_muted)
+ .child(" | ")
+ .into_any_element(),
+ );
+ }
+
+ let title = item.title.clone();
+ let action = item.action.clone();
+ let position = line.position;
+ let editor_handle = editor.clone();
+
+ children.push(
+ div()
+ .id(ElementId::from(i))
+ .font(font.clone())
+ .text_size(font_size)
+ .text_color(cx.app.theme().colors().text_muted)
+ .cursor_pointer()
+ .hover(|style| style.text_color(cx.app.theme().colors().text))
+ .child(title)
+ .on_mouse_down(MouseButton::Left, |_, _, cx| {
+ cx.stop_propagation();
+ })
+ .on_mouse_down(MouseButton::Right, |_, _, cx| {
+ cx.stop_propagation();
+ })
+ .on_click({
+ move |_event, window, cx| {
+ if let Some(editor) = editor_handle.upgrade() {
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(
+ SelectionEffects::default(),
+ window,
+ cx,
+ |s| {
+ s.select_anchor_ranges([position..position]);
+ },
+ );
+
+ let action = action.clone();
+ if let Some(workspace) = editor.workspace() {
+ if try_handle_client_command(
+ &action, editor, &workspace, window, cx,
+ ) {
+ return;
+ }
+
+ let project = workspace.read(cx).project().clone();
+ if let Some(buffer) = editor
+ .buffer()
+ .read(cx)
+ .buffer(action.range.start.buffer_id)
+ {
+ project
+ .update(cx, |project, cx| {
+ project
+ .apply_code_action(buffer, action, true, cx)
+ })
+ .detach_and_log_err(cx);
+ }
+ }
+ });
+ }
+ }
+ })
+ .into_any_element(),
+ );
+ }
+
+ div()
+ .id(cx.block_id)
+ .pl(cx.margins.gutter.full_width() + cx.em_width * (line.indent_column as f32 + 0.5))
+ .h_full()
+ .flex()
+ .flex_row()
+ .items_end()
+ .children(children)
+ .into_any_element()
+ })
+}
+
#[cfg(test)]
mod tests {
use std::{
@@ -592,7 +657,7 @@ mod tests {
use util::path;
use crate::{
- Editor,
+ Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT,
editor_tests::{init_test, update_test_editor_settings},
test::editor_lsp_test_context::EditorLspTestContext,
};
@@ -660,12 +725,209 @@ mod tests {
let total_blocks: usize = editor
.code_lens
.as_ref()
- .map(|s| s.block_ids.values().map(|v| v.len()).sum())
+ .map(|s| s.blocks.values().map(|v| v.len()).sum())
.unwrap_or(0);
assert_eq!(total_blocks, 2, "Should have inserted two code lens blocks");
});
}
+ #[gpui::test]
+ async fn test_code_lens_blocks_kept_across_refresh(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ update_test_editor_settings(cx, &|settings| {
+ settings.code_lens = Some(CodeLens::On);
+ });
+
+ let mut cx = EditorLspTestContext::new_typescript(
+ lsp::ServerCapabilities {
+ code_lens_provider: Some(lsp::CodeLensOptions {
+ resolve_provider: None,
+ }),
+ execute_command_provider: Some(lsp::ExecuteCommandOptions {
+ commands: vec!["lens_cmd".to_string()],
+ ..lsp::ExecuteCommandOptions::default()
+ }),
+ ..lsp::ServerCapabilities::default()
+ },
+ cx,
+ )
+ .await;
+
+ let mut code_lens_request =
+ cx.set_request_handler::<lsp::request::CodeLensRequest, _, _>(move |_, _, _| async {
+ Ok(Some(vec![lsp::CodeLens {
+ range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 19)),
+ command: Some(lsp::Command {
+ title: "1 reference".to_owned(),
+ command: "lens_cmd".to_owned(),
+ arguments: None,
+ }),
+ data: None,
+ }]))
+ });
+
+ cx.set_state("ˇfunction hello() {}\nfunction world() {}");
+
+ assert!(
+ code_lens_request.next().await.is_some(),
+ "should have received the initial code lens request"
+ );
+ cx.run_until_parked();
+
+ let initial_block_ids = cx.editor.read_with(&cx.cx.cx, |editor, _| {
+ editor
+ .code_lens
+ .as_ref()
+ .map(|s| {
+ s.blocks
+ .values()
+ .flatten()
+ .map(|b| b.block_id)
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default()
+ });
+ assert_eq!(
+ initial_block_ids.len(),
+ 1,
+ "Should have one initial code lens block"
+ );
+
+ cx.update_editor(|editor, window, cx| {
+ editor.move_to_end(&crate::actions::MoveToEnd, window, cx);
+ editor.handle_input("\n// trailing comment", window, cx);
+ });
+ cx.executor()
+ .advance_clock(LSP_REQUEST_DEBOUNCE_TIMEOUT + Duration::from_millis(50));
+ assert!(
+ code_lens_request.next().await.is_some(),
+ "should have received another code lens request after edit"
+ );
+ cx.run_until_parked();
+
+ let refreshed_block_ids = cx.editor.read_with(&cx.cx.cx, |editor, _| {
+ editor
+ .code_lens
+ .as_ref()
+ .map(|s| {
+ s.blocks
+ .values()
+ .flatten()
+ .map(|b| b.block_id)
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default()
+ });
+ assert_eq!(
+ refreshed_block_ids, initial_block_ids,
+ "Code lens blocks should be preserved across refreshes when their content is unchanged"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_code_lens_blocks_kept_when_only_resolve_fills_titles(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ update_test_editor_settings(cx, &|settings| {
+ settings.code_lens = Some(CodeLens::On);
+ });
+
+ let mut cx = EditorLspTestContext::new_typescript(
+ lsp::ServerCapabilities {
+ code_lens_provider: Some(lsp::CodeLensOptions {
+ resolve_provider: Some(true),
+ }),
+ ..lsp::ServerCapabilities::default()
+ },
+ cx,
+ )
+ .await;
+
+ // The LSP returns shallow code lenses on every fetch; only `resolve`
+ // populates the command/title. This is the realistic flow with
+ // servers like rust-analyzer and exercises the path where each
+ // post-edit refresh comes back unresolved before the resolve catches
+ // up.
+ let mut code_lens_request =
+ cx.set_request_handler::<lsp::request::CodeLensRequest, _, _>(move |_, _, _| async {
+ Ok(Some(vec![lsp::CodeLens {
+ range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 19)),
+ command: None,
+ data: Some(serde_json::json!({"id": "lens_1"})),
+ }]))
+ });
+
+ cx.lsp
+ .set_request_handler::<lsp::request::CodeLensResolve, _, _>(|lens, _| async move {
+ Ok(lsp::CodeLens {
+ command: Some(lsp::Command {
+ title: "1 reference".to_owned(),
+ command: "resolved_cmd".to_owned(),
+ arguments: None,
+ }),
+ ..lens
+ })
+ });
+
+ cx.set_state("ˇfunction hello() {}\nfunction world() {}");
+
+ assert!(
+ code_lens_request.next().await.is_some(),
+ "should have received the initial code lens request"
+ );
+ cx.run_until_parked();
+
+ let initial = cx.editor.read_with(&cx.cx.cx, |editor, _| {
+ editor
+ .code_lens
+ .as_ref()
+ .map(|s| {
+ s.blocks
+ .values()
+ .flatten()
+ .map(|b| b.block_id)
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default()
+ });
+ assert_eq!(
+ initial.len(),
+ 1,
+ "resolve should have inserted exactly one block from the shallow lens"
+ );
+
+ for keystroke in [" ", "x", "y"] {
+ cx.update_editor(|editor, window, cx| {
+ editor.move_to_end(&crate::actions::MoveToEnd, window, cx);
+ editor.handle_input(keystroke, window, cx);
+ });
+ cx.executor()
+ .advance_clock(LSP_REQUEST_DEBOUNCE_TIMEOUT + Duration::from_millis(50));
+ assert!(
+ code_lens_request.next().await.is_some(),
+ "should have received another (shallow) code lens request after edit"
+ );
+ cx.run_until_parked();
+
+ let after = cx.editor.read_with(&cx.cx.cx, |editor, _| {
+ editor
+ .code_lens
+ .as_ref()
+ .map(|s| {
+ s.blocks
+ .values()
+ .flatten()
+ .map(|b| b.block_id)
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default()
+ });
+ assert_eq!(
+ after, initial,
+ "Block IDs must survive the unresolved-fetch → resolve cycle without churn"
+ );
+ }
+ }
+
#[gpui::test]
async fn test_code_lens_disabled_by_default(cx: &mut TestAppContext) {
init_test(cx, |_| {});
@@ -754,7 +1016,7 @@ mod tests {
let total_blocks: usize = editor
.code_lens
.as_ref()
- .map(|s| s.block_ids.values().map(|v| v.len()).sum())
+ .map(|s| s.blocks.values().map(|v| v.len()).sum())
.unwrap_or(0);
assert_eq!(total_blocks, 1, "Should have one code lens block");
});
@@ -841,7 +1103,7 @@ mod tests {
let total_blocks: usize = editor
.code_lens
.as_ref()
- .map(|s| s.block_ids.values().map(|v| v.len()).sum())
+ .map(|s| s.blocks.values().map(|v| v.len()).sum())
.unwrap_or(0);
assert_eq!(
total_blocks, 2,