@@ -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 ¤t_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 ¤t_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);