Debian Codegraph @

helix-term/src/ui/mod.rs

raw symbols SCIP
1 mod completion;
2 mod document;
3 pub(crate) mod editor;
4 mod info;
5 pub mod lsp;
6 mod markdown;
7 pub mod menu;
8 pub mod overlay;
9 pub mod picker;
10 pub mod popup;
11 pub mod prompt;
12 mod select;
13 mod spinner;
14 mod statusline;
15 mod text;
16 mod text_decorations;
17
18 use crate::compositor::Compositor;
19 use crate::filter_picker_entry;
20 use crate::job::{self, Callback};
21 pub use completion::Completion;
22 pub use editor::EditorView;
23 use helix_stdx::rope;
24 use helix_view::theme::Style;
25 pub use markdown::Markdown;
26 pub use menu::Menu;
27 pub use picker::{Column as PickerColumn, FileLocation, Picker};
28 pub use popup::Popup;
29 pub use prompt::{Prompt, PromptEvent};
30 pub use select::Select;
31 pub use spinner::{ProgressSpinners, Spinner};
32 pub use text::Text;
33
34 use helix_view::Editor;
35 use tui::text::{Span, Spans};
36
37 use std::path::Path;
38 use std::{error::Error, path::PathBuf};
39
40 struct Utf8PathBuf {
41 path: String,
42 is_dir: bool,
43 is_symlink: bool,
44 }
45
46 impl AsRef<str> for Utf8PathBuf {
47 fn as_ref(&self) -> &str {
48 &self.path
49 }
50 }
51
52 pub fn prompt(
53 cx: &mut crate::commands::Context,
54 prompt: std::borrow::Cow<'static, str>,
55 history_register: Option<char>,
56 completion_fn: impl FnMut(&Editor, &str) -> Vec<prompt::Completion> + 'static,
57 callback_fn: impl FnMut(&mut crate::compositor::Context, &str, PromptEvent) + 'static,
58 ) {
59 let mut prompt = Prompt::new(prompt, history_register, completion_fn, callback_fn);
60 // Calculate the initial completion
61 prompt.recalculate_completion(cx.editor);
62 cx.push_layer(Box::new(prompt));
63 }
64
65 pub fn prompt_with_input(
66 cx: &mut crate::commands::Context,
67 prompt: std::borrow::Cow<'static, str>,
68 input: String,
69 history_register: Option<char>,
70 completion_fn: impl FnMut(&Editor, &str) -> Vec<prompt::Completion> + 'static,
71 callback_fn: impl FnMut(&mut crate::compositor::Context, &str, PromptEvent) + 'static,
72 ) {
73 let prompt = Prompt::new(prompt, history_register, completion_fn, callback_fn)
74 .with_line(input, cx.editor);
75 cx.push_layer(Box::new(prompt));
76 }
77
78 pub fn regex_prompt(
79 cx: &mut crate::commands::Context,
80 prompt: std::borrow::Cow<'static, str>,
81 history_register: Option<char>,
82 completion_fn: impl FnMut(&Editor, &str) -> Vec<prompt::Completion> + 'static,
83 fun: impl Fn(&mut crate::compositor::Context, rope::Regex, PromptEvent) + 'static,
84 ) {
85 raw_regex_prompt(
86 cx,
87 prompt,
88 history_register,
89 completion_fn,
90 move |cx, regex, _, event| fun(cx, regex, event),
91 );
92 }
93 pub fn raw_regex_prompt(
94 cx: &mut crate::commands::Context,
95 prompt: std::borrow::Cow<'static, str>,
96 history_register: Option<char>,
97 completion_fn: impl FnMut(&Editor, &str) -> Vec<prompt::Completion> + 'static,
98 fun: impl Fn(&mut crate::compositor::Context, rope::Regex, &str, PromptEvent) + 'static,
99 ) {
100 let (view, doc) = current!(cx.editor);
101 let doc_id = view.doc;
102 let view_id = view.id;
103 let snapshot = doc.selection(view.id).clone();
104 let offset_snapshot = doc.view_offset(view.id);
105 let config = cx.editor.config();
106
107 let mut prompt = Prompt::new(
108 prompt,
109 history_register,
110 completion_fn,
111 move |cx: &mut crate::compositor::Context, input: &str, event: PromptEvent| {
112 match event {
113 PromptEvent::Abort => {
114 let doc = doc_mut!(cx.editor, &doc_id);
115 let view = view_mut!(cx.editor, view_id);
116 doc.set_selection(view.id, snapshot.clone());
117 doc.set_view_offset(view.id, offset_snapshot);
118 }
119 PromptEvent::Update | PromptEvent::Validate => {
120 // skip empty input
121 if input.is_empty() {
122 return;
123 }
124
125 let case_insensitive = if config.search.smart_case {
126 !input.chars().any(char::is_uppercase)
127 } else {
128 false
129 };
130
131 let is_crlf = doc!(cx.editor).line_ending == helix_core::LineEnding::Crlf;
132 match rope::RegexBuilder::new()
133 .syntax(
134 rope::Config::new()
135 .case_insensitive(case_insensitive)
136 .multi_line(true)
137 .crlf(is_crlf),
138 )
139 .build(input)
140 {
141 Ok(regex) => {
142 let doc = doc_mut!(cx.editor, &doc_id);
143 let view = view_mut!(cx.editor, view_id);
144
145 // revert state to what it was before the last update
146 doc.set_selection(view.id, snapshot.clone());
147
148 if event == PromptEvent::Validate {
149 // Equivalent to push_jump to store selection just before jump
150 view.push_jump(doc, (doc_id, snapshot.clone()));
151 }
152
153 fun(cx, regex, input, event);
154
155 let (view, doc) = current!(cx.editor);
156 view.ensure_cursor_in_view(doc, config.scrolloff);
157 }
158 Err(err) => {
159 let doc = doc_mut!(cx.editor, &doc_id);
160 let view = view_mut!(cx.editor, view_id);
161 doc.set_selection(view.id, snapshot.clone());
162 doc.set_view_offset(view.id, offset_snapshot);
163
164 if event == PromptEvent::Validate {
165 let callback = async move {
166 let call: job::Callback = Callback::EditorCompositor(Box::new(
167 move |_editor: &mut Editor, compositor: &mut Compositor| {
168 let contents = Text::new(format!("{}", err));
169 let size = compositor.size();
170 let popup = Popup::new("invalid-regex", contents)
171 .position(Some(helix_core::Position::new(
172 size.height as usize - 2, // 2 = statusline + commandline
173 0,
174 )))
175 .auto_close(true);
176 compositor.replace_or_push("invalid-regex", popup);
177 },
178 ));
179 Ok(call)
180 };
181
182 cx.jobs.callback(callback);
183 }
184 }
185 }
186 }
187 }
188 },
189 )
190 .with_language("regex", std::sync::Arc::clone(&cx.editor.syn_loader));
191 // Calculate initial completion
192 prompt.recalculate_completion(cx.editor);
193 // prompt
194 cx.push_layer(Box::new(prompt));
195 }
196
197 /// We want to exclude files that the editor can't handle yet
198 fn get_excluded_types() -> ignore::types::Types {
199 use ignore::types::TypesBuilder;
200 let mut type_builder = TypesBuilder::new();
201 type_builder
202 .add(
203 "compressed",
204 "*.{zip,gz,bz2,zst,lzo,sz,tgz,tbz2,lz,lz4,lzma,lzo,z,Z,xz,7z,rar,cab}",
205 )
206 .expect("Invalid type definition");
207 type_builder.negate("all");
208 type_builder
209 .build()
210 .expect("failed to build excluded_types")
211 }
212
213 #[derive(Debug)]
214 pub struct FilePickerData {
215 root: PathBuf,
216 directory_style: Style,
217 }
218 type FilePicker = Picker<PathBuf, FilePickerData>;
219
220 pub fn file_picker(editor: &Editor, root: PathBuf) -> FilePicker {
221 use ignore::WalkBuilder;
222 use std::time::Instant;
223
224 let config = editor.config();
225 let data = FilePickerData {
226 root: root.clone(),
227 directory_style: editor.theme.get("ui.text.directory"),
228 };
229
230 let now = Instant::now();
231
232 let dedup_symlinks = config.file_picker.deduplicate_links;
233 let absolute_root = root.canonicalize().unwrap_or_else(|_| root.clone());
234
235 let mut walk_builder = WalkBuilder::new(&root);
236
237 let mut files = walk_builder
238 .hidden(config.file_picker.hidden)
239 .parents(config.file_picker.parents)
240 .ignore(config.file_picker.ignore)
241 .follow_links(config.file_picker.follow_symlinks)
242 .git_ignore(config.file_picker.git_ignore)
243 .git_global(config.file_picker.git_global)
244 .git_exclude(config.file_picker.git_exclude)
245 .sort_by_file_name(|name1, name2| name1.cmp(name2))
246 .max_depth(config.file_picker.max_depth)
247 .filter_entry(move |entry| filter_picker_entry(entry, &absolute_root, dedup_symlinks))
248 .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"))
249 .add_custom_ignore_filename(".helix/ignore")
250 .types(get_excluded_types())
251 .build()
252 .filter_map(|entry| {
253 let entry = entry.ok()?;
254 if !entry.path().is_file() {
255 return None;
256 }
257 Some(entry.into_path())
258 });
259 log::debug!("file_picker init {:?}", Instant::now().duration_since(now));
260
261 let columns = [PickerColumn::new(
262 "path",
263 |item: &PathBuf, data: &FilePickerData| {
264 let path = item.strip_prefix(&data.root).unwrap_or(item);
265 let mut spans = Vec::with_capacity(3);
266 if let Some(dirs) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
267 spans.extend([
268 Span::styled(dirs.to_string_lossy(), data.directory_style),
269 Span::styled(std::path::MAIN_SEPARATOR_STR, data.directory_style),
270 ]);
271 }
272 let filename = path
273 .file_name()
274 .expect("normalized paths can't end in `..`")
275 .to_string_lossy();
276 spans.push(Span::raw(filename));
277 Spans::from(spans).into()
278 },
279 )];
280 let picker = Picker::new(columns, 0, [], data, move |cx, path: &PathBuf, action| {
281 if let Err(e) = cx.editor.open(path, action) {
282 let err = if let Some(err) = e.source() {
283 format!("{}", err)
284 } else {
285 format!("unable to open \"{}\"", path.display())
286 };
287 cx.editor.set_error(err);
288 }
289 })
290 .with_preview(|_editor, path| Some((path.as_path().into(), None)));
291 let injector = picker.injector();
292 let timeout = std::time::Instant::now() + std::time::Duration::from_millis(30);
293
294 let mut hit_timeout = false;
295 for file in &mut files {
296 if injector.push(file).is_err() {
297 break;
298 }
299 if std::time::Instant::now() >= timeout {
300 hit_timeout = true;
301 break;
302 }
303 }
304 if hit_timeout {
305 std::thread::spawn(move || {
306 for file in files {
307 if injector.push(file).is_err() {
308 break;
309 }
310 }
311 });
312 }
313 picker
314 }
315
316 type FileExplorer = Picker<(PathBuf, bool), (PathBuf, Style)>;
317
318 pub fn file_explorer(root: PathBuf, editor: &Editor) -> Result<FileExplorer, std::io::Error> {
319 let directory_style = editor.theme.get("ui.text.directory");
320 let directory_content = directory_content(&root, editor)?;
321
322 let columns = [PickerColumn::new(
323 "path",
324 |(path, is_dir): &(PathBuf, bool), (root, directory_style): &(PathBuf, Style)| {
325 let name = path.strip_prefix(root).unwrap_or(path).to_string_lossy();
326 if *is_dir {
327 Span::styled(format!("{}/", name), *directory_style).into()
328 } else {
329 name.into()
330 }
331 },
332 )];
333 let picker = Picker::new(
334 columns,
335 0,
336 directory_content,
337 (root, directory_style),
338 move |cx, (path, is_dir): &(PathBuf, bool), action| {
339 if *is_dir {
340 let new_root = helix_stdx::path::normalize(path);
341 let callback = Box::pin(async move {
342 let call: Callback =
343 Callback::EditorCompositor(Box::new(move |editor, compositor| {
344 if let Ok(picker) = file_explorer(new_root, editor) {
345 compositor.push(Box::new(overlay::overlaid(picker)));
346 }
347 }));
348 Ok(call)
349 });
350 cx.jobs.callback(callback);
351 } else if let Err(e) = cx.editor.open(path, action) {
352 let err = if let Some(err) = e.source() {
353 format!("{}", err)
354 } else {
355 format!("unable to open \"{}\"", path.display())
356 };
357 cx.editor.set_error(err);
358 }
359 },
360 )
361 .with_preview(|_editor, (path, _is_dir)| Some((path.as_path().into(), None)));
362
363 Ok(picker)
364 }
365
366 fn directory_content(root: &Path, editor: &Editor) -> Result<Vec<(PathBuf, bool)>, std::io::Error> {
367 use ignore::WalkBuilder;
368
369 let config = editor.config();
370
371 let mut walk_builder = WalkBuilder::new(root);
372
373 let mut content: Vec<(PathBuf, bool)> = walk_builder
374 .hidden(config.file_explorer.hidden)
375 .parents(config.file_explorer.parents)
376 .ignore(config.file_explorer.ignore)
377 .follow_links(config.file_explorer.follow_symlinks)
378 .git_ignore(config.file_explorer.git_ignore)
379 .git_global(config.file_explorer.git_global)
380 .git_exclude(config.file_explorer.git_exclude)
381 .max_depth(Some(1))
382 .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"))
383 .add_custom_ignore_filename(".helix/ignore")
384 .types(get_excluded_types())
385 .build()
386 .filter_map(|entry| {
387 entry
388 .map(|entry| {
389 let path = entry.path();
390 let is_dir = path.is_dir();
391 let mut path = path.to_path_buf();
392 if is_dir && path != root && config.file_explorer.flatten_dirs {
393 while let Some(single_child_directory) = get_child_if_single_dir(&path) {
394 path = single_child_directory;
395 }
396 }
397 (path, is_dir)
398 })
399 .ok()
400 .filter(|entry| entry.0 != root)
401 })
402 .collect();
403
404 content.sort_by(|(path1, is_dir1), (path2, is_dir2)| (!is_dir1, path1).cmp(&(!is_dir2, path2)));
405
406 if root.parent().is_some() {
407 content.insert(0, (root.join(".."), true));
408 }
409
410 Ok(content)
411 }
412
413 fn get_child_if_single_dir(path: &Path) -> Option<PathBuf> {
414 let mut entries = path.read_dir().ok()?;
415 let entry = entries.next()?.ok()?;
416 let entry_path = entry.path();
417 if entries.next().is_none() && entry_path.is_dir() {
418 Some(entry_path)
419 } else {
420 None
421 }
422 }
423
424 pub mod completers {
425 use super::Utf8PathBuf;
426 use crate::ui::prompt::Completion;
427 use helix_core::command_line::{self, Tokenizer};
428 use helix_core::fuzzy::fuzzy_match;
429 use helix_core::syntax::config::LanguageServerFeature;
430 use helix_view::document::SCRATCH_BUFFER_NAME;
431 use helix_view::theme;
432 use helix_view::{editor::Config, Editor};
433 use once_cell::sync::Lazy;
434 use std::borrow::Cow;
435 use std::collections::BTreeSet;
436 use tui::text::Span;
437
438 pub type Completer = fn(&Editor, &str) -> Vec<Completion>;
439
440 pub fn none(_editor: &Editor, _input: &str) -> Vec<Completion> {
441 Vec::new()
442 }
443
444 pub fn buffer(editor: &Editor, input: &str) -> Vec<Completion> {
445 let names = editor.documents.values().map(|doc| {
446 doc.relative_path()
447 .map(|p| p.display().to_string().into())
448 .unwrap_or_else(|| Cow::from(SCRATCH_BUFFER_NAME))
449 });
450
451 fuzzy_match(input, names, true)
452 .into_iter()
453 .map(|(name, _)| ((0..), name.into()))
454 .collect()
455 }
456
457 pub fn theme(_editor: &Editor, input: &str) -> Vec<Completion> {
458 let mut names = theme::Loader::read_names(&helix_loader::config_dir().join("themes"));
459 for rt_dir in helix_loader::runtime_dirs() {
460 names.extend(theme::Loader::read_names(&rt_dir.join("themes")));
461 }
462 names.push("default".into());
463 names.push("base16_default".into());
464 names.sort();
465 names.dedup();
466
467 fuzzy_match(input, names, false)
468 .into_iter()
469 .map(|(name, _)| ((0..), name.into()))
470 .collect()
471 }
472
473 /// Recursive function to get all keys from this value and add them to vec
474 fn get_keys(value: &serde_json::Value, vec: &mut Vec<String>, scope: Option<&str>) {
475 if let Some(map) = value.as_object() {
476 for (key, value) in map.iter() {
477 let key = match scope {
478 Some(scope) => format!("{}.{}", scope, key),
479 None => key.clone(),
480 };
481 get_keys(value, vec, Some(&key));
482 if !value.is_object() {
483 vec.push(key);
484 }
485 }
486 }
487 }
488
489 /// Completes names of language servers which are running for the current document.
490 pub fn active_language_servers(editor: &Editor, input: &str) -> Vec<Completion> {
491 let language_servers = doc!(editor).language_servers().map(|ls| ls.name());
492
493 fuzzy_match(input, language_servers, false)
494 .into_iter()
495 .map(|(name, _)| ((0..), Span::raw(name.to_string())))
496 .collect()
497 }
498
499 /// Completes names of language servers which are configured for the language of the current
500 /// document.
501 pub fn configured_language_servers(editor: &Editor, input: &str) -> Vec<Completion> {
502 let language_servers = doc!(editor)
503 .language_config()
504 .into_iter()
505 .flat_map(|config| &config.language_servers)
506 .map(|ls| ls.name.as_str());
507
508 fuzzy_match(input, language_servers, false)
509 .into_iter()
510 .map(|(name, _)| ((0..), Span::raw(name.to_string())))
511 .collect()
512 }
513
514 pub fn setting(_editor: &Editor, input: &str) -> Vec<Completion> {
515 static KEYS: Lazy<Vec<String>> = Lazy::new(|| {
516 let mut keys = Vec::new();
517 let json = serde_json::json!(Config::default());
518 get_keys(&json, &mut keys, None);
519 keys
520 });
521
522 fuzzy_match(input, &*KEYS, false)
523 .into_iter()
524 .map(|(name, _)| ((0..), Span::raw(name)))
525 .collect()
526 }
527
528 pub fn filename(editor: &Editor, input: &str) -> Vec<Completion> {
529 filename_with_git_ignore(editor, input, true)
530 }
531
532 pub fn filename_with_git_ignore(
533 editor: &Editor,
534 input: &str,
535 git_ignore: bool,
536 ) -> Vec<Completion> {
537 filename_impl(editor, input, git_ignore, |entry| {
538 if entry.path().is_dir() {
539 FileMatch::AcceptIncomplete
540 } else {
541 FileMatch::Accept
542 }
543 })
544 }
545
546 pub fn language(editor: &Editor, input: &str) -> Vec<Completion> {
547 let text: String = "text".into();
548
549 let loader = editor.syn_loader.load();
550 let language_ids = loader
551 .language_configs()
552 .map(|config| &config.language_id)
553 .chain(std::iter::once(&text));
554
555 fuzzy_match(input, language_ids, false)
556 .into_iter()
557 .map(|(name, _)| ((0..), name.to_owned().into()))
558 .collect()
559 }
560
561 pub fn lsp_workspace_command(editor: &Editor, input: &str) -> Vec<Completion> {
562 let commands = doc!(editor)
563 .language_servers_with_feature(LanguageServerFeature::WorkspaceCommand)
564 .flat_map(|ls| {
565 ls.capabilities()
566 .execute_command_provider
567 .iter()
568 .flat_map(|options| options.commands.iter())
569 });
570
571 fuzzy_match(input, commands, false)
572 .into_iter()
573 .map(|(name, _)| ((0..), name.to_owned().into()))
574 .collect()
575 }
576
577 pub fn directory(editor: &Editor, input: &str) -> Vec<Completion> {
578 directory_with_git_ignore(editor, input, true)
579 }
580
581 pub fn directory_with_git_ignore(
582 editor: &Editor,
583 input: &str,
584 git_ignore: bool,
585 ) -> Vec<Completion> {
586 filename_impl(editor, input, git_ignore, |entry| {
587 if entry.path().is_dir() {
588 FileMatch::Accept
589 } else {
590 FileMatch::Reject
591 }
592 })
593 }
594
595 #[derive(Copy, Clone, PartialEq, Eq)]
596 enum FileMatch {
597 /// Entry should be ignored
598 Reject,
599 /// Entry is usable but can't be the end (for instance if the entry is a directory and we
600 /// try to match a file)
601 AcceptIncomplete,
602 /// Entry is usable and can be the end of the match
603 Accept,
604 }
605
606 // TODO: we could return an iter/lazy thing so it can fetch as many as it needs.
607 fn filename_impl<F>(
608 editor: &Editor,
609 input: &str,
610 git_ignore: bool,
611 filter_fn: F,
612 ) -> Vec<Completion>
613 where
614 F: Fn(&ignore::DirEntry) -> FileMatch,
615 {
616 // Rust's filename handling is really annoying.
617
618 use ignore::WalkBuilder;
619 use std::path::Path;
620
621 let is_tilde = input == "~";
622 let path = helix_stdx::path::expand_tilde(Path::new(input));
623
624 let (dir, file_name) = if input.ends_with(std::path::MAIN_SEPARATOR) {
625 (path, None)
626 } else {
627 let is_period = (input.ends_with((format!("{}.", std::path::MAIN_SEPARATOR)).as_str())
628 && input.len() > 2)
629 || input == ".";
630 let file_name = if is_period {
631 Some(String::from("."))
632 } else {
633 path.file_name()
634 .and_then(|file| file.to_str().map(|path| path.to_owned()))
635 };
636
637 let path = if is_period {
638 path
639 } else {
640 match path.parent() {
641 Some(path) if !path.as_os_str().is_empty() => Cow::Borrowed(path),
642 // Path::new("h")'s parent is Some("")...
643 _ => Cow::Owned(helix_stdx::env::current_working_dir()),
644 }
645 };
646
647 (path, file_name)
648 };
649
650 let end = input.len()..;
651
652 let files = WalkBuilder::new(&dir)
653 .hidden(false)
654 .follow_links(false) // We're scanning over depth 1
655 .git_ignore(git_ignore)
656 .max_depth(Some(1))
657 .build()
658 .filter_map(|file| {
659 file.ok().and_then(|entry| {
660 let fmatch = filter_fn(&entry);
661
662 if fmatch == FileMatch::Reject {
663 return None;
664 }
665
666 let path = entry.path();
667 let is_dir = path.is_dir();
668 let file_type = entry.file_type();
669 let is_symlink = file_type.is_some_and(|ft| ft.is_symlink());
670 let mut path = if is_tilde {
671 // if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on
672 // one of the directories the tilde will be replaced with a valid path not with a relative
673 // home directory name.
674 // ~ -> <TAB> -> /home/user
675 // ~/ -> <TAB> -> ~/first_entry
676 path.to_path_buf()
677 } else {
678 path.strip_prefix(&dir).unwrap_or(path).to_path_buf()
679 };
680
681 if fmatch == FileMatch::AcceptIncomplete {
682 path.push("");
683 }
684
685 let path = path.into_os_string().into_string().ok()?;
686 Some(Utf8PathBuf {
687 path,
688 is_dir,
689 is_symlink,
690 })
691 })
692 }) // TODO: unwrap or skip
693 .filter(|path| !path.path.is_empty());
694
695 let directory_color = editor.theme.get("ui.text.directory");
696 let symlink_color = editor.theme.get("ui.text.symlink");
697
698 let style_from_file = |file: Utf8PathBuf| {
699 if file.is_symlink {
700 Span::styled(file.path, symlink_color)
701 } else if file.is_dir {
702 Span::styled(file.path, directory_color)
703 } else {
704 Span::raw(file.path)
705 }
706 };
707
708 // if empty, return a list of dirs and files in current dir
709 if let Some(file_name) = file_name {
710 let range = (input.len().saturating_sub(file_name.len()))..;
711 fuzzy_match(&file_name, files, true)
712 .into_iter()
713 .map(|(name, _)| (range.clone(), style_from_file(name)))
714 .collect()
715
716 // TODO: complete to longest common match
717 } else {
718 let mut files: Vec<_> = files
719 .map(|file| (end.clone(), style_from_file(file)))
720 .collect();
721 files.sort_unstable_by(|(_, path1), (_, path2)| path1.content.cmp(&path2.content));
722 files
723 }
724 }
725
726 pub fn register(editor: &Editor, input: &str) -> Vec<Completion> {
727 let iter = editor
728 .registers
729 .iter_preview()
730 // Exclude special registers that shouldn't be written to
731 .filter(|(ch, _)| !matches!(ch, '%' | '#' | '.'))
732 .map(|(ch, _)| ch.to_string());
733
734 fuzzy_match(input, iter, false)
735 .into_iter()
736 .map(|(name, _)| ((0..), name.into()))
737 .collect()
738 }
739
740 pub fn program(_editor: &Editor, input: &str) -> Vec<Completion> {
741 static PROGRAMS_IN_PATH: Lazy<BTreeSet<String>> = Lazy::new(|| {
742 // Go through the entire PATH and read all files into a set.
743 let Some(path) = std::env::var_os("PATH") else {
744 return Default::default();
745 };
746
747 std::env::split_paths(&path)
748 .filter_map(|path| std::fs::read_dir(path).ok())
749 .flatten()
750 .filter_map(|res| {
751 let entry = res.ok()?;
752 let file_type = entry.file_type().ok()?;
753 if file_type.is_file() || file_type.is_symlink() {
754 entry.file_name().into_string().ok()
755 } else {
756 None
757 }
758 })
759 .collect()
760 });
761
762 fuzzy_match(input, PROGRAMS_IN_PATH.iter(), false)
763 .into_iter()
764 .map(|(name, _)| ((0..), name.clone().into()))
765 .collect()
766 }
767
768 /// This expects input to be a raw string of arguments, because this is what Signature's raw_after does.
769 pub fn repeating_filenames(editor: &Editor, input: &str) -> Vec<Completion> {
770 let token = match Tokenizer::new(input, false).last() {
771 Some(token) => token.unwrap(),
772 None => return filename(editor, input),
773 };
774
775 let offset = token.content_start;
776
777 let mut completions = filename(editor, &input[offset..]);
778 for completion in completions.iter_mut() {
779 completion.0.start += offset;
780 }
781 completions
782 }
783
784 pub fn shell(editor: &Editor, input: &str) -> Vec<Completion> {
785 let (command, args, complete_command) = command_line::split(input);
786
787 if complete_command {
788 return program(editor, command);
789 }
790
791 let mut completions = repeating_filenames(editor, args);
792 for completion in completions.iter_mut() {
793 // + 1 for separator between `command` and `args`
794 completion.0.start += command.len() + 1;
795 }
796
797 completions
798 }
799 }
800
801 #[cfg(test)]
802 mod tests {
803 use std::fs::{create_dir, File};
804
805 use super::*;
806
807 #[test]
808 fn test_get_child_if_single_dir() {
809 let root = tempfile::tempdir().unwrap();
810
811 assert_eq!(get_child_if_single_dir(root.path()), None);
812
813 let dir = root.path().join("dir1");
814 create_dir(&dir).unwrap();
815
816 assert_eq!(get_child_if_single_dir(root.path()), Some(dir));
817
818 let file = root.path().join("file");
819 File::create(file).unwrap();
820
821 assert_eq!(get_child_if_single_dir(root.path()), None);
822 }
823 }