tui: path completion for ~/ / ./ ../ #174
No files matched your search
@@ -186,7 +186,15 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
|
||||
label,
|
||||
detail: detail.into(),
|
||||
};
|
||||
let items = if let Some(q) = tok.strip_prefix('@') {
|
||||
let raw = tok.strip_prefix('@').unwrap_or(tok);
|
||||
let items = if is_fs_path(raw) && (start > 0 || tok.starts_with('@') || raw[1..].contains('/'))
|
||||
{
|
||||
let at = if tok.starts_with('@') { "@" } else { "" };
|
||||
complete_path(raw)
|
||||
.into_iter()
|
||||
.map(|f| cand(format!("{at}{f}"), ""))
|
||||
.collect()
|
||||
} else if let Some(q) = tok.strip_prefix('@') {
|
||||
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
|
||||
.into_iter()
|
||||
.map(|f| cand(format!("@{f}"), ""))
|
||||
@@ -221,6 +229,61 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
|
||||
Completion { start, items }
|
||||
}
|
||||
|
||||
pub fn is_fs_path(t: &str) -> bool {
|
||||
t == "~"
|
||||
|| t.starts_with(['/', '~']) && t.contains('/')
|
||||
|| t.starts_with("./")
|
||||
|| t.starts_with("../")
|
||||
}
|
||||
|
||||
/// Expand a leading `~/` to `$HOME`.
|
||||
pub fn expand_home(p: &str) -> PathBuf {
|
||||
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
|
||||
(Some(rest), Some(h)) => PathBuf::from(h).join(rest),
|
||||
_ => PathBuf::from(p),
|
||||
}
|
||||
}
|
||||
|
||||
/// Live directory listing for a `~/`, `/`, `./` or `../` token; the typed form is kept in labels.
|
||||
/// Directories first and suffixed `/`; dotfiles only when the prefix starts with `.`.
|
||||
fn complete_path(tok: &str) -> Vec<String> {
|
||||
if tok == "~" {
|
||||
return vec!["~/".into()];
|
||||
}
|
||||
let (dir, pre) = tok.rsplit_once('/').map_or(("", tok), |(d, p)| (d, p));
|
||||
let shown = format!("{dir}/");
|
||||
let real = if dir.is_empty() {
|
||||
PathBuf::from("/")
|
||||
} else {
|
||||
expand_home(&shown)
|
||||
};
|
||||
let Ok(rd) = std::fs::read_dir(real) else {
|
||||
return vec![];
|
||||
};
|
||||
let pre_l = pre.to_lowercase();
|
||||
let mut v: Vec<(bool, String)> = rd
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let n = e.file_name().to_string_lossy().into_owned();
|
||||
if (n.starts_with('.') && !pre.starts_with('.'))
|
||||
|| !n.to_lowercase().starts_with(&pre_l)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let d = e.path().is_dir();
|
||||
Some((d, if d { format!("{n}/") } else { n }))
|
||||
})
|
||||
.collect();
|
||||
v.sort_by(|a, b| {
|
||||
b.0.cmp(&a.0)
|
||||
.then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))
|
||||
});
|
||||
v.into_iter()
|
||||
.take(MAX_ENUM_ITEMS)
|
||||
.map(|(_, n)| format!("{shown}{n}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn detail(s: &CmdSpec) -> String {
|
||||
let tag = match s.source {
|
||||
Source::Builtin => "",
|
||||
@@ -289,6 +352,33 @@ pub fn common_prefix<S: AsRef<str>>(xs: &[S]) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn fs_paths_complete() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let r = d.path();
|
||||
std::fs::create_dir_all(r.join("Docs/sub")).unwrap();
|
||||
std::fs::write(r.join("doc.txt"), "").unwrap();
|
||||
std::fs::write(r.join(".hid"), "").unwrap();
|
||||
let t = |l: &str| -> Vec<String> {
|
||||
super::complete(l, l.len(), &[], &[])
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|c| c.label)
|
||||
.collect()
|
||||
};
|
||||
let b = r.display();
|
||||
assert_eq!(
|
||||
t(&format!("see {b}/do")),
|
||||
[format!("{b}/Docs/"), format!("{b}/doc.txt")]
|
||||
);
|
||||
assert_eq!(t(&format!("@{b}/Docs/")), [format!("@{b}/Docs/sub/")]);
|
||||
assert_eq!(t(&format!("{b}/.")), [format!("{b}/.hid")]);
|
||||
assert!(t(&format!("{b}/nope/x")).is_empty());
|
||||
assert_eq!(t("x ~"), ["~/"]);
|
||||
// slash command stays a command
|
||||
assert!(t("/etc").is_empty());
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
fn labels(c: &Completion) -> Vec<&str> {
|
||||
|
||||
@@ -243,7 +243,7 @@ pub fn project_files(root: &std::path::Path) -> Vec<String> {
|
||||
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
|
||||
let mut att = String::new();
|
||||
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
|
||||
let p = root.join(w);
|
||||
let p = root.join(cmd::expand_home(w));
|
||||
if let Ok(c) = std::fs::read_to_string(&p)
|
||||
&& c.len() < 200_000
|
||||
{
|
||||
@@ -1228,7 +1228,11 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
match labels.len() {
|
||||
0 => app.hint = "no match".into(),
|
||||
1 => {
|
||||
let l = format!("{} ", labels[0]);
|
||||
let l = if labels[0].ends_with('/') {
|
||||
labels[0].to_string()
|
||||
} else {
|
||||
format!("{} ", labels[0])
|
||||
};
|
||||
app.ed.replace(c.start, &l);
|
||||
}
|
||||
_ => {
|
||||
@@ -1260,19 +1264,22 @@ fn completion(app: &App) -> Completion {
|
||||
/// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big).
|
||||
fn live_popup(app: &mut App) {
|
||||
app.popup = None;
|
||||
if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') {
|
||||
if app.ed.buf.contains('\n') {
|
||||
return;
|
||||
}
|
||||
let c = completion(app);
|
||||
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||||
let tok = &app.ed.buf[c.start..app.ed.cur];
|
||||
let fs = cmd::is_fs_path(tok.strip_prefix('@').unwrap_or(tok));
|
||||
if fs || (app.ed.buf.starts_with('/') && !tok.starts_with('@')) {
|
||||
app.popup = popup::Popup::new(c);
|
||||
}
|
||||
}
|
||||
|
||||
fn accept(app: &mut App) {
|
||||
if let Some(p) = app.popup.take() {
|
||||
app.ed
|
||||
.replace(p.comp.start, &format!("{} ", p.selected_label()));
|
||||
let l = p.selected_label();
|
||||
let sp = if l.ends_with('/') { "" } else { " " };
|
||||
app.ed.replace(p.comp.start, &format!("{l}{sp}"));
|
||||
live_popup(app);
|
||||
}
|
||||
}
|
||||
@@ -2552,6 +2559,21 @@ mod tests {
|
||||
assert!(s.ends_with("/nonexistent-hx (missing)"), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fs_path_popup_opens_live_and_dirs_keep_going() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(d.path().join("alpha/inner")).unwrap();
|
||||
let mut app = test_app();
|
||||
for c in format!("look {}/al", d.path().display()).chars() {
|
||||
key(&mut app, KeyCode::Char(c));
|
||||
}
|
||||
assert!(app.popup.is_some());
|
||||
key(&mut app, KeyCode::Tab);
|
||||
assert!(app.ed.buf.ends_with("/alpha/"), "{}", app.ed.buf);
|
||||
key(&mut app, KeyCode::Tab);
|
||||
assert!(app.ed.buf.ends_with("/alpha/inner/"), "{}", app.ed.buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_keys_and_render() {
|
||||
let mut app = test_app();
|
||||
|
||||
Reference in new issue
Block a user