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.

Improve overall compilation stats after the telescope picker feature (#60114)

Kirill Bulatov04efe79649b4
diff --git a/Cargo.lock b/Cargo.lock
index caa07b26757..ab1ad792fb7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6597,6 +6597,7 @@ dependencies = [
"menu",
"open_path_prompt",
"picker",
+ "picker_preview",
"pretty_assertions",
"project",
"project_panel",
@@ -13455,9 +13456,7 @@ dependencies = [
"gpui",
"language",
"menu",
- "multi_buffer",
"project",
- "rope",
"schemars 1.0.4",
"serde",
"serde_json",
@@ -13471,6 +13470,23 @@ dependencies = [
"zed_actions",
]
+[[package]]
+name = "picker_preview"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "editor",
+ "gpui",
+ "language",
+ "multi_buffer",
+ "picker",
+ "project",
+ "rope",
+ "settings",
+ "ui",
+ "util",
+]
+
[[package]]
name = "pico-args"
version = "0.5.0"
@@ -16238,6 +16254,7 @@ dependencies = [
"menu",
"multi_buffer",
"picker",
+ "picker_preview",
"pretty_assertions",
"project",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index 5fc63678142..80cc6501001 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -153,6 +153,7 @@ members = [
"crates/panel",
"crates/paths",
"crates/picker",
+ "crates/picker_preview",
"crates/platform_title_bar",
"crates/prettier",
"crates/project",
@@ -415,6 +416,7 @@ panel = { path = "crates/panel" }
paths = { path = "crates/paths" }
perf = { path = "tooling/perf" }
picker = { path = "crates/picker" }
+picker_preview = { path = "crates/picker_preview" }
prettier = { path = "crates/prettier" }
settings_profile_selector = { path = "crates/settings_profile_selector" }
project = { path = "crates/project" }
diff --git a/crates/file_finder/Cargo.toml b/crates/file_finder/Cargo.toml
index 56901182810..7890bd3a87f 100644
--- a/crates/file_finder/Cargo.toml
+++ b/crates/file_finder/Cargo.toml
@@ -27,6 +27,7 @@ language.workspace = true
menu.workspace = true
open_path_prompt.workspace = true
picker.workspace = true
+picker_preview.workspace = true
project.workspace = true
settings.workspace = true
serde.workspace = true
diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs
index 25a2e5ab0e1..f3711361d13 100644
--- a/crates/file_finder/src/file_finder.rs
+++ b/crates/file_finder/src/file_finder.rs
@@ -170,8 +170,9 @@ impl FileFinder {
let project = delegate.project.clone();
let modal_max_width = Self::modal_max_width(modal_max_width_setting, window);
+ let preview = picker_preview::editor_preview(project, window, cx);
let picker = cx.new(|cx| {
- Picker::uniform_list_with_preview(delegate, project, window, cx)
+ Picker::uniform_list_with_preview(delegate, preview, window, cx)
.initial_width(Rems::from_pixels(modal_max_width, window))
});
let picker_focus_handle = picker.focus_handle(cx);
diff --git a/crates/picker/Cargo.toml b/crates/picker/Cargo.toml
index 0bd29b0a2b9..6dbec3175f0 100644
--- a/crates/picker/Cargo.toml
+++ b/crates/picker/Cargo.toml
@@ -18,9 +18,7 @@ test-support = []
[dependencies]
anyhow.workspace = true
db.workspace = true
-editor.workspace = true
language.workspace = true
-rope.workspace = true
gpui.workspace = true
menu.workspace = true
project.workspace = true
@@ -34,7 +32,6 @@ ui.workspace = true
ui_input.workspace = true
workspace.workspace = true
zed_actions.workspace = true
-multi_buffer.workspace = true
util.workspace = true
[dev-dependencies]
diff --git a/crates/picker/src/picker.rs b/crates/picker/src/picker.rs
index ef58058e5c7..dd0af8ef048 100644
--- a/crates/picker/src/picker.rs
+++ b/crates/picker/src/picker.rs
@@ -1,12 +1,11 @@
use anyhow::Result;
use gpui::Action;
use gpui::{
- AnyElement, App, Bounds, ClickEvent, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
+ AnyElement, App, Bounds, ClickEvent, Context, DismissEvent, EventEmitter, FocusHandle,
Focusable, ListSizingBehavior, ListState, MouseButton, MouseUpEvent, Pixels, ScrollStrategy,
Task, UniformListScrollHandle, Window, actions, canvas, div, list, prelude::*, uniform_list,
};
use head::Head;
-use project::Project;
use schemars::JsonSchema;
use serde::Deserialize;
use std::{
@@ -32,8 +31,10 @@ use crate::shape::RelativeHeight;
use crate::shape::RelativeWidth;
pub use footer::PickerAction;
pub use language::{HighlightedText, HighlightedTextBuilder};
+pub use preview::Layout as PreviewLayout;
pub use preview::MatchLocation;
pub use preview::Preview;
+pub use preview::PreviewBackend;
pub use preview::PreviewSource;
pub use preview::Update as PreviewUpdate;
pub use ui_input::ErasedEditor;
@@ -399,7 +400,7 @@ impl<D: PickerDelegate> Picker<D> {
/// preview window where it shows extra information.
pub fn uniform_list_with_preview(
delegate: D,
- project: Entity<Project>,
+ preview: Arc<dyn PreviewBackend>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
@@ -410,7 +411,7 @@ impl<D: PickerDelegate> Picker<D> {
cx,
);
- let preview = Preview::new_editor(project, window, cx);
+ let preview = Preview::new(preview);
Self::new(
delegate,
ContainerKind::UniformList,
@@ -427,7 +428,7 @@ impl<D: PickerDelegate> Picker<D> {
/// (e.g. section headers and separators interleaved with matches).
pub fn list_with_preview(
delegate: D,
- project: Entity<Project>,
+ preview: Arc<dyn PreviewBackend>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
@@ -438,7 +439,7 @@ impl<D: PickerDelegate> Picker<D> {
cx,
);
- let preview = Preview::new_editor(project, window, cx);
+ let preview = Preview::new(preview);
Self::new(
delegate,
ContainerKind::List,
diff --git a/crates/picker/src/preview.rs b/crates/picker/src/preview.rs
index e529a17d738..88a9b6219db 100644
--- a/crates/picker/src/preview.rs
+++ b/crates/picker/src/preview.rs
@@ -2,31 +2,28 @@ use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
-use editor::{Editor, EditorSettings, HighlightKey, MultiBuffer, RowHighlightOptions};
-use gpui::{App, Task};
-use gpui::{AppContext, Context, Entity, TaskExt, Window};
-use language::{Buffer, HighlightedText, HighlightedTextBuilder, ToPoint};
-use project::Project;
-use rope::Point;
-use settings::Settings;
-use ui::{ActiveTheme, IntoElement, Pixels, px};
-use util::rel_path::RelPath;
-
-pub mod render;
+use gpui::{AnyElement, App, Entity, IntoElement, Window};
+use language::{Anchor, Buffer, HighlightedText};
+
+/// The editor-agnostic interface a [`Picker`](crate::Picker) uses to drive its
+/// preview.
+pub trait PreviewBackend: 'static {
+ fn update(&self, update: Update, window: &mut Window, cx: &mut App);
+ fn render(&self, layout: Layout, cx: &mut App) -> AnyElement;
+ /// Called after a resize to let the preview do resizing logic like scrolling.
+ fn adjust_to_new_size(&self, window: &mut Window, cx: &mut App);
+ /// Empty the preview and show a placeholder message.
+ fn clear(&self, cx: &mut App);
+}
/// The preview window of a [`Picker`](crate::Picker).
-///
-/// Why an enum? While most pickers will want to show just the buffer
-/// there will be some: like bookmarks with description that want to display
-/// other metadata too. A preview for breakpoints could be part editor part
-/// showing any condition (if any) and how many times the breakpoint got hit.
pub struct Preview {
- content: Entity<EditorPreview>,
+ content: Arc<dyn PreviewBackend>,
pub(crate) layout: Layout,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
-pub(crate) enum Layout {
+pub enum Layout {
#[default]
Hidden,
Below,
@@ -34,38 +31,27 @@ pub(crate) enum Layout {
}
impl Preview {
- pub fn new_editor(project: Entity<Project>, window: &mut Window, cx: &mut App) -> Self {
+ pub fn new(content: Arc<dyn PreviewBackend>) -> Self {
Preview {
- content: cx.new(|cx| EditorPreview::new(project, window, cx)),
+ content,
layout: Layout::default(),
}
}
- pub fn update(&mut self, update: Update, window: &mut Window, cx: &mut impl AppContext) {
- // self.content since this will become a match to support non editor or composite previews
- self.content.update(cx, |content, cx| {
- content.update(update, window, cx);
- });
+ pub fn update(&mut self, update: Update, window: &mut Window, cx: &mut App) {
+ self.content.update(update, window, cx);
}
pub fn render(&self, cx: &mut App) -> impl IntoElement {
- let layout = self.layout;
- self.content.update(cx, |content, cx| {
- content.render(layout, cx).into_any_element()
- })
+ self.content.render(self.layout, cx)
}
- /// Called after a resize to let the preview do resizing logic
- /// like scrolling
pub fn adjust_to_new_size(&self, window: &mut Window, cx: &mut App) {
- self.content.update(cx, |content, cx| {
- content.scroll_to_focus_match(window, cx);
- })
+ self.content.adjust_to_new_size(window, cx);
}
- /// Empty the preview and show a placeholder message
pub(crate) fn clear(&self, cx: &mut App) {
- self.content.update(cx, |content, _| content.clear())
+ self.content.clear(cx);
}
}
@@ -91,7 +77,7 @@ pub enum PreviewSource {
pub struct MatchLocation {
/// The location of the match (for highlighting)
- pub anchor_range: Range<language::Anchor>,
+ pub anchor_range: Range<Anchor>,
/// The location of the match as an offset (for scrolling)
pub range: Range<usize>,
}
@@ -132,223 +118,3 @@ impl Update {
}
}
}
-
-struct SearchMatchLineHighlight;
-
-pub struct EditorPreview {
- project: Entity<Project>,
- current_path: Option<Arc<RelPath>>,
- /// When set show a text message instead of a preview
- message: Option<HighlightedText>,
- preview_editor: Entity<Editor>,
-}
-
-impl EditorPreview {
- fn new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let preview_editor = cx.new(|cx: &mut Context<Editor>| {
- let capability = language::Capability::ReadWrite; // Later narrowed per buffer
- let multi_buffer = cx.new(|_| MultiBuffer::without_headers(capability));
- let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
- let editor_settings = EditorSettings::get_global(cx).clone();
-
- // We want editing to happen in the multibuffer not in the modal. The editor acts
- // as one big <send to multibuffer> button.
- editor.set_read_only(true);
- editor.set_input_enabled(false);
- editor.scroll_manager.set_forbid_vertical_scroll(true);
- editor.disable_scrollbars_and_minimap(window, cx);
- editor.disable_inline_diagnostics();
- editor.disable_diagnostics(cx);
- editor.disable_expand_excerpt_buttons(cx);
- editor.disable_mouse_wheel_zoom();
- editor.set_show_gutter(editor_settings.gutter.line_numbers, cx); // needed for line numbers
- editor.set_show_line_numbers(editor_settings.gutter.line_numbers, cx);
- editor.set_show_breakpoints(false, cx);
- editor.set_show_bookmarks(false, cx);
- editor.set_show_code_actions(false, cx);
- editor.set_show_runnables(false, cx);
- editor.set_show_git_diff_gutter(false, cx);
- editor.set_show_wrap_guides(false, cx);
- editor.set_show_indent_guides(false, cx);
- editor.set_show_cursor_when_unfocused(true, cx);
- editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
- editor
- });
-
- let mut this = Self {
- project,
- preview_editor,
- current_path: None,
- message: None,
- };
- this.clear(); // picker starts with no results.
- this
- }
-
- fn clear(&mut self) {
- let mut message = HighlightedTextBuilder::default();
- message.push_plain("No results to preview");
- self.message = Some(message.build());
- }
-
- fn update(&mut self, update: Update, window: &mut Window, cx: &mut Context<Self>) {
- let Update {
- source,
- match_location: highlight,
- } = update;
-
- match source {
- PreviewSource::Path(abs_path) => {
- self.update_from_path(abs_path, highlight, window, cx);
- }
- PreviewSource::Buffer(buffer) => {
- self.update_from_buffer(buffer, highlight, window, cx);
- cx.notify();
- }
- PreviewSource::Message(message) => {
- self.message = Some(message);
- cx.notify();
- }
- }
- }
-
- fn update_from_path(
- &mut self,
- abs_path: PathBuf,
- highlight: Option<MatchLocation>,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let open_task = self.project.update(cx, |project, cx| {
- match project.project_path_for_absolute_path(&abs_path, cx) {
- Some(project_path) => {
- if let Some(buffer) = project.get_open_buffer(&project_path, cx) {
- Task::ready(Ok(buffer))
- } else {
- project.open_buffer(project_path, cx)
- }
- }
- None => project.open_local_buffer(&abs_path, cx),
- }
- });
-
- cx.spawn_in(window, async move |this, cx| {
- let buffer = open_task.await?;
- this.update_in(cx, |this, window, cx| {
- this.update_from_buffer(buffer, highlight, window, cx);
- cx.notify();
- })?;
- anyhow::Ok(())
- })
- .detach_and_log_err(cx);
- }
-
- fn update_from_buffer(
- &mut self,
- buffer: Entity<Buffer>,
- highlight: Option<MatchLocation>,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- self.message = None; // show the preview editor
- self.current_path = buffer.read(cx).file().map(|file| file.path().clone());
-
- const MIN_LINE_HEIGHT_PX: Pixels = px(6.0);
- const MARGIN: u32 = 2; // scrolling can offset things;
- let max_visible_rows =
- (window.viewport_size().height / MIN_LINE_HEIGHT_PX).ceil() as u32 + MARGIN;
-
- self.preview_editor.update(cx, |editor, cx| {
- let focus_row = highlight
- .as_ref()
- .map(|hl| {
- hl.anchor_range
- .start
- .to_point(&buffer.read(cx).text_snapshot())
- .row
- })
- .unwrap_or_default();
-
- let multi_buffer = editor.buffer().clone();
- multi_buffer.update(cx, |multi_buffer, cx| {
- multi_buffer.clear(cx);
- multi_buffer.set_excerpts_for_buffer(
- buffer,
- [Point::new(focus_row, 0)..Point::new(focus_row, 0)],
- max_visible_rows,
- cx,
- );
- });
-
- editor.clear_row_highlights::<SearchMatchLineHighlight>();
- editor.clear_background_highlights(HighlightKey::PickerPreview, cx);
-
- let Some(highlight) = highlight else {
- return;
- };
-
- let mb = multi_buffer.read(cx).snapshot(cx);
- let Some(range) = mb
- .anchor_in_excerpt(highlight.anchor_range.start)
- .zip(mb.anchor_in_excerpt(highlight.anchor_range.end))
- .map(|(start, end)| start..end)
- else {
- return;
- };
-
- editor.highlight_rows::<SearchMatchLineHighlight>(
- range.clone(),
- |cx| cx.theme().colors().editor_active_line_background,
- RowHighlightOptions::default(),
- cx,
- );
-
- editor.highlight_background(
- HighlightKey::PickerPreview,
- &[range],
- |_, theme| theme.colors().search_match_background,
- cx,
- );
- });
- self.scroll_to_focus_match(window, cx);
- }
-
- /// Keep the scroll as far left as possible while showing the match.
- /// Vertically center the match as much as possible
- fn scroll_to_focus_match(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.preview_editor.update(cx, |editor, cx| {
- let display_snapshot = editor.display_snapshot(cx);
- let buffer_snapshot = display_snapshot.buffer_snapshot();
- let search_range = buffer_snapshot.anchor_before(multi_buffer::MultiBufferOffset(0))
- ..buffer_snapshot.anchor_after(buffer_snapshot.len());
-
- // There is at most one highlighted match in the preview, so take the
- // first background highlight range as the match to focus.
- let Some((range, _)) = editor
- .background_highlights_in_range(search_range, &display_snapshot, cx.theme())
- .into_iter()
- .next()
- else {
- return;
- };
-
- let target_row = range.start.row().0 as f64;
- let centered_y = editor
- .visible_line_count()
- .map_or(target_row, |visible_lines| {
- (target_row - (visible_lines - 1.) / 2.).max(0.)
- });
-
- let start_column = range.start.column() as f64;
- let end_column = range.end.column() as f64;
- let centered_x = editor.visible_column_count().map_or(0., |visible_columns| {
- let min_x_for_end = (end_column - visible_columns + 1.).max(0.);
- min_x_for_end.min(start_column)
- });
-
- editor.scroll_manager.set_forbid_vertical_scroll(false);
- editor.set_scroll_position(gpui::Point::new(centered_x, centered_y), window, cx);
- editor.scroll_manager.set_forbid_vertical_scroll(true);
- })
- }
-}
diff --git a/crates/picker/src/preview/render.rs b/crates/picker/src/preview/render.rs
deleted file mode 100644
index aac1d0b96bb..00000000000
--- a/crates/picker/src/preview/render.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-use gpui::{Action, StyledText};
-use language::HighlightedText;
-use ui::prelude::*;
-
-use crate::ToMultiBuffer;
-
-use crate::preview;
-use crate::preview::EditorPreview;
-
-impl EditorPreview {
- pub(crate) fn render(&self, layout: preview::Layout, cx: &App) -> impl IntoElement {
- match layout {
- preview::Layout::Below => self.render_preview_below(cx).into_any_element(),
- preview::Layout::Right => self.render_preview_right(cx).into_any_element(),
- preview::Layout::Hidden => gpui::Empty.into_any_element(),
- }
- }
-}
-
-impl EditorPreview {
- pub(crate) fn render_preview_right(&self, cx: &App) -> impl IntoElement {
- v_flex()
- .size_full()
- .rounded_t_md()
- .rounded_b_md()
- .child(self.render_message_or_editor(cx))
- }
-
- fn render_preview_below(&self, cx: &App) -> impl IntoElement {
- v_flex()
- .size_full()
- .rounded_b_md()
- .child(self.render_message_or_editor(cx))
- }
-
- fn render_message_or_editor(&self, cx: &App) -> impl IntoElement {
- if let Some(message) = &self.message {
- self.render_message(message, cx).into_any_element()
- } else {
- div()
- .flex_1()
- .overflow_hidden()
- .child(self.editor_as_giant_button())
- .into_any_element()
- }
- }
-
- fn render_message(&self, message: &HighlightedText, cx: &App) -> impl IntoElement {
- // `with_highlights` inherits the container's text style (set below),
- // while keeping the message's own highlights (e.g. the file path in
- // the file finder's "Create new file" entry).
- let content = StyledText::new(message.text.clone())
- .with_highlights(message.highlights.iter().cloned())
- .into_any_element();
- v_flex()
- .size_full()
- .items_center()
- .justify_center()
- .font_ui(cx)
- .text_ui(cx)
- .text_color(Color::Muted.color(cx))
- .child(content)
- }
-
- fn editor_as_giant_button(&self) -> impl IntoElement {
- div()
- .relative()
- .size_full()
- .child(self.preview_editor.clone())
- .child(
- div()
- .id("picker-preview-editor")
- .absolute()
- .inset_0()
- .occlude()
- .on_click(|_, window, cx| {
- window.dispatch_action(ToMultiBuffer.boxed_clone(), cx);
- }),
- )
- }
-}
diff --git a/crates/picker/src/preview/state.rs b/crates/picker/src/preview/state.rs
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/crates/picker_preview/Cargo.toml b/crates/picker_preview/Cargo.toml
new file mode 100644
index 00000000000..49417be5435
--- /dev/null
+++ b/crates/picker_preview/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "picker_preview"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/picker_preview.rs"
+doctest = false
+
+[dependencies]
+anyhow.workspace = true
+editor.workspace = true
+gpui.workspace = true
+language.workspace = true
+multi_buffer.workspace = true
+picker.workspace = true
+project.workspace = true
+rope.workspace = true
+settings.workspace = true
+ui.workspace = true
+util.workspace = true
diff --git a/crates/picker_preview/LICENSE-GPL b/crates/picker_preview/LICENSE-GPL
new file mode 120000
index 00000000000..89e542f750c
--- /dev/null
+++ b/crates/picker_preview/LICENSE-GPL
@@ -0,0 +1 @@
+../../LICENSE-GPL
\ No newline at end of file
diff --git a/crates/picker_preview/src/picker_preview.rs b/crates/picker_preview/src/picker_preview.rs
new file mode 100644
index 00000000000..50aff9d3ce7
--- /dev/null
+++ b/crates/picker_preview/src/picker_preview.rs
@@ -0,0 +1,343 @@
+//! The editor-backed implementation of [`picker::PreviewBackend`].
+
+use std::sync::Arc;
+
+use gpui::{
+ Action, AnyElement, App, AppContext as _, Context, Entity, IntoElement, Pixels, StyledText,
+ Task, TaskExt as _, Window, px,
+};
+use language::{Buffer, HighlightedText, HighlightedTextBuilder, ToPoint};
+use picker::{
+ MatchLocation, PreviewBackend, PreviewLayout, PreviewSource, PreviewUpdate, ToMultiBuffer,
+};
+use project::Project;
+use rope::Point;
+use settings::Settings;
+use ui::{ActiveTheme, Color, div, prelude::*, v_flex};
+use util::rel_path::RelPath;
+
+use editor::{Editor, EditorSettings, RowHighlightOptions, display_map::HighlightKey};
+use multi_buffer::{MultiBuffer, MultiBufferOffset};
+
+pub fn editor_preview(
+ project: Entity<Project>,
+ window: &mut Window,
+ cx: &mut App,
+) -> Arc<dyn PreviewBackend> {
+ Arc::new(EditorPreviewHandle(
+ cx.new(|cx| EditorPreview::new(project, window, cx)),
+ ))
+}
+
+struct EditorPreviewHandle(Entity<EditorPreview>);
+
+impl PreviewBackend for EditorPreviewHandle {
+ fn update(&self, update: PreviewUpdate, window: &mut Window, cx: &mut App) {
+ self.0
+ .update(cx, |content, cx| content.update(update, window, cx));
+ }
+
+ fn render(&self, layout: PreviewLayout, cx: &mut App) -> AnyElement {
+ self.0.update(cx, |content, cx| {
+ content.render(layout, cx).into_any_element()
+ })
+ }
+
+ fn adjust_to_new_size(&self, window: &mut Window, cx: &mut App) {
+ self.0
+ .update(cx, |content, cx| content.scroll_to_focus_match(window, cx));
+ }
+
+ fn clear(&self, cx: &mut App) {
+ self.0.update(cx, |content, _| content.clear());
+ }
+}
+
+struct SearchMatchLineHighlight;
+
+struct EditorPreview {
+ project: Entity<Project>,
+ current_path: Option<Arc<RelPath>>,
+ /// When set show a text message instead of a preview
+ message: Option<HighlightedText>,
+ preview_editor: Entity<Editor>,
+}
+
+impl EditorPreview {
+ fn new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let preview_editor = cx.new(|cx: &mut Context<Editor>| {
+ let capability = language::Capability::ReadWrite; // Later narrowed per buffer
+ let multi_buffer = cx.new(|_| MultiBuffer::without_headers(capability));
+ let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
+ let editor_settings = EditorSettings::get_global(cx).clone();
+
+ // We want editing to happen in the multibuffer not in the modal. The editor acts
+ // as one big <send to multibuffer> button.
+ editor.set_read_only(true);
+ editor.set_input_enabled(false);
+ editor.scroll_manager.set_forbid_vertical_scroll(true);
+ editor.disable_scrollbars_and_minimap(window, cx);
+ editor.disable_inline_diagnostics();
+ editor.disable_diagnostics(cx);
+ editor.disable_expand_excerpt_buttons(cx);
+ editor.disable_mouse_wheel_zoom();
+ editor.set_show_gutter(editor_settings.gutter.line_numbers, cx); // needed for line numbers
+ editor.set_show_line_numbers(editor_settings.gutter.line_numbers, cx);
+ editor.set_show_breakpoints(false, cx);
+ editor.set_show_bookmarks(false, cx);
+ editor.set_show_code_actions(false, cx);
+ editor.set_show_runnables(false, cx);
+ editor.set_show_git_diff_gutter(false, cx);
+ editor.set_show_wrap_guides(false, cx);
+ editor.set_show_indent_guides(false, cx);
+ editor.set_show_cursor_when_unfocused(true, cx);
+ editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
+ editor
+ });
+
+ let mut this = Self {
+ project,
+ preview_editor,
+ current_path: None,
+ message: None,
+ };
+ this.clear(); // picker starts with no results.
+ this
+ }
+
+ fn clear(&mut self) {
+ let mut message = HighlightedTextBuilder::default();
+ message.push_plain("No results to preview");
+ self.message = Some(message.build());
+ }
+
+ fn update(&mut self, update: PreviewUpdate, window: &mut Window, cx: &mut Context<Self>) {
+ let PreviewUpdate {
+ source,
+ match_location: highlight,
+ } = update;
+
+ match source {
+ PreviewSource::Path(abs_path) => {
+ self.update_from_path(abs_path, highlight, window, cx);
+ }
+ PreviewSource::Buffer(buffer) => {
+ self.update_from_buffer(buffer, highlight, window, cx);
+ cx.notify();
+ }
+ PreviewSource::Message(message) => {
+ self.message = Some(message);
+ cx.notify();
+ }
+ }
+ }
+
+ fn update_from_path(
+ &mut self,
+ abs_path: std::path::PathBuf,
+ highlight: Option<MatchLocation>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let open_task = self.project.update(cx, |project, cx| {
+ match project.project_path_for_absolute_path(&abs_path, cx) {
+ Some(project_path) => {
+ if let Some(buffer) = project.get_open_buffer(&project_path, cx) {
+ Task::ready(Ok(buffer))
+ } else {
+ project.open_buffer(project_path, cx)
+ }
+ }
+ None => project.open_local_buffer(&abs_path, cx),
+ }
+ });
+
+ cx.spawn_in(window, async move |this, cx| {
+ let buffer = open_task.await?;
+ this.update_in(cx, |this, window, cx| {
+ this.update_from_buffer(buffer, highlight, window, cx);
+ cx.notify();
+ })?;
+ anyhow::Ok(())
+ })
+ .detach_and_log_err(cx);
+ }
+
+ fn update_from_buffer(
+ &mut self,
+ buffer: Entity<Buffer>,
+ highlight: Option<MatchLocation>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.message = None; // show the preview editor
+ self.current_path = buffer.read(cx).file().map(|file| file.path().clone());
+
+ const MIN_LINE_HEIGHT_PX: Pixels = px(6.0);
+ const MARGIN: u32 = 2; // scrolling can offset things;
+ let max_visible_rows =
+ (window.viewport_size().height / MIN_LINE_HEIGHT_PX).ceil() as u32 + MARGIN;
+
+ self.preview_editor.update(cx, |editor, cx| {
+ let focus_row = highlight
+ .as_ref()
+ .map(|hl| {
+ hl.anchor_range
+ .start
+ .to_point(&buffer.read(cx).text_snapshot())
+ .row
+ })
+ .unwrap_or_default();
+
+ let multi_buffer = editor.buffer().clone();
+ multi_buffer.update(cx, |multi_buffer, cx| {
+ multi_buffer.clear(cx);
+ multi_buffer.set_excerpts_for_buffer(
+ buffer,
+ [Point::new(focus_row, 0)..Point::new(focus_row, 0)],
+ max_visible_rows,
+ cx,
+ );
+ });
+
+ editor.clear_row_highlights::<SearchMatchLineHighlight>();
+ editor.clear_background_highlights(HighlightKey::PickerPreview, cx);
+
+ let Some(highlight) = highlight else {
+ return;
+ };
+
+ let mb = multi_buffer.read(cx).snapshot(cx);
+ let Some(range) = mb
+ .anchor_in_excerpt(highlight.anchor_range.start)
+ .zip(mb.anchor_in_excerpt(highlight.anchor_range.end))
+ .map(|(start, end)| start..end)
+ else {
+ return;
+ };
+
+ editor.highlight_rows::<SearchMatchLineHighlight>(
+ range.clone(),
+ |cx| cx.theme().colors().editor_active_line_background,
+ RowHighlightOptions::default(),
+ cx,
+ );
+
+ editor.highlight_background(
+ HighlightKey::PickerPreview,
+ &[range],
+ |_, theme| theme.colors().search_match_background,
+ cx,
+ );
+ });
+ self.scroll_to_focus_match(window, cx);
+ }
+
+ /// Keep the scroll as far left as possible while showing the match.
+ /// Vertically center the match as much as possible
+ fn scroll_to_focus_match(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.preview_editor.update(cx, |editor, cx| {
+ let display_snapshot = editor.display_snapshot(cx);
+ let buffer_snapshot = display_snapshot.buffer_snapshot();
+ let search_range = buffer_snapshot.anchor_before(MultiBufferOffset(0))
+ ..buffer_snapshot.anchor_after(buffer_snapshot.len());
+
+ // There is at most one highlighted match in the preview, so take the
+ // first background highlight range as the match to focus.
+ let Some((range, _)) = editor
+ .background_highlights_in_range(search_range, &display_snapshot, cx.theme())
+ .into_iter()
+ .next()
+ else {
+ return;
+ };
+
+ let target_row = range.start.row().0 as f64;
+ let centered_y = editor
+ .visible_line_count()
+ .map_or(target_row, |visible_lines| {
+ (target_row - (visible_lines - 1.) / 2.).max(0.)
+ });
+
+ let start_column = range.start.column() as f64;
+ let end_column = range.end.column() as f64;
+ let centered_x = editor.visible_column_count().map_or(0., |visible_columns| {
+ let min_x_for_end = (end_column - visible_columns + 1.).max(0.);
+ min_x_for_end.min(start_column)
+ });
+
+ editor.scroll_manager.set_forbid_vertical_scroll(false);
+ editor.set_scroll_position(gpui::Point::new(centered_x, centered_y), window, cx);
+ editor.scroll_manager.set_forbid_vertical_scroll(true);
+ })
+ }
+
+ fn render(&self, layout: PreviewLayout, cx: &App) -> impl IntoElement {
+ match layout {
+ PreviewLayout::Below => self.render_preview_below(cx).into_any_element(),
+ PreviewLayout::Right => self.render_preview_right(cx).into_any_element(),
+ PreviewLayout::Hidden => gpui::Empty.into_any_element(),
+ }
+ }
+
+ fn render_preview_right(&self, cx: &App) -> impl IntoElement {
+ v_flex()
+ .size_full()
+ .rounded_t_md()
+ .rounded_b_md()
+ .child(self.render_message_or_editor(cx))
+ }
+
+ fn render_preview_below(&self, cx: &App) -> impl IntoElement {
+ v_flex()
+ .size_full()
+ .rounded_b_md()
+ .child(self.render_message_or_editor(cx))
+ }
+
+ fn render_message_or_editor(&self, cx: &App) -> impl IntoElement {
+ if let Some(message) = &self.message {
+ self.render_message(message, cx).into_any_element()
+ } else {
+ div()
+ .flex_1()
+ .overflow_hidden()
+ .child(self.editor_as_giant_button())
+ .into_any_element()
+ }
+ }
+
+ fn render_message(&self, message: &HighlightedText, cx: &App) -> impl IntoElement {
+ // `with_highlights` inherits the container's text style (set below),
+ // while keeping the message's own highlights (e.g. the file path in
+ // the file finder's "Create new file" entry).
+ let content = StyledText::new(message.text.clone())
+ .with_highlights(message.highlights.iter().cloned())
+ .into_any_element();
+ v_flex()
+ .size_full()
+ .items_center()
+ .justify_center()
+ .font_ui(cx)
+ .text_ui(cx)
+ .text_color(Color::Muted.color(cx))
+ .child(content)
+ }
+
+ fn editor_as_giant_button(&self) -> impl IntoElement {
+ div()
+ .relative()
+ .size_full()
+ .child(self.preview_editor.clone())
+ .child(
+ div()
+ .id("picker-preview-editor")
+ .absolute()
+ .inset_0()
+ .occlude()
+ .on_click(|_, window, cx| {
+ window.dispatch_action(ToMultiBuffer.boxed_clone(), cx);
+ }),
+ )
+ }
+}
diff --git a/crates/search/Cargo.toml b/crates/search/Cargo.toml
index 3ef52302fa2..56d7e2b37d7 100644
--- a/crates/search/Cargo.toml
+++ b/crates/search/Cargo.toml
@@ -34,6 +34,7 @@ language.workspace = true
menu.workspace = true
multi_buffer.workspace = true
picker.workspace = true
+picker_preview.workspace = true
project.workspace = true
serde.workspace = true
serde_json.workspace = true
diff --git a/crates/search/src/text_finder.rs b/crates/search/src/text_finder.rs
index fde2f6da537..040a45ec3ec 100644
--- a/crates/search/src/text_finder.rs
+++ b/crates/search/src/text_finder.rs
@@ -265,7 +265,8 @@ impl TextFinder {
cx: &mut Context<Self>,
) -> Self {
let project = delegate.project(cx).clone();
- let picker = cx.new(|cx| Picker::list_with_preview(delegate, project, window, cx));
+ let preview = picker_preview::editor_preview(project, window, cx);
+ let picker = cx.new(|cx| Picker::list_with_preview(delegate, preview, window, cx));
let picker_weak = picker.downgrade();
let picker_focus_handle = picker.focus_handle(cx);
picker.update(cx, |picker, cx| {