Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve shell autocompletion #448

Merged
merged 3 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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