1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
|
use crate::parse::{self, CompletionContext};
use crate::{BString, Session};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::DirEntry;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fs};
pub struct Suggestion {
/// display string that is shown in the possibilities
pub display: BString,
/// *escaped* bytes that can be directly appended into terminal.
pub delta: BString,
}
fn _path_completion(
cc: CompletionContext,
filter: &dyn Fn(&DirEntry) -> bool,
) -> std::io::Result<Vec<Suggestion>> {
let delim = cc.delim;
let mut prefix = cc.partial;
let mut partial_entry = BString::new();
while let Some(c) = prefix.last().cloned() {
if c == b'/' {
break;
}
partial_entry.push(c);
prefix.pop();
}
partial_entry.reverse();
let mut sugs = Vec::new();
if prefix.is_empty() {
prefix.push(b'.');
}
for entry in fs::read_dir(OsStr::from_bytes(&prefix))? {
let entry = entry?;
if !filter(&entry) {
continue;
}
let name = entry.file_name().as_bytes().to_vec();
if name.starts_with(&partial_entry) {
let mut delta = BString::new();
delim.escape(&name[partial_entry.len()..], &mut delta);
let is_dir = entry.metadata().map(|m| m.is_dir()).unwrap_or(false);
if is_dir {
delta.push(b'/');
} else {
delim.write_closing_delimiter(&mut delta);
delta.push(b' ');
}
sugs.push(Suggestion {
display: name,
delta,
});
}
}
Ok(sugs)
}
pub fn path_completion(cc: CompletionContext) -> Vec<Suggestion> {
match _path_completion(cc, &|_| true) {
Ok(suggestions) => suggestions,
Err(err) => {
println!("path completion failed: {err:?}\r");
Vec::new()
}
}
}
pub fn path_exe_completion(cc: CompletionContext) -> Vec<Suggestion> {
match _path_completion(cc, &|d| is_executable(&d.path())) {
Ok(suggestions) => suggestions,
Err(err) => {
println!("path completion failed: {err:?}\r");
Vec::new()
}
}
}
pub fn variable_completion(session: Arc<Mutex<Session>>, prefix: BString) -> Vec<Suggestion> {
let se = session.lock().unwrap();
let mut out = Vec::new();
for var in se.vars.vars() {
if var.starts_with(&prefix) {
out.push(Suggestion {
display: var.to_vec(),
delta: var[prefix.len()..].to_vec(),
});
}
}
drop(se);
for var in env::vars_os() {
let var = var.0.as_bytes();
if var.starts_with(&prefix) {
out.push(Suggestion {
display: var.to_vec(),
delta: var[prefix.len()..].to_vec(),
});
}
}
out
}
#[derive(Default)]
pub struct PathCache {
binaries: HashMap<BString, PathBuf>,
}
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path)
.map(|m| m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
pub fn populate_path_cache(session: Arc<Mutex<Session>>) {
let path_var = env::var_os("PATH").unwrap();
let mut binaries = HashMap::new();
for dir in env::split_paths(&path_var) {
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && is_executable(&path) {
binaries.insert(path.file_name().unwrap().as_bytes().to_vec(), path);
}
}
}
}
session.lock().unwrap().path_cache = PathCache { binaries };
}
pub fn command_completion(session: Arc<Mutex<Session>>, cc: CompletionContext) -> Vec<Suggestion> {
let se = session.lock().unwrap();
let mut out = Vec::new();
for fun in se
.funs
.keys()
.chain(se.builtins.keys())
.chain(se.path_cache.binaries.keys())
{
if fun.starts_with(&cc.partial) {
let mut delta = BString::new();
cc.delim.escape(&fun[cc.partial.len()..], &mut delta);
cc.delim.write_closing_delimiter(&mut delta);
delta.push(b' ');
out.push(Suggestion {
display: fun.to_vec(),
delta,
})
}
}
out
}
pub struct CompletionResult {
pub kind: parse::CompletionKind,
pub suggestions: Vec<Suggestion>,
pub shared_prefix: BString,
}
impl CompletionResult {
pub fn empty() -> Self {
CompletionResult {
kind: parse::CompletionKind::None,
suggestions: Vec::new(),
shared_prefix: BString::new(),
}
}
}
pub fn completion(session: Arc<Mutex<Session>>, cmd: &[u8]) -> CompletionResult {
let comp = parse::completion_context(
&cmd,
&mut crate::run::Executor::new_for_completion(session.clone()),
);
let kind = comp.kind.clone();
let mut suggestions = match comp.kind {
parse::CompletionKind::Command => command_completion(session.clone(), comp),
parse::CompletionKind::PathCommand => path_exe_completion(comp),
parse::CompletionKind::Argument => path_completion(comp),
parse::CompletionKind::Variable => variable_completion(session.clone(), comp.partial),
parse::CompletionKind::None => return CompletionResult::empty(),
};
suggestions.sort_by(|x, y| x.delta.cmp(&y.delta));
suggestions.dedup_by(|x, y| x.delta == y.delta);
if suggestions.is_empty() {
return CompletionResult {
kind,
..CompletionResult::empty()
};
}
// find longest shared prefix
let mut shared_prefix = &suggestions[0].delta[..];
for s in suggestions.iter() {
let mut new = &shared_prefix[..0];
for i in 0..shared_prefix.len().min(s.delta.len()) {
if shared_prefix[i] != s.delta[i] {
break;
} else {
new = &s.delta[..=i];
}
}
shared_prefix = new;
}
let shared_prefix = shared_prefix.to_vec();
CompletionResult {
kind,
suggestions,
shared_prefix,
}
}
|