Improve shell autocompletion (#448)

* Fix autocompletion of second arg

* Fix autocompletion after ^C

* Autocomplete dirs on first arg
This commit is contained in:
Vincent Ollivier 2022-12-02 00:06:48 +01:00 committed by GitHub
parent 3348bb7150
commit d2722f85ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 15 deletions

View File

@ -33,10 +33,12 @@ impl Prompt {
while let Some(c) = io::stdin().read_char() { while let Some(c) = io::stdin().read_char() {
match c { match c {
console::ETX_KEY => { // End of Text (^C) console::ETX_KEY => { // End of Text (^C)
self.update_completion();
println!(); println!();
return Some(String::new()); return Some(String::new());
}, },
console::EOT_KEY => { // End of Transmission (^D) console::EOT_KEY => { // End of Transmission (^D)
self.update_completion();
println!(); println!();
return None; return None;
}, },

View File

@ -53,31 +53,40 @@ fn autocomplete_commands() -> Vec<String> {
fn shell_completer(line: &str) -> Vec<String> { fn shell_completer(line: &str) -> Vec<String> {
let mut entries = Vec::new(); let mut entries = Vec::new();
let mut args = split_args(line);
let args = split_args(line); if line.ends_with(' ') {
args.push(String::new());
}
let i = args.len() - 1; 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() { for cmd in autocomplete_commands() {
if let Some(entry) = cmd.strip_prefix(&args[i]) { if let Some(entry) = cmd.strip_prefix(&args[i]) {
entries.push(entry.into()); entries.push(entry.into());
} }
} }
} else { // Autocomplete path }
let pathname = fs::realpath(&args[i]);
let dirname = fs::dirname(&pathname); // Autocomplete path
let filename = fs::filename(&pathname); let pathname = fs::realpath(&args[i]);
let sep = if dirname.ends_with('/') { "" } else { "/" }; let dirname = fs::dirname(&pathname);
if let Ok(files) = fs::read_dir(dirname) { let filename = fs::filename(&pathname);
for file in files { let sep = if dirname.ends_with('/') { "" } else { "/" };
let name = file.name(); if let Ok(files) = fs::read_dir(dirname) {
if name.starts_with(filename) { for file in files {
let end = if file.is_dir() { "/" } else { "" }; let name = file.name();
let path = format!("{}{}{}{}", dirname, sep, name, end); if name.starts_with(filename) {
entries.push(path[pathname.len()..].into()); 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.sort();
entries entries
} }