on 2158366 help sign in
294 lines 9.5 kB history raw
1mod completion;
2pub(crate) mod editor;
3mod info;
4mod markdown;
5mod menu;
6mod picker;
7mod popup;
8mod prompt;
9mod spinner;
10mod text;
12pub use completion::Completion;
13pub use editor::EditorView;
14pub use markdown::Markdown;
15pub use menu::Menu;
16pub use picker::{FilePicker, Picker};
17pub use popup::Popup;
18pub use prompt::{Prompt, PromptEvent};
19pub use spinner::{ProgressSpinners, Spinner};
20pub use text::Text;
22use helix_core::regex::Regex;
23use helix_core::register::Registers;
24use helix_view::{Document, Editor, View};
26use std::path::PathBuf;
28pub fn regex_prompt(
29 cx: &mut crate::commands::Context,
30 prompt: String,
31 fun: impl Fn(&mut View, &mut Document, &mut Registers, Regex) + 'static,
32) -> Prompt {
33 let (view, doc) = current!(cx.editor);
34 let view_id = view.id;
35 let snapshot = doc.selection(view_id).clone();
37 Prompt::new(
38 prompt,
39 None,
40 |_input: &str| Vec::new(), // this is fine because Vec::new() doesn't allocate
41 move |cx: &mut crate::compositor::Context, input: &str, event: PromptEvent| {
42 match event {
43 PromptEvent::Abort => {
44 let (view, doc) = current!(cx.editor);
45 doc.set_selection(view.id, snapshot.clone());
46 }
47 PromptEvent::Validate => {
48 // TODO: push_jump to store selection just before jump
49 }
50 PromptEvent::Update => {
51 // skip empty input, TODO: trigger default
52 if input.is_empty() {
53 return;
54 }
56 match Regex::new(input) {
57 Ok(regex) => {
58 let (view, doc) = current!(cx.editor);
59 let registers = &mut cx.editor.registers;
61 // revert state to what it was before the last update
62 doc.set_selection(view.id, snapshot.clone());
64 fun(view, doc, registers, regex);
66 view.ensure_cursor_in_view(doc, cx.editor.config.scrolloff);
67 }
68 Err(_err) => (), // TODO: mark command line as error
69 }
70 }
71 }
72 },
73 )
76pub fn file_picker(root: PathBuf) -> FilePicker<PathBuf> {
77 use ignore::Walk;
78 use std::time;
79 let files = Walk::new(&root).filter_map(|entry| {
80 let entry = entry.ok()?;
81 // Path::is_dir() traverses symlinks, so we use it over DirEntry::is_dir
82 if entry.path().is_dir() {
83 // Will give a false positive if metadata cannot be read (eg. permission error)
84 return None;
85 }
87 let time = entry.metadata().map_or(time::UNIX_EPOCH, |metadata| {
88 metadata
89 .accessed()
90 .or_else(|_| metadata.modified())
91 .or_else(|_| metadata.created())
92 .unwrap_or(time::UNIX_EPOCH)
93 });
95 Some((entry.into_path(), time))
96 });
98 let mut files: Vec<_> = if root.join(".git").is_dir() {
99 files.collect()
100 } else {
101 const MAX: usize = 8192;
102 files.take(MAX).collect()
103 };
105 files.sort_by_key(|file| std::cmp::Reverse(file.1));
107 let files = files.into_iter().map(|(path, _)| path).collect();
109 FilePicker::new(
110 files,
111 move |path: &PathBuf| {
112 // format_fn
113 path.strip_prefix(&root)
114 .unwrap_or(path)
115 .to_str()
116 .unwrap()
117 .into()
118 },
119 move |editor: &mut Editor, path: &PathBuf, action| {
120 editor
121 .open(path.into(), action)
122 .expect("editor.open failed");
123 },
124 |_editor, path| Some((path.clone(), None)),
125 )
128pub mod completers {
129 use crate::ui::prompt::Completion;
130 use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
131 use fuzzy_matcher::FuzzyMatcher;
132 use helix_view::theme;
133 use std::borrow::Cow;
134 use std::cmp::Reverse;
136 pub type Completer = fn(&str) -> Vec<Completion>;
138 pub fn theme(input: &str) -> Vec<Completion> {
139 let mut names = theme::Loader::read_names(&helix_core::runtime_dir().join("themes"));
140 names.extend(theme::Loader::read_names(
141 &helix_core::config_dir().join("themes"),
142 ));
143 names.push("default".into());
145 let mut names: Vec<_> = names
146 .into_iter()
147 .map(|name| ((0..), Cow::from(name)))
148 .collect();
150 let matcher = Matcher::default();
152 let mut matches: Vec<_> = names
153 .into_iter()
154 .filter_map(|(_range, name)| {
155 matcher.fuzzy_match(&name, input).map(|score| (name, score))
156 })
157 .collect();
159 matches.sort_unstable_by_key(|(_file, score)| Reverse(*score));
160 names = matches.into_iter().map(|(name, _)| ((0..), name)).collect();
162 names
163 }
165 pub fn filename(input: &str) -> Vec<Completion> {
166 filename_impl(input, |entry| {
167 let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
169 if is_dir {
170 FileMatch::AcceptIncomplete
171 } else {
172 FileMatch::Accept
173 }
174 })
175 }
177 pub fn directory(input: &str) -> Vec<Completion> {
178 filename_impl(input, |entry| {
179 let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
181 if is_dir {
182 FileMatch::Accept
183 } else {
184 FileMatch::Reject
185 }
186 })
187 }
189 #[derive(Copy, Clone, PartialEq, Eq)]
190 enum FileMatch {
191 /// Entry should be ignored
192 Reject,
193 /// Entry is usable but can't be the end (for instance if the entry is a directory and we
194 /// try to match a file)
195 AcceptIncomplete,
196 /// Entry is usable and can be the end of the match
197 Accept,
198 }
200 // TODO: we could return an iter/lazy thing so it can fetch as many as it needs.
201 fn filename_impl<F>(input: &str, filter_fn: F) -> Vec<Completion>
202 where
203 F: Fn(&ignore::DirEntry) -> FileMatch,
204 {
205 // Rust's filename handling is really annoying.
207 use ignore::WalkBuilder;
208 use std::path::Path;
210 let is_tilde = input.starts_with('~') && input.len() == 1;
211 let path = helix_view::document::expand_tilde(Path::new(input));
213 let (dir, file_name) = if input.ends_with('/') {
214 (path, None)
215 } else {
216 let file_name = path
217 .file_name()
218 .map(|file| file.to_str().unwrap().to_owned());
220 let path = match path.parent() {
221 Some(path) if !path.as_os_str().is_empty() => path.to_path_buf(),
222 // Path::new("h")'s parent is Some("")...
223 _ => std::env::current_dir().expect("couldn't determine current directory"),
224 };
226 (path, file_name)
227 };
229 let end = input.len()..;
231 let mut files: Vec<_> = WalkBuilder::new(dir.clone())
232 .max_depth(Some(1))
233 .build()
234 .filter_map(|file| {
235 file.ok().and_then(|entry| {
236 let fmatch = filter_fn(&entry);
238 if fmatch == FileMatch::Reject {
239 return None;
240 }
242 //let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
244 let path = entry.path();
245 let mut path = if is_tilde {
246 // if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on
247 // one of the directories the tilde will be replaced with a valid path not with a relative
248 // home directory name.
249 // ~ -> <TAB> -> /home/user
250 // ~/ -> <TAB> -> ~/first_entry
251 path.to_path_buf()
252 } else {
253 path.strip_prefix(&dir).unwrap_or(path).to_path_buf()
254 };
256 if fmatch == FileMatch::AcceptIncomplete {
257 path.push("");
258 }
260 let path = path.to_str().unwrap().to_owned();
261 Some((end.clone(), Cow::from(path)))
262 })
263 }) // TODO: unwrap or skip
264 .filter(|(_, path)| !path.is_empty()) // TODO
265 .collect();
267 // if empty, return a list of dirs and files in current dir
268 if let Some(file_name) = file_name {
269 let matcher = Matcher::default();
271 // inefficient, but we need to calculate the scores, filter out None, then sort.
272 let mut matches: Vec<_> = files
273 .into_iter()
274 .filter_map(|(_range, file)| {
275 matcher
276 .fuzzy_match(&file, &file_name)
277 .map(|score| (file, score))
278 })
279 .collect();
281 let range = (input.len().saturating_sub(file_name.len()))..;
283 matches.sort_unstable_by_key(|(_file, score)| Reverse(*score));
284 files = matches
285 .into_iter()
286 .map(|(file, _)| (range.clone(), file))
287 .collect();
289 // TODO: complete to longest common match
290 }
292 files
293 }