Skip to content

Commit e7c5d6f

Browse files
committed
patchy: auto-merge pull request helix-editor#11285
`patchy` is a tool which makes it easy to declaratively manage personal forks by automatically merging pull requests. Check it out here: https://github.com/NikitaRevenco/patchy
2 parents 377e369 + 52a9cef commit e7c5d6f

File tree

3 files changed

+198
-21
lines changed

3 files changed

+198
-21
lines changed

helix-term/src/commands.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,9 @@ impl MappableCommand {
393393
file_picker, "Open file picker",
394394
file_picker_in_current_buffer_directory, "Open file picker at current buffer's directory",
395395
file_picker_in_current_directory, "Open file picker at current working directory",
396+
file_browser, "Open file browser in workspace root",
397+
file_browser_in_current_buffer_directory, "Open file browser at current buffer's directory",
398+
file_browser_in_current_directory, "Open file browser at current working directory",
396399
code_action, "Perform code action",
397400
buffer_picker, "Open buffer picker",
398401
jumplist_picker, "Open jumplist picker",
@@ -2986,6 +2989,58 @@ fn file_picker_in_current_directory(cx: &mut Context) {
29862989
cx.push_layer(Box::new(overlaid(picker)));
29872990
}
29882991

2992+
fn file_browser(cx: &mut Context) {
2993+
let root = find_workspace().0;
2994+
if !root.exists() {
2995+
cx.editor.set_error("Workspace directory does not exist");
2996+
return;
2997+
}
2998+
2999+
if let Ok(picker) = ui::file_browser(root, cx.editor) {
3000+
cx.push_layer(Box::new(overlaid(picker)));
3001+
}
3002+
}
3003+
3004+
fn file_browser_in_current_buffer_directory(cx: &mut Context) {
3005+
let doc_dir = doc!(cx.editor)
3006+
.path()
3007+
.and_then(|path| path.parent().map(|path| path.to_path_buf()));
3008+
3009+
let path = match doc_dir {
3010+
Some(path) => path,
3011+
None => {
3012+
let cwd = helix_stdx::env::current_working_dir();
3013+
if !cwd.exists() {
3014+
cx.editor.set_error(
3015+
"Current buffer has no parent and current working directory does not exist",
3016+
);
3017+
return;
3018+
}
3019+
cx.editor.set_error(
3020+
"Current buffer has no parent, opening file browser in current working directory",
3021+
);
3022+
cwd
3023+
}
3024+
};
3025+
3026+
if let Ok(picker) = ui::file_browser(path, cx.editor) {
3027+
cx.push_layer(Box::new(overlaid(picker)));
3028+
}
3029+
}
3030+
3031+
fn file_browser_in_current_directory(cx: &mut Context) {
3032+
let cwd = helix_stdx::env::current_working_dir();
3033+
if !cwd.exists() {
3034+
cx.editor
3035+
.set_error("Current working directory does not exist");
3036+
return;
3037+
}
3038+
3039+
if let Ok(picker) = ui::file_browser(cwd, cx.editor) {
3040+
cx.push_layer(Box::new(overlaid(picker)));
3041+
}
3042+
}
3043+
29893044
fn buffer_picker(cx: &mut Context) {
29903045
let current = view!(cx.editor).doc;
29913046

helix-term/src/ui/mod.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::job::{self, Callback};
2020
pub use completion::Completion;
2121
pub use editor::EditorView;
2222
use helix_stdx::rope;
23+
use helix_view::theme::Style;
2324
pub use markdown::Markdown;
2425
pub use menu::Menu;
2526
pub use picker::{Column as PickerColumn, FileLocation, Picker};
@@ -29,7 +30,9 @@ pub use spinner::{ProgressSpinners, Spinner};
2930
pub use text::Text;
3031

3132
use helix_view::Editor;
33+
use tui::text::Span;
3234

35+
use std::path::Path;
3336
use std::{error::Error, path::PathBuf};
3437

3538
struct Utf8PathBuf {
@@ -276,6 +279,74 @@ pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePi
276279
picker
277280
}
278281

282+
type FileBrowser = Picker<(PathBuf, bool), (PathBuf, Style)>;
283+
284+
pub fn file_browser(root: PathBuf, editor: &Editor) -> Result<FileBrowser, std::io::Error> {
285+
let directory_style = editor.theme.get("ui.text.directory");
286+
let directory_content = directory_content(&root)?;
287+
288+
let columns = [PickerColumn::new(
289+
"path",
290+
|(path, is_dir): &(PathBuf, bool), (root, directory_style): &(PathBuf, Style)| {
291+
let name = path.strip_prefix(root).unwrap_or(path).to_string_lossy();
292+
if *is_dir {
293+
Span::styled(format!("{}/", name), *directory_style).into()
294+
} else {
295+
name.into()
296+
}
297+
},
298+
)];
299+
let picker = Picker::new(
300+
columns,
301+
0,
302+
directory_content,
303+
(root, directory_style),
304+
move |cx, (path, is_dir): &(PathBuf, bool), action| {
305+
if *is_dir {
306+
let owned_path = path.clone();
307+
let callback = Box::pin(async move {
308+
let call: Callback =
309+
Callback::EditorCompositor(Box::new(move |editor, compositor| {
310+
if let Ok(picker) = file_browser(owned_path, editor) {
311+
compositor.push(Box::new(overlay::overlaid(picker)));
312+
}
313+
}));
314+
Ok(call)
315+
});
316+
cx.jobs.callback(callback);
317+
} else if let Err(e) = cx.editor.open(path, action) {
318+
let err = if let Some(err) = e.source() {
319+
format!("{}", err)
320+
} else {
321+
format!("unable to open \"{}\"", path.display())
322+
};
323+
cx.editor.set_error(err);
324+
}
325+
},
326+
)
327+
.with_preview(|_editor, (path, _is_dir)| Some((path.as_path().into(), None)));
328+
329+
Ok(picker)
330+
}
331+
332+
fn directory_content(path: &Path) -> Result<Vec<(PathBuf, bool)>, std::io::Error> {
333+
let mut content: Vec<_> = std::fs::read_dir(path)?
334+
.flatten()
335+
.map(|entry| {
336+
(
337+
entry.path(),
338+
entry.file_type().is_ok_and(|file_type| file_type.is_dir()),
339+
)
340+
})
341+
.collect();
342+
343+
content.sort_by(|(path1, is_dir1), (path2, is_dir2)| (!is_dir1, path1).cmp(&(!is_dir2, path2)));
344+
if path.parent().is_some() {
345+
content.insert(0, (path.join(".."), true));
346+
}
347+
Ok(content)
348+
}
349+
279350
pub mod completers {
280351
use super::Utf8PathBuf;
281352
use crate::ui::prompt::Completion;

helix-term/src/ui/picker.rs

Lines changed: 72 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ pub type FileLocation<'a> = (PathOrId<'a>, Option<(usize, usize)>);
8585

8686
pub enum CachedPreview {
8787
Document(Box<Document>),
88+
Directory(Vec<(String, bool)>),
8889
Binary,
8990
LargeFile,
9091
NotFound,
@@ -106,12 +107,20 @@ impl Preview<'_, '_> {
106107
}
107108
}
108109

110+
fn dir_content(&self) -> Option<&Vec<(String, bool)>> {
111+
match self {
112+
Preview::Cached(CachedPreview::Directory(dir_content)) => Some(dir_content),
113+
_ => None,
114+
}
115+
}
116+
109117
/// Alternate text to show for the preview.
110118
fn placeholder(&self) -> &str {
111119
match *self {
112120
Self::EditorDocument(_) => "<Invalid file location>",
113121
Self::Cached(preview) => match preview {
114122
CachedPreview::Document(_) => "<Invalid file location>",
123+
CachedPreview::Directory(_) => "<Invalid directory location>",
115124
CachedPreview::Binary => "<Binary file>",
116125
CachedPreview::LargeFile => "<File too large to preview>",
117126
CachedPreview::NotFound => "<File not found>",
@@ -584,33 +593,58 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
584593
}
585594

586595
let path: Arc<Path> = path.into();
587-
let data = std::fs::File::open(&path).and_then(|file| {
588-
let metadata = file.metadata()?;
589-
// Read up to 1kb to detect the content type
590-
let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
591-
let content_type = content_inspector::inspect(&self.read_buffer[..n]);
592-
self.read_buffer.clear();
593-
Ok((metadata, content_type))
594-
});
595-
let preview = data
596-
.map(
597-
|(metadata, content_type)| match (metadata.len(), content_type) {
598-
(_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
599-
(size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => {
600-
CachedPreview::LargeFile
596+
let preview = std::fs::metadata(&path)
597+
.and_then(|metadata| {
598+
if metadata.is_dir() {
599+
let files = super::directory_content(&path)?;
600+
let file_names: Vec<_> = files
601+
.iter()
602+
.filter_map(|(path, is_dir)| {
603+
let name = path.file_name()?.to_string_lossy();
604+
if *is_dir {
605+
Some((format!("{}/", name), true))
606+
} else {
607+
Some((name.into_owned(), false))
608+
}
609+
})
610+
.collect();
611+
Ok(CachedPreview::Directory(file_names))
612+
} else if metadata.is_file() {
613+
if metadata.len() > MAX_FILE_SIZE_FOR_PREVIEW {
614+
return Ok(CachedPreview::LargeFile);
615+
}
616+
let content_type = std::fs::File::open(&path).and_then(|file| {
617+
// Read up to 1kb to detect the content type
618+
let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
619+
let content_type =
620+
content_inspector::inspect(&self.read_buffer[..n]);
621+
self.read_buffer.clear();
622+
Ok(content_type)
623+
})?;
624+
if content_type.is_binary() {
625+
return Ok(CachedPreview::Binary);
601626
}
602-
_ => Document::open(&path, None, None, editor.config.clone())
603-
.map(|doc| {
627+
Document::open(&path, None, None, editor.config.clone()).map_or(
628+
Err(std::io::Error::new(
629+
std::io::ErrorKind::NotFound,
630+
"Cannot open document",
631+
)),
632+
|doc| {
604633
// Asynchronously highlight the new document
605634
helix_event::send_blocking(
606635
&self.preview_highlight_handler,
607636
path.clone(),
608637
);
609-
CachedPreview::Document(Box::new(doc))
610-
})
611-
.unwrap_or(CachedPreview::NotFound),
612-
},
613-
)
638+
Ok(CachedPreview::Document(Box::new(doc)))
639+
},
640+
)
641+
} else {
642+
Err(std::io::Error::new(
643+
std::io::ErrorKind::NotFound,
644+
"Neither a dir, nor a file",
645+
))
646+
}
647+
})
614648
.unwrap_or(CachedPreview::NotFound);
615649
self.preview_cache.insert(path.clone(), preview);
616650
Some((Preview::Cached(&self.preview_cache[&path]), range))
@@ -823,6 +857,7 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
823857
// clear area
824858
let background = cx.editor.theme.get("ui.background");
825859
let text = cx.editor.theme.get("ui.text");
860+
let directory = cx.editor.theme.get("ui.text.directory");
826861
surface.clear_with(area, background);
827862

828863
const BLOCK: Block<'_> = Block::bordered();
@@ -844,6 +879,22 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
844879
doc
845880
}
846881
_ => {
882+
if let Some(dir_content) = preview.dir_content() {
883+
for (i, (path, is_dir)) in
884+
dir_content.iter().take(inner.height as usize).enumerate()
885+
{
886+
let style = if *is_dir { directory } else { text };
887+
surface.set_stringn(
888+
inner.x,
889+
inner.y + i as u16,
890+
path,
891+
inner.width as usize,
892+
style,
893+
);
894+
}
895+
return;
896+
}
897+
847898
let alt_text = preview.placeholder();
848899
let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
849900
let y = inner.y + inner.height / 2;

0 commit comments

Comments
 (0)