Skip to content

Commit

Permalink
Improve shell autocompletion (#448)
Browse files Browse the repository at this point in the history
* Fix autocompletion of second arg

* Fix autocompletion after ^C

* Autocomplete dirs on first arg
  • Loading branch information
vinc authored Dec 1, 2022
1 parent 3348bb7 commit d2722f8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
2 changes: 2 additions & 0 deletions src/api/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ impl Prompt {
while let Some(c) = io::stdin().read_char() {
match c {
console::ETX_KEY => { // End of Text (^C)
self.update_completion();
println!();
return Some(String::new());
},
console::EOT_KEY => { // End of Transmission (^D)
self.update_completion();
println!();
return None;
},
Expand Down
39 changes: 24 additions & 15 deletions src/usr/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,40 @@ fn autocomplete_commands() -> Vec<String> {

fn shell_completer(line: &str) -> Vec<String> {
let mut entries = Vec::new();

let args = split_args(line);
let mut args = split_args(line);
if line.ends_with(' ') {
args.push(String::new());
}
let i = args.len() - 1;
if args.len() == 1 && !args[0].starts_with('/') && !args[0].starts_with('~') { // Autocomplete command

// Autocomplete command
if args.len() == 1 && !args[i].starts_with('/') && !args[i].starts_with('~') {
for cmd in autocomplete_commands() {
if let Some(entry) = cmd.strip_prefix(&args[i]) {
entries.push(entry.into());
}
}
} else { // Autocomplete path
let pathname = fs::realpath(&args[i]);
let dirname = fs::dirname(&pathname);
let filename = fs::filename(&pathname);
let sep = if dirname.ends_with('/') { "" } else { "/" };
if let Ok(files) = fs::read_dir(dirname) {
for file in files {
let name = file.name();
if name.starts_with(filename) {
let end = if file.is_dir() { "/" } else { "" };
let path = format!("{}{}{}{}", dirname, sep, name, end);
entries.push(path[pathname.len()..].into());
}

// Autocomplete path
let pathname = fs::realpath(&args[i]);
let dirname = fs::dirname(&pathname);
let filename = fs::filename(&pathname);
let sep = if dirname.ends_with('/') { "" } else { "/" };
if let Ok(files) = fs::read_dir(dirname) {
for file in files {
let name = file.name();
if name.starts_with(filename) {
if args.len() == 1 && !file.is_dir() {
continue;
}
let end = if args.len() != 1 && file.is_dir() { "/" } else { "" };
let path = format!("{}{}{}{}", dirname, sep, name, end);
entries.push(path[pathname.len()..].into());
}
}
}

entries.sort();
entries
}
Expand Down

0 comments on commit d2722f8

Please sign in to comment.