on master help sign in
Merge pull request #7264 from the-mikedavis/merge-picker-and-filepicker

Merge FilePicker into Picker

commit06d63d6ac1644ce57d6a90b53ea4f832e67ab2a9 authorPascal Kuthe <pascal.kuthe@semimod.de> dateMon 19 Jun 2023, 04:18 (3 years ago) parent29638baf18acad
5 files changed+490−556
helix-term/src/commands.rs+24−30 helix-term/src/commands/dap.rs+44−50 helix-term/src/commands/lsp.rs+41−49 helix-term/src/ui/mod.rs+13−17 helix-term/src/ui/picker.rs+368−410
helix-term/src/commands.rs+24−30
@@ -55,8 +55,8 @@ use crate::{
5555 job::Callback,
5656 keymap::ReverseKeymap,
5757 ui::{
58− self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem,
59− FilePicker, Picker, Popup, Prompt, PromptEvent,
58+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
59+ Popup, Prompt, PromptEvent,
6060 },
6161};
6262
@@ -2156,7 +2156,7 @@ fn global_search(cx: &mut Context) {
21562156 return;
21572157 }
21582158
2159− let picker = FilePicker::new(
2159+ let picker = Picker::new(
21602160 all_matches,
21612161 current_path,
21622162 move |cx, FileResult { path, line_num }, action| {
@@ -2184,11 +2184,9 @@ fn global_search(cx: &mut Context) {
21842184
21852185 doc.set_selection(view.id, Selection::single(start, end));
21862186 align_view(doc, view, Align::Center);
2187− },
2188− |_editor, FileResult { path, line_num }| {
2187+ }).with_preview(|_editor, FileResult { path, line_num }| {
21892188 Some((path.clone().into(), Some((*line_num, *line_num))))
2190− },
2191− );
2189+ });
21922190 compositor.push(Box::new(overlaid(picker)));
21932191 },
21942192 ));
@@ -2579,22 +2577,18 @@ fn buffer_picker(cx: &mut Context) {
25792577 // mru
25802578 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
25812579
2582− let picker = FilePicker::new(
2583− items,
2584− (),
2585− |cx, meta, action| {
2586− cx.editor.switch(meta.id, action);
2587− },
2588− |editor, meta| {
2589− let doc = &editor.documents.get(&meta.id)?;
2590− let &view_id = doc.selections().keys().next()?;
2591− let line = doc
2592− .selection(view_id)
2593− .primary()
2594− .cursor_line(doc.text().slice(..));
2595− Some((meta.id.into(), Some((line, line))))
2596− },
2597− );
2580+ let picker = Picker::new(items, (), |cx, meta, action| {
2581+ cx.editor.switch(meta.id, action);
2582+ })
2583+ .with_preview(|editor, meta| {
2584+ let doc = &editor.documents.get(&meta.id)?;
2585+ let &view_id = doc.selections().keys().next()?;
2586+ let line = doc
2587+ .selection(view_id)
2588+ .primary()
2589+ .cursor_line(doc.text().slice(..));
2590+ Some((meta.id.into(), Some((line, line))))
2591+ });
25982592 cx.push_layer(Box::new(overlaid(picker)));
25992593}
26002594
@@ -2660,7 +2654,7 @@ fn jumplist_picker(cx: &mut Context) {
26602654 }
26612655 };
26622656
2663− let picker = FilePicker::new(
2657+ let picker = Picker::new(
26642658 cx.editor
26652659 .tree
26662660 .views()
@@ -2678,12 +2672,12 @@ fn jumplist_picker(cx: &mut Context) {
26782672 doc.set_selection(view.id, meta.selection.clone());
26792673 view.ensure_cursor_in_view_center(doc, config.scrolloff);
26802674 },
2681− |editor, meta| {
2682− let doc = &editor.documents.get(&meta.id)?;
2683− let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2684− Some((meta.id.into(), Some((line, line))))
2685− },
2686− );
2675+ )
2676+ .with_preview(|editor, meta| {
2677+ let doc = &editor.documents.get(&meta.id)?;
2678+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2679+ Some((meta.id.into(), Some((line, line))))
2680+ });
26872681 cx.push_layer(Box::new(overlaid(picker)));
26882682}
26892683
helix-term/src/commands/dap.rs+44−50
@@ -2,7 +2,7 @@ use super::{Context, Editor};
22use crate::{
33 compositor::{self, Compositor},
44 job::{Callback, Jobs},
5− ui::{self, overlay::overlaid, FilePicker, Picker, Popup, Prompt, PromptEvent, Text},
5+ ui::{self, overlay::overlaid, Picker, Popup, Prompt, PromptEvent, Text},
66};
77use dap::{StackFrame, Thread, ThreadStates};
88use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate};
@@ -73,21 +73,19 @@ fn thread_picker(
7373 let debugger = debugger!(editor);
7474
7575 let thread_states = debugger.thread_states.clone();
76− let picker = FilePicker::new(
77− threads,
78− thread_states,
79− move |cx, thread, _action| callback_fn(cx.editor, thread),
80− move |editor, thread| {
81− let frames = editor.debugger.as_ref()?.stack_frames.get(&thread.id)?;
82− let frame = frames.get(0)?;
83− let path = frame.source.as_ref()?.path.clone()?;
84− let pos = Some((
85− frame.line.saturating_sub(1),
86− frame.end_line.unwrap_or(frame.line).saturating_sub(1),
87− ));
88− Some((path.into(), pos))
89− },
90− );
76+ let picker = Picker::new(threads, thread_states, move |cx, thread, _action| {
77+ callback_fn(cx.editor, thread)
78+ })
79+ .with_preview(move |editor, thread| {
80+ let frames = editor.debugger.as_ref()?.stack_frames.get(&thread.id)?;
81+ let frame = frames.get(0)?;
82+ let path = frame.source.as_ref()?.path.clone()?;
83+ let pos = Some((
84+ frame.line.saturating_sub(1),
85+ frame.end_line.unwrap_or(frame.line).saturating_sub(1),
86+ ));
87+ Some((path.into(), pos))
88+ });
9189 compositor.push(Box::new(picker));
9290 },
9391 );
@@ -728,39 +726,35 @@ pub fn dap_switch_stack_frame(cx: &mut Context) {
728726
729727 let frames = debugger.stack_frames[&thread_id].clone();
730728
731− let picker = FilePicker::new(
732− frames,
733− (),
734− move |cx, frame, _action| {
735− let debugger = debugger!(cx.editor);
736− // TODO: this should be simpler to find
737− let pos = debugger.stack_frames[&thread_id]
738− .iter()
739− .position(|f| f.id == frame.id);
740− debugger.active_frame = pos;
741−
742− let frame = debugger.stack_frames[&thread_id]
743− .get(pos.unwrap_or(0))
744− .cloned();
745− if let Some(frame) = &frame {
746− jump_to_stack_frame(cx.editor, frame);
747− }
748− },
749− move |_editor, frame| {
750− frame
751− .source
752− .as_ref()
753− .and_then(|source| source.path.clone())
754− .map(|path| {
755− (
756− path.into(),
757− Some((
758− frame.line.saturating_sub(1),
759− frame.end_line.unwrap_or(frame.line).saturating_sub(1),
760− )),
761− )
762− })
763− },
764− );
729+ let picker = Picker::new(frames, (), move |cx, frame, _action| {
730+ let debugger = debugger!(cx.editor);
731+ // TODO: this should be simpler to find
732+ let pos = debugger.stack_frames[&thread_id]
733+ .iter()
734+ .position(|f| f.id == frame.id);
735+ debugger.active_frame = pos;
736+
737+ let frame = debugger.stack_frames[&thread_id]
738+ .get(pos.unwrap_or(0))
739+ .cloned();
740+ if let Some(frame) = &frame {
741+ jump_to_stack_frame(cx.editor, frame);
742+ }
743+ })
744+ .with_preview(move |_editor, frame| {
745+ frame
746+ .source
747+ .as_ref()
748+ .and_then(|source| source.path.clone())
749+ .map(|path| {
750+ (
751+ path.into(),
752+ Some((
753+ frame.line.saturating_sub(1),
754+ frame.end_line.unwrap_or(frame.line).saturating_sub(1),
755+ )),
756+ )
757+ })
758+ });
765759 cx.push_layer(Box::new(picker))
766760}
helix-term/src/commands/lsp.rs+41−49
@@ -31,8 +31,8 @@ use crate::{
3131 compositor::{self, Compositor},
3232 job::Callback,
3333 ui::{
34− self, lsp::SignatureHelp, overlay::overlaid, DynamicPicker, FileLocation, FilePicker,
35− Popup, PromptEvent,
34+ self, lsp::SignatureHelp, overlay::overlaid, DynamicPicker, FileLocation, Picker, Popup,
35+ PromptEvent,
3636 },
3737};
3838
@@ -236,48 +236,44 @@ fn jump_to_location(
236236 align_view(doc, view, Align::Center);
237237}
238238
239−type SymbolPicker = FilePicker<SymbolInformationItem>;
239+type SymbolPicker = Picker<SymbolInformationItem>;
240240
241241fn sym_picker(symbols: Vec<SymbolInformationItem>, current_path: Option<lsp::Url>) -> SymbolPicker {
242242 // TODO: drop current_path comparison and instead use workspace: bool flag?
243− FilePicker::new(
244− symbols,
245− current_path.clone(),
246− move |cx, item, action| {
247− let (view, doc) = current!(cx.editor);
248− push_jump(view, doc);
249−
250− if current_path.as_ref() != Some(&item.symbol.location.uri) {
251− let uri = &item.symbol.location.uri;
252− let path = match uri.to_file_path() {
253− Ok(path) => path,
254− Err(_) => {
255− let err = format!("unable to convert URI to filepath: {}", uri);
256− cx.editor.set_error(err);
257− return;
258− }
259− };
260− if let Err(err) = cx.editor.open(&path, action) {
261− let err = format!("failed to open document: {}: {}", uri, err);
262− log::error!("{}", err);
243+ Picker::new(symbols, current_path.clone(), move |cx, item, action| {
244+ let (view, doc) = current!(cx.editor);
245+ push_jump(view, doc);
246+
247+ if current_path.as_ref() != Some(&item.symbol.location.uri) {
248+ let uri = &item.symbol.location.uri;
249+ let path = match uri.to_file_path() {
250+ Ok(path) => path,
251+ Err(_) => {
252+ let err = format!("unable to convert URI to filepath: {}", uri);
263253 cx.editor.set_error(err);
264254 return;
265255 }
256+ };
257+ if let Err(err) = cx.editor.open(&path, action) {
258+ let err = format!("failed to open document: {}: {}", uri, err);
259+ log::error!("{}", err);
260+ cx.editor.set_error(err);
261+ return;
266262 }
263+ }
267264
268− let (view, doc) = current!(cx.editor);
265+ let (view, doc) = current!(cx.editor);
269266
270− if let Some(range) =
271− lsp_range_to_range(doc.text(), item.symbol.location.range, item.offset_encoding)
272− {
273− // we flip the range so that the cursor sits on the start of the symbol
274− // (for example start of the function).
275− doc.set_selection(view.id, Selection::single(range.head, range.anchor));
276− align_view(doc, view, Align::Center);
277− }
278− },
279− move |_editor, item| Some(location_to_file_location(&item.symbol.location)),
280− )
267+ if let Some(range) =
268+ lsp_range_to_range(doc.text(), item.symbol.location.range, item.offset_encoding)
269+ {
270+ // we flip the range so that the cursor sits on the start of the symbol
271+ // (for example start of the function).
272+ doc.set_selection(view.id, Selection::single(range.head, range.anchor));
273+ align_view(doc, view, Align::Center);
274+ }
275+ })
276+ .with_preview(move |_editor, item| Some(location_to_file_location(&item.symbol.location)))
281277 .truncate_start(false)
282278}
283279
@@ -292,7 +288,7 @@ fn diag_picker(
292288 diagnostics: BTreeMap<lsp::Url, Vec<(lsp::Diagnostic, usize)>>,
293289 current_path: Option<lsp::Url>,
294290 format: DiagnosticsFormat,
295−) -> FilePicker<PickerDiagnostic> {
291+) -> Picker<PickerDiagnostic> {
296292 // TODO: drop current_path comparison and instead use workspace: bool flag?
297293
298294 // flatten the map to a vec of (url, diag) pairs
@@ -318,7 +314,7 @@ fn diag_picker(
318314 error: cx.editor.theme.get("error"),
319315 };
320316
321− FilePicker::new(
317+ Picker::new(
322318 flat_diag,
323319 (styles, format),
324320 move |cx,
@@ -345,11 +341,11 @@ fn diag_picker(
345341 align_view(doc, view, Align::Center);
346342 }
347343 },
348− move |_editor, PickerDiagnostic { url, diag, .. }| {
349− let location = lsp::Location::new(url.clone(), diag.range);
350− Some(location_to_file_location(&location))
351− },
352344 )
345+ .with_preview(move |_editor, PickerDiagnostic { url, diag, .. }| {
346+ let location = lsp::Location::new(url.clone(), diag.range);
347+ Some(location_to_file_location(&location))
348+ })
353349 .truncate_start(false)
354350}
355351
@@ -1047,14 +1043,10 @@ fn goto_impl(
10471043 editor.set_error("No definition found.");
10481044 }
10491045 _locations => {
1050− let picker = FilePicker::new(
1051− locations,
1052− cwdir,
1053− move |cx, location, action| {
1054− jump_to_location(cx.editor, location, offset_encoding, action)
1055− },
1056− move |_editor, location| Some(location_to_file_location(location)),
1057− );
1046+ let picker = Picker::new(locations, cwdir, move |cx, location, action| {
1047+ jump_to_location(cx.editor, location, offset_encoding, action)
1048+ })
1049+ .with_preview(move |_editor, location| Some(location_to_file_location(location)));
10581050 compositor.push(Box::new(overlaid(picker)));
10591051 }
10601052 }
helix-term/src/ui/mod.rs+13−17
@@ -21,7 +21,7 @@ pub use completion::{Completion, CompletionItem};
2121pub use editor::EditorView;
2222pub use markdown::Markdown;
2323pub use menu::Menu;
24−pub use picker::{DynamicPicker, FileLocation, FilePicker, Picker};
24+pub use picker::{DynamicPicker, FileLocation, Picker};
2525pub use popup::Popup;
2626pub use prompt::{Prompt, PromptEvent};
2727pub use spinner::{ProgressSpinners, Spinner};
@@ -158,7 +158,7 @@ pub fn regex_prompt(
158158 cx.push_layer(Box::new(prompt));
159159}
160160
161−pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePicker<PathBuf> {
161+pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> Picker<PathBuf> {
162162 use ignore::{types::TypesBuilder, WalkBuilder};
163163 use std::time::Instant;
164164
@@ -217,21 +217,17 @@ pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePi
217217
218218 log::debug!("file_picker init {:?}", Instant::now().duration_since(now));
219219
220− FilePicker::new(
221− files,
222− root,
223− move |cx, path: &PathBuf, action| {
224− if let Err(e) = cx.editor.open(path, action) {
225− let err = if let Some(err) = e.source() {
226− format!("{}", err)
227− } else {
228− format!("unable to open \"{}\"", path.display())
229− };
230− cx.editor.set_error(err);
231− }
232− },
233− |_editor, path| Some((path.clone().into(), None)),
234− )
220+ Picker::new(files, root, move |cx, path: &PathBuf, action| {
221+ if let Err(e) = cx.editor.open(path, action) {
222+ let err = if let Some(err) = e.source() {
223+ format!("{}", err)
224+ } else {
225+ format!("unable to open \"{}\"", path.display())
226+ };
227+ cx.editor.set_error(err);
228+ }
229+ })
230+ .with_preview(|_editor, path| Some((path.clone().into(), None)))
235231}
236232
237233pub mod completers {
helix-term/src/ui/picker.rs+368−410
@@ -77,16 +77,6 @@ type FileCallback<T> = Box<dyn Fn(&Editor, &T) -> Option<FileLocation>>;
7777/// File path and range of lines (used to align and highlight lines)
7878pub type FileLocation = (PathOrId, Option<(usize, usize)>);
7979
80−pub struct FilePicker<T: Item> {
81− picker: Picker<T>,
82− pub truncate_start: bool,
83− /// Caches paths to documents
84− preview_cache: HashMap<PathBuf, CachedPreview>,
85− read_buffer: Vec<u8>,
86− /// Given an item in the picker, return the file path and line number to display.
87− file_fn: FileCallback<T>,
88−}
89−
9080pub enum CachedPreview {
9181 Document(Box<Document>),
9282 Binary,
@@ -124,325 +114,6 @@ impl Preview<'_, '_> {
124114 }
125115}
126116
127−impl<T: Item + 'static> FilePicker<T> {
128− pub fn new(
129− options: Vec<T>,
130− editor_data: T::Data,
131− callback_fn: impl Fn(&mut Context, &T, Action) + 'static,
132− preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
133− ) -> Self {
134− let truncate_start = true;
135− let mut picker = Picker::new(options, editor_data, callback_fn);
136− picker.truncate_start = truncate_start;
137−
138− Self {
139− picker,
140− truncate_start,
141− preview_cache: HashMap::new(),
142− read_buffer: Vec::with_capacity(1024),
143− file_fn: Box::new(preview_fn),
144− }
145− }
146−
147− pub fn truncate_start(mut self, truncate_start: bool) -> Self {
148− self.truncate_start = truncate_start;
149− self.picker.truncate_start = truncate_start;
150− self
151− }
152−
153− fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
154− self.picker
155− .selection()
156− .and_then(|current| (self.file_fn)(editor, current))
157− .and_then(|(path_or_id, line)| path_or_id.get_canonicalized().ok().zip(Some(line)))
158− }
159−
160− /// Get (cached) preview for a given path. If a document corresponding
161− /// to the path is already open in the editor, it is used instead.
162− fn get_preview<'picker, 'editor>(
163− &'picker mut self,
164− path_or_id: PathOrId,
165− editor: &'editor Editor,
166− ) -> Preview<'picker, 'editor> {
167− match path_or_id {
168− PathOrId::Path(path) => {
169− let path = &path;
170− if let Some(doc) = editor.document_by_path(path) {
171− return Preview::EditorDocument(doc);
172− }
173−
174− if self.preview_cache.contains_key(path) {
175− return Preview::Cached(&self.preview_cache[path]);
176− }
177−
178− let data = std::fs::File::open(path).and_then(|file| {
179− let metadata = file.metadata()?;
180− // Read up to 1kb to detect the content type
181− let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
182− let content_type = content_inspector::inspect(&self.read_buffer[..n]);
183− self.read_buffer.clear();
184− Ok((metadata, content_type))
185− });
186− let preview = data
187− .map(
188− |(metadata, content_type)| match (metadata.len(), content_type) {
189− (_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
190− (size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => {
191− CachedPreview::LargeFile
192− }
193− _ => {
194− // TODO: enable syntax highlighting; blocked by async rendering
195− Document::open(path, None, None, editor.config.clone())
196− .map(|doc| CachedPreview::Document(Box::new(doc)))
197− .unwrap_or(CachedPreview::NotFound)
198− }
199− },
200− )
201− .unwrap_or(CachedPreview::NotFound);
202− self.preview_cache.insert(path.to_owned(), preview);
203− Preview::Cached(&self.preview_cache[path])
204− }
205− PathOrId::Id(id) => {
206− let doc = editor.documents.get(&id).unwrap();
207− Preview::EditorDocument(doc)
208− }
209− }
210− }
211−
212− fn handle_idle_timeout(&mut self, cx: &mut Context) -> EventResult {
213− let Some((current_file, _)) = self.current_file(cx.editor) else {
214− return EventResult::Consumed(None)
215− };
216−
217− // Try to find a document in the cache
218− let doc = match &current_file {
219− PathOrId::Id(doc_id) => doc_mut!(cx.editor, doc_id),
220− PathOrId::Path(path) => match self.preview_cache.get_mut(path) {
221− Some(CachedPreview::Document(ref mut doc)) => doc,
222− _ => return EventResult::Consumed(None),
223− },
224− };
225−
226− let mut callback: Option<compositor::Callback> = None;
227−
228− // Then attempt to highlight it if it has no language set
229− if doc.language_config().is_none() {
230− if let Some(language_config) = doc.detect_language_config(&cx.editor.syn_loader) {
231− doc.language = Some(language_config.clone());
232− let text = doc.text().clone();
233− let loader = cx.editor.syn_loader.clone();
234− let job = tokio::task::spawn_blocking(move || {
235− let syntax = language_config
236− .highlight_config(&loader.scopes())
237− .and_then(|highlight_config| Syntax::new(&text, highlight_config, loader));
238− let callback = move |editor: &mut Editor, compositor: &mut Compositor| {
239− let Some(syntax) = syntax else {
240− log::info!("highlighting picker item failed");
241− return
242− };
243− let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
244− log::info!("picker closed before syntax highlighting finished");
245− return
246− };
247− // Try to find a document in the cache
248− let doc = match current_file {
249− PathOrId::Id(doc_id) => doc_mut!(editor, &doc_id),
250− PathOrId::Path(path) => match picker.preview_cache.get_mut(&path) {
251− Some(CachedPreview::Document(ref mut doc)) => doc,
252− _ => return,
253− },
254− };
255− doc.syntax = Some(syntax);
256− };
257− Callback::EditorCompositor(Box::new(callback))
258− });
259− let tmp: compositor::Callback = Box::new(move |_, ctx| {
260− ctx.jobs
261− .callback(job.map(|res| res.map_err(anyhow::Error::from)))
262− });
263− callback = Some(Box::new(tmp))
264− }
265− }
266−
267− // QUESTION: do we want to compute inlay hints in pickers too ? Probably not for now
268− // but it could be interesting in the future
269−
270− EventResult::Consumed(callback)
271− }
272−}
273−
274−impl<T: Item + 'static> Component for FilePicker<T> {
275− fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
276− // +---------+ +---------+
277− // |prompt | |preview |
278− // +---------+ | |
279− // |picker | | |
280− // | | | |
281− // +---------+ +---------+
282−
283− let render_preview = self.picker.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
284− // -- Render the frame:
285− // clear area
286− let background = cx.editor.theme.get("ui.background");
287− let text = cx.editor.theme.get("ui.text");
288− surface.clear_with(area, background);
289−
290− let picker_width = if render_preview {
291− area.width / 2
292− } else {
293− area.width
294− };
295−
296− let picker_area = area.with_width(picker_width);
297− self.picker.render(picker_area, surface, cx);
298−
299− if !render_preview {
300− return;
301− }
302−
303− let preview_area = area.clip_left(picker_width);
304−
305− // don't like this but the lifetime sucks
306− let block = Block::default().borders(Borders::ALL);
307−
308− // calculate the inner area inside the box
309− let inner = block.inner(preview_area);
310− // 1 column gap on either side
311− let margin = Margin::horizontal(1);
312− let inner = inner.inner(&margin);
313− block.render(preview_area, surface);
314−
315− if let Some((path, range)) = self.current_file(cx.editor) {
316− let preview = self.get_preview(path, cx.editor);
317− let doc = match preview.document() {
318− Some(doc) => doc,
319− None => {
320− let alt_text = preview.placeholder();
321− let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
322− let y = inner.y + inner.height / 2;
323− surface.set_stringn(x, y, alt_text, inner.width as usize, text);
324− return;
325− }
326− };
327−
328− // align to middle
329− let first_line = range
330− .map(|(start, end)| {
331− let height = end.saturating_sub(start) + 1;
332− let middle = start + (height.saturating_sub(1) / 2);
333− middle.saturating_sub(inner.height as usize / 2).min(start)
334− })
335− .unwrap_or(0);
336−
337− let offset = ViewPosition {
338− anchor: doc.text().line_to_char(first_line),
339− horizontal_offset: 0,
340− vertical_offset: 0,
341− };
342−
343− let mut highlights = EditorView::doc_syntax_highlights(
344− doc,
345− offset.anchor,
346− area.height,
347− &cx.editor.theme,
348− );
349− for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
350− if spans.is_empty() {
351− continue;
352− }
353− highlights = Box::new(helix_core::syntax::merge(highlights, spans));
354− }
355− let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
356−
357− if let Some((start, end)) = range {
358− let style = cx
359− .editor
360− .theme
361− .try_get("ui.highlight")
362− .unwrap_or_else(|| cx.editor.theme.get("ui.selection"));
363− let draw_highlight = move |renderer: &mut TextRenderer, pos: LinePos| {
364− if (start..=end).contains(&pos.doc_line) {
365− let area = Rect::new(
366− renderer.viewport.x,
367− renderer.viewport.y + pos.visual_line,
368− renderer.viewport.width,
369− 1,
370− );
371− renderer.surface.set_style(area, style)
372− }
373− };
374− decorations.push(Box::new(draw_highlight))
375− }
376−
377− render_document(
378− surface,
379− inner,
380− doc,
381− offset,
382− // TODO: compute text annotations asynchronously here (like inlay hints)
383− &TextAnnotations::default(),
384− highlights,
385− &cx.editor.theme,
386− &mut decorations,
387− &mut [],
388− );
389− }
390− }
391−
392− fn handle_event(&mut self, event: &Event, ctx: &mut Context) -> EventResult {
393− if let Event::IdleTimeout = event {
394− return self.handle_idle_timeout(ctx);
395− }
396− // TODO: keybinds for scrolling preview
397− self.picker.handle_event(event, ctx)
398− }
399−
400− fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
401− self.picker.cursor(area, ctx)
402− }
403−
404− fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
405− let picker_width = if width > MIN_AREA_WIDTH_FOR_PREVIEW {
406− width / 2
407− } else {
408− width
409− };
410− self.picker.required_size((picker_width, height))?;
411− Some((width, height))
412− }
413−
414− fn id(&self) -> Option<&'static str> {
415− Some("file-picker")
416− }
417−}
418−
419−#[derive(PartialEq, Eq, Debug)]
420−struct PickerMatch {
421− score: i64,
422− index: usize,
423− len: usize,
424−}
425−
426−impl PickerMatch {
427− fn key(&self) -> impl Ord {
428− (cmp::Reverse(self.score), self.len, self.index)
429− }
430−}
431−
432−impl PartialOrd for PickerMatch {
433− fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
434− Some(self.cmp(other))
435− }
436−}
437−
438−impl Ord for PickerMatch {
439− fn cmp(&self, other: &Self) -> Ordering {
440− self.key().cmp(&other.key())
441− }
442−}
443−
444−type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
445−
446117pub struct Picker<T: Item> {
447118 options: Vec<T>,
448119 editor_data: T::Data,
@@ -457,17 +128,22 @@ pub struct Picker<T: Item> {
457128 // pattern: String,
458129 prompt: Prompt,
459130 previous_pattern: (String, FuzzyQuery),
460− /// Whether to truncate the start (default true)
461− pub truncate_start: bool,
462131 /// Whether to show the preview panel (default true)
463132 show_preview: bool,
464133 /// Constraints for tabular formatting
465134 widths: Vec<Constraint>,
466135
467136 callback_fn: PickerCallback<T>,
137+
138+ pub truncate_start: bool,
139+ /// Caches paths to documents
140+ preview_cache: HashMap<PathBuf, CachedPreview>,
141+ read_buffer: Vec<u8>,
142+ /// Given an item in the picker, return the file path and line number to display.
143+ file_fn: Option<FileCallback<T>>,
468144}
469145
470−impl<T: Item> Picker<T> {
146+impl<T: Item + 'static> Picker<T> {
471147 pub fn new(
472148 options: Vec<T>,
473149 editor_data: T::Data,
@@ -493,6 +169,9 @@ impl<T: Item> Picker<T> {
493169 callback_fn: Box::new(callback_fn),
494170 completion_height: 0,
495171 widths: Vec::new(),
172+ preview_cache: HashMap::new(),
173+ read_buffer: Vec::with_capacity(1024),
174+ file_fn: None,
496175 };
497176
498177 picker.calculate_column_widths();
@@ -513,6 +192,19 @@ impl<T: Item> Picker<T> {
513192 picker
514193 }
515194
195+ pub fn truncate_start(mut self, truncate_start: bool) -> Self {
196+ self.truncate_start = truncate_start;
197+ self
198+ }
199+
200+ pub fn with_preview(
201+ mut self,
202+ preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
203+ ) -> Self {
204+ self.file_fn = Some(Box::new(preview_fn));
205+ self
206+ }
207+
516208 pub fn set_options(&mut self, new_options: Vec<T>) {
517209 self.options = new_options;
518210 self.cursor = 0;
@@ -679,92 +371,127 @@ impl<T: Item> Picker<T> {
679371 }
680372 EventResult::Consumed(None)
681373 }
682−}
683374
684−// process:
685−// - read all the files into a list, maxed out at a large value
686−// - on input change:
687−// - score all the names in relation to input
688−
689−impl<T: Item + 'static> Component for Picker<T> {
690− fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
691− self.completion_height = viewport.1.saturating_sub(4);
692− Some(viewport)
375+ fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
376+ self.selection()
377+ .and_then(|current| (self.file_fn.as_ref()?)(editor, current))
378+ .and_then(|(path_or_id, line)| path_or_id.get_canonicalized().ok().zip(Some(line)))
693379 }
694380
695− fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
696− let key_event = match event {
697− Event::Key(event) => *event,
698− Event::Paste(..) => return self.prompt_handle_event(event, cx),
699− Event::Resize(..) => return EventResult::Consumed(None),
700− _ => return EventResult::Ignored(None),
701− };
702−
703− let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _cx| {
704− // remove the layer
705− compositor.last_picker = compositor.pop();
706− })));
707−
708− // So that idle timeout retriggers
709− cx.editor.reset_idle_timer();
710−
711− match key_event {
712− shift!(Tab) | key!(Up) | ctrl!('p') => {
713− self.move_by(1, Direction::Backward);
714− }
715− key!(Tab) | key!(Down) | ctrl!('n') => {
716− self.move_by(1, Direction::Forward);
717− }
718− key!(PageDown) | ctrl!('d') => {
719− self.page_down();
720− }
721− key!(PageUp) | ctrl!('u') => {
722− self.page_up();
723− }
724− key!(Home) => {
725− self.to_start();
726− }
727− key!(End) => {
728− self.to_end();
729− }
730− key!(Esc) | ctrl!('c') => {
731− return close_fn;
732− }
733− alt!(Enter) => {
734− if let Some(option) = self.selection() {
735− (self.callback_fn)(cx, option, Action::Load);
736− }
737− }
738− key!(Enter) => {
739− if let Some(option) = self.selection() {
740− (self.callback_fn)(cx, option, Action::Replace);
741− }
742− return close_fn;
743− }
744− ctrl!('s') => {
745− if let Some(option) = self.selection() {
746− (self.callback_fn)(cx, option, Action::HorizontalSplit);
381+ /// Get (cached) preview for a given path. If a document corresponding
382+ /// to the path is already open in the editor, it is used instead.
383+ fn get_preview<'picker, 'editor>(
384+ &'picker mut self,
385+ path_or_id: PathOrId,
386+ editor: &'editor Editor,
387+ ) -> Preview<'picker, 'editor> {
388+ match path_or_id {
389+ PathOrId::Path(path) => {
390+ let path = &path;
391+ if let Some(doc) = editor.document_by_path(path) {
392+ return Preview::EditorDocument(doc);
747393 }
748− return close_fn;
749− }
750− ctrl!('v') => {
751− if let Some(option) = self.selection() {
752− (self.callback_fn)(cx, option, Action::VerticalSplit);
394+
395+ if self.preview_cache.contains_key(path) {
396+ return Preview::Cached(&self.preview_cache[path]);
753397 }
754− return close_fn;
398+
399+ let data = std::fs::File::open(path).and_then(|file| {
400+ let metadata = file.metadata()?;
401+ // Read up to 1kb to detect the content type
402+ let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
403+ let content_type = content_inspector::inspect(&self.read_buffer[..n]);
404+ self.read_buffer.clear();
405+ Ok((metadata, content_type))
406+ });
407+ let preview = data
408+ .map(
409+ |(metadata, content_type)| match (metadata.len(), content_type) {
410+ (_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
411+ (size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => {
412+ CachedPreview::LargeFile
413+ }
414+ _ => {
415+ // TODO: enable syntax highlighting; blocked by async rendering
416+ Document::open(path, None, None, editor.config.clone())
417+ .map(|doc| CachedPreview::Document(Box::new(doc)))
418+ .unwrap_or(CachedPreview::NotFound)
419+ }
420+ },
421+ )
422+ .unwrap_or(CachedPreview::NotFound);
423+ self.preview_cache.insert(path.to_owned(), preview);
424+ Preview::Cached(&self.preview_cache[path])
755425 }
756− ctrl!('t') => {
757− self.toggle_preview();
426+ PathOrId::Id(id) => {
427+ let doc = editor.documents.get(&id).unwrap();
428+ Preview::EditorDocument(doc)
758429 }
759− _ => {
760− self.prompt_handle_event(event, cx);
430+ }
431+ }
432+
433+ fn handle_idle_timeout(&mut self, cx: &mut Context) -> EventResult {
434+ let Some((current_file, _)) = self.current_file(cx.editor) else {
435+ return EventResult::Consumed(None)
436+ };
437+
438+ // Try to find a document in the cache
439+ let doc = match &current_file {
440+ PathOrId::Id(doc_id) => doc_mut!(cx.editor, doc_id),
441+ PathOrId::Path(path) => match self.preview_cache.get_mut(path) {
442+ Some(CachedPreview::Document(ref mut doc)) => doc,
443+ _ => return EventResult::Consumed(None),
444+ },
445+ };
446+
447+ let mut callback: Option<compositor::Callback> = None;
448+
449+ // Then attempt to highlight it if it has no language set
450+ if doc.language_config().is_none() {
451+ if let Some(language_config) = doc.detect_language_config(&cx.editor.syn_loader) {
452+ doc.language = Some(language_config.clone());
453+ let text = doc.text().clone();
454+ let loader = cx.editor.syn_loader.clone();
455+ let job = tokio::task::spawn_blocking(move || {
456+ let syntax = language_config
457+ .highlight_config(&loader.scopes())
458+ .and_then(|highlight_config| Syntax::new(&text, highlight_config, loader));
459+ let callback = move |editor: &mut Editor, compositor: &mut Compositor| {
460+ let Some(syntax) = syntax else {
461+ log::info!("highlighting picker item failed");
462+ return
463+ };
464+ let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
465+ log::info!("picker closed before syntax highlighting finished");
466+ return
467+ };
468+ // Try to find a document in the cache
469+ let doc = match current_file {
470+ PathOrId::Id(doc_id) => doc_mut!(editor, &doc_id),
471+ PathOrId::Path(path) => match picker.preview_cache.get_mut(&path) {
472+ Some(CachedPreview::Document(ref mut doc)) => doc,
473+ _ => return,
474+ },
475+ };
476+ doc.syntax = Some(syntax);
477+ };
478+ Callback::EditorCompositor(Box::new(callback))
479+ });
480+ let tmp: compositor::Callback = Box::new(move |_, ctx| {
481+ ctx.jobs
482+ .callback(job.map(|res| res.map_err(anyhow::Error::from)))
483+ });
484+ callback = Some(Box::new(tmp))
761485 }
762486 }
763487
764− EventResult::Consumed(None)
488+ // QUESTION: do we want to compute inlay hints in pickers too ? Probably not for now
489+ // but it could be interesting in the future
490+
491+ EventResult::Consumed(callback)
765492 }
766493
767− fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
494+ fn render_picker(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
768495 let text_style = cx.editor.theme.get("ui.text");
769496 let selected = cx.editor.theme.get("ui.text.focus");
770497 let highlight_style = cx.editor.theme.get("special").add_modifier(Modifier::BOLD);
@@ -930,6 +657,178 @@ impl<T: Item + 'static> Component for Picker<T> {
930657 );
931658 }
932659
660+ fn render_preview(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
661+ // -- Render the frame:
662+ // clear area
663+ let background = cx.editor.theme.get("ui.background");
664+ let text = cx.editor.theme.get("ui.text");
665+ surface.clear_with(area, background);
666+
667+ // don't like this but the lifetime sucks
668+ let block = Block::default().borders(Borders::ALL);
669+
670+ // calculate the inner area inside the box
671+ let inner = block.inner(area);
672+ // 1 column gap on either side
673+ let margin = Margin::horizontal(1);
674+ let inner = inner.inner(&margin);
675+ block.render(area, surface);
676+
677+ if let Some((path, range)) = self.current_file(cx.editor) {
678+ let preview = self.get_preview(path, cx.editor);
679+ let doc = match preview.document() {
680+ Some(doc) => doc,
681+ None => {
682+ let alt_text = preview.placeholder();
683+ let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
684+ let y = inner.y + inner.height / 2;
685+ surface.set_stringn(x, y, alt_text, inner.width as usize, text);
686+ return;
687+ }
688+ };
689+
690+ // align to middle
691+ let first_line = range
692+ .map(|(start, end)| {
693+ let height = end.saturating_sub(start) + 1;
694+ let middle = start + (height.saturating_sub(1) / 2);
695+ middle.saturating_sub(inner.height as usize / 2).min(start)
696+ })
697+ .unwrap_or(0);
698+
699+ let offset = ViewPosition {
700+ anchor: doc.text().line_to_char(first_line),
701+ horizontal_offset: 0,
702+ vertical_offset: 0,
703+ };
704+
705+ let mut highlights = EditorView::doc_syntax_highlights(
706+ doc,
707+ offset.anchor,
708+ area.height,
709+ &cx.editor.theme,
710+ );
711+ for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
712+ if spans.is_empty() {
713+ continue;
714+ }
715+ highlights = Box::new(helix_core::syntax::merge(highlights, spans));
716+ }
717+ let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
718+
719+ if let Some((start, end)) = range {
720+ let style = cx
721+ .editor
722+ .theme
723+ .try_get("ui.highlight")
724+ .unwrap_or_else(|| cx.editor.theme.get("ui.selection"));
725+ let draw_highlight = move |renderer: &mut TextRenderer, pos: LinePos| {
726+ if (start..=end).contains(&pos.doc_line) {
727+ let area = Rect::new(
728+ renderer.viewport.x,
729+ renderer.viewport.y + pos.visual_line,
730+ renderer.viewport.width,
731+ 1,
732+ );
733+ renderer.surface.set_style(area, style)
734+ }
735+ };
736+ decorations.push(Box::new(draw_highlight))
737+ }
738+
739+ render_document(
740+ surface,
741+ inner,
742+ doc,
743+ offset,
744+ // TODO: compute text annotations asynchronously here (like inlay hints)
745+ &TextAnnotations::default(),
746+ highlights,
747+ &cx.editor.theme,
748+ &mut decorations,
749+ &mut [],
750+ );
751+ }
752+ }
753+
754+ fn handle_event(&mut self, event: &Event, ctx: &mut Context) -> EventResult {
755+ if let Event::IdleTimeout = event {
756+ return self.handle_idle_timeout(ctx);
757+ }
758+ // TODO: keybinds for scrolling preview
759+
760+ let key_event = match event {
761+ Event::Key(event) => *event,
762+ Event::Paste(..) => return self.prompt_handle_event(event, ctx),
763+ Event::Resize(..) => return EventResult::Consumed(None),
764+ _ => return EventResult::Ignored(None),
765+ };
766+
767+ let close_fn =
768+ EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _ctx| {
769+ // remove the layer
770+ compositor.last_picker = compositor.pop();
771+ })));
772+
773+ // So that idle timeout retriggers
774+ ctx.editor.reset_idle_timer();
775+
776+ match key_event {
777+ shift!(Tab) | key!(Up) | ctrl!('p') => {
778+ self.move_by(1, Direction::Backward);
779+ }
780+ key!(Tab) | key!(Down) | ctrl!('n') => {
781+ self.move_by(1, Direction::Forward);
782+ }
783+ key!(PageDown) | ctrl!('d') => {
784+ self.page_down();
785+ }
786+ key!(PageUp) | ctrl!('u') => {
787+ self.page_up();
788+ }
789+ key!(Home) => {
790+ self.to_start();
791+ }
792+ key!(End) => {
793+ self.to_end();
794+ }
795+ key!(Esc) | ctrl!('c') => {
796+ return close_fn;
797+ }
798+ alt!(Enter) => {
799+ if let Some(option) = self.selection() {
800+ (self.callback_fn)(ctx, option, Action::Load);
801+ }
802+ }
803+ key!(Enter) => {
804+ if let Some(option) = self.selection() {
805+ (self.callback_fn)(ctx, option, Action::Replace);
806+ }
807+ return close_fn;
808+ }
809+ ctrl!('s') => {
810+ if let Some(option) = self.selection() {
811+ (self.callback_fn)(ctx, option, Action::HorizontalSplit);
812+ }
813+ return close_fn;
814+ }
815+ ctrl!('v') => {
816+ if let Some(option) = self.selection() {
817+ (self.callback_fn)(ctx, option, Action::VerticalSplit);
818+ }
819+ return close_fn;
820+ }
821+ ctrl!('t') => {
822+ self.toggle_preview();
823+ }
824+ _ => {
825+ self.prompt_handle_event(event, ctx);
826+ }
827+ }
828+
829+ EventResult::Consumed(None)
830+ }
831+
933832 fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
934833 let block = Block::default().borders(Borders::ALL);
935834 // calculate the inner area inside the box
@@ -940,8 +839,67 @@ impl<T: Item + 'static> Component for Picker<T> {
940839
941840 self.prompt.cursor(area, editor)
942841 }
842+
843+ fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
844+ self.completion_height = height.saturating_sub(4);
845+ Some((width, height))
846+ }
847+}
848+
849+impl<T: Item + 'static> Component for Picker<T> {
850+ fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
851+ // +---------+ +---------+
852+ // |prompt | |preview |
853+ // +---------+ | |
854+ // |picker | | |
855+ // | | | |
856+ // +---------+ +---------+
857+
858+ let render_preview = self.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
859+
860+ let picker_width = if render_preview {
861+ area.width / 2
862+ } else {
863+ area.width
864+ };
865+
866+ let picker_area = area.with_width(picker_width);
867+ self.render_picker(picker_area, surface, cx);
868+
869+ if render_preview {
870+ let preview_area = area.clip_left(picker_width);
871+ self.render_preview(preview_area, surface, cx);
872+ }
873+ }
874+}
875+
876+#[derive(PartialEq, Eq, Debug)]
877+struct PickerMatch {
878+ score: i64,
879+ index: usize,
880+ len: usize,
881+}
882+
883+impl PickerMatch {
884+ fn key(&self) -> impl Ord {
885+ (cmp::Reverse(self.score), self.len, self.index)
886+ }
887+}
888+
889+impl PartialOrd for PickerMatch {
890+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
891+ Some(self.cmp(other))
892+ }
943893}
944894
895+impl Ord for PickerMatch {
896+ fn cmp(&self, other: &Self) -> Ordering {
897+ self.key().cmp(&other.key())
898+ }
899+}
900+
901+type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
902+
945903/// Returns a new list of options to replace the contents of the picker
946904/// when called with the current picker query,
947905pub type DynQueryCallback<T> =
@@ -950,7 +908,7 @@ pub type DynQueryCallback<T> =
950908/// A picker that updates its contents via a callback whenever the
951909/// query string changes. Useful for live grep, workspace symbols, etc.
952910pub struct DynamicPicker<T: ui::menu::Item + Send> {
953− file_picker: FilePicker<T>,
911+ file_picker: Picker<T>,
954912 query_callback: DynQueryCallback<T>,
955913 query: String,
956914}
@@ -958,7 +916,7 @@ pub struct DynamicPicker<T: ui::menu::Item + Send> {
958916impl<T: ui::menu::Item + Send> DynamicPicker<T> {
959917 pub const ID: &'static str = "dynamic-picker";
960918
961− pub fn new(file_picker: FilePicker<T>, query_callback: DynQueryCallback<T>) -> Self {
919+ pub fn new(file_picker: Picker<T>, query_callback: DynQueryCallback<T>) -> Self {
962920 Self {
963921 file_picker,
964922 query_callback,
@@ -974,7 +932,7 @@ impl<T: Item + Send + 'static> Component for DynamicPicker<T> {
974932
975933 fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
976934 let event_result = self.file_picker.handle_event(event, cx);
977− let current_query = self.file_picker.picker.prompt.line();
935+ let current_query = self.file_picker.prompt.line();
978936
979937 if !matches!(event, Event::IdleTimeout) || self.query == *current_query {
980938 return event_result;
@@ -990,7 +948,7 @@ impl<T: Item + Send + 'static> Component for DynamicPicker<T> {
990948 // Wrapping of pickers in overlay is done outside the picker code,
991949 // so this is fragile and will break if wrapped in some other widget.
992950 let picker = match compositor.find_id::<Overlay<DynamicPicker<T>>>(Self::ID) {
993− Some(overlay) => &mut overlay.content.file_picker.picker,
951+ Some(overlay) => &mut overlay.content.file_picker,
994952 None => return,
995953 };
996954 picker.set_options(new_options);