1use std::path::{Path, PathBuf};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct DirEnt {
15 pub name: String,
16 pub is_dir: bool,
17}
18
19pub trait PathSource {
22 fn list(&self, dir: &Path) -> Vec<DirEnt>;
23 fn home(&self) -> Option<PathBuf>;
24 fn is_dir(&self, path: &Path) -> bool {
25 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
26 return !self.list(path).is_empty();
27 };
28 let parent = path.parent().unwrap_or(path);
29 self.list(parent).iter().any(|e| e.name == name && e.is_dir)
30 }
31}
32
33pub struct FsSource;
35
36impl PathSource for FsSource {
37 fn list(&self, dir: &Path) -> Vec<DirEnt> {
38 let Ok(rd) = std::fs::read_dir(dir) else {
39 return Vec::new();
40 };
41 rd.flatten()
42 .filter_map(|e| {
43 let name = e.file_name().to_string_lossy().into_owned();
44 if name == "." || name == ".." {
45 return None;
46 }
47 let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false) || e.path().is_dir();
48 Some(DirEnt { name, is_dir })
49 })
50 .collect()
51 }
52
53 fn home(&self) -> Option<PathBuf> {
54 std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
55 }
56
57 fn is_dir(&self, path: &Path) -> bool {
58 path.is_dir()
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Outcome {
65 pub text: String,
66 pub candidates: Vec<String>,
67 pub selected: Option<usize>,
68 pub message: Option<String>,
69}
70
71impl Outcome {
72 pub fn list_hint(&self, max_chars: usize) -> String {
74 if let Some(msg) = &self.message
75 && self.candidates.is_empty()
76 {
77 return msg.clone();
78 }
79 if self.candidates.is_empty() {
80 return String::new();
81 }
82 let n = self.candidates.len();
83 let sel = self.selected.unwrap_or(0);
84 let mut parts = Vec::new();
85 let mut used = 0usize;
86 let start = if n <= 8 { 0 } else { sel.saturating_sub(2) };
88 for (i, c) in self.candidates.iter().enumerate().skip(start) {
89 let piece = if Some(i) == self.selected { format!("[{c}]") } else { c.clone() };
90 let extra = piece.len() + if parts.is_empty() { 0 } else { 2 };
91 if used + extra > max_chars && !parts.is_empty() {
92 parts.push("…".into());
93 break;
94 }
95 used += extra;
96 parts.push(piece);
97 }
98 parts.join(" ")
99 }
100
101 pub fn changed(&self, previous: &str) -> bool {
103 self.text != previous || self.selected.is_some() || self.message.is_some()
104 }
105}
106
107#[derive(Debug, Clone, Default)]
109pub struct Engine {
110 cycle: Option<Cycle>,
111}
112
113#[derive(Debug, Clone)]
114struct Cycle {
115 stem: String,
116 matches: Vec<String>,
117 index: Option<usize>,
119 shown: String,
120}
121
122impl Engine {
123 pub fn new() -> Self {
124 Self::default()
125 }
126
127 pub fn reset(&mut self) {
128 self.cycle = None;
129 }
130
131 pub fn tab(&mut self, text: &str, stem: &str, token: &str, matches: &[String], reverse: bool) -> Outcome {
134 if let Some(c) = &self.cycle
135 && text == c.shown
136 && !c.matches.is_empty()
137 && c.matches == matches
138 {
139 let n = c.matches.len();
140 let i = match c.index {
141 None => {
142 if reverse {
143 n - 1
144 } else {
145 0
146 }
147 }
148 Some(i) => {
149 if reverse {
150 (i + n - 1) % n
151 } else {
152 (i + 1) % n
153 }
154 }
155 };
156 let shown = format!("{}{}", c.stem, c.matches[i]);
157 let matches = c.matches.clone();
158 self.cycle = Some(Cycle { stem: c.stem.clone(), matches: matches.clone(), index: Some(i), shown: shown.clone() });
159 return Outcome { text: shown, candidates: matches, selected: Some(i), message: None };
160 }
161
162 if matches.is_empty() {
163 self.cycle = None;
164 return Outcome { text: text.to_string(), candidates: Vec::new(), selected: None, message: Some("no matches".into()) };
165 }
166
167 if matches.len() == 1 {
168 let shown = format!("{}{}", stem, matches[0]);
169 self.cycle = Some(Cycle { stem: stem.into(), matches: matches.to_vec(), index: Some(0), shown: shown.clone() });
170 return Outcome { text: shown, candidates: matches.to_vec(), selected: Some(0), message: None };
171 }
172
173 let common = common_prefix(matches);
174 if !reverse && common.len() > token.len() {
175 let shown = format!("{stem}{common}");
176 self.cycle = Some(Cycle { stem: stem.into(), matches: matches.to_vec(), index: None, shown: shown.clone() });
177 return Outcome { text: shown, candidates: matches.to_vec(), selected: None, message: None };
178 }
179
180 let i = if reverse { matches.len() - 1 } else { 0 };
181 let shown = format!("{}{}", stem, matches[i]);
182 self.cycle = Some(Cycle { stem: stem.into(), matches: matches.to_vec(), index: Some(i), shown: shown.clone() });
183 Outcome { text: shown, candidates: matches.to_vec(), selected: Some(i), message: None }
184 }
185}
186
187pub fn common_prefix(items: &[String]) -> String {
189 let Some(first) = items.first() else {
190 return String::new();
191 };
192 let mut end = first.len();
193 for s in &items[1..] {
194 end = first.as_bytes().iter().zip(s.as_bytes()).take_while(|(a, b)| a == b).count().min(end);
195 while !first.is_char_boundary(end) {
196 end = end.saturating_sub(1);
197 }
198 }
199 first[..end].to_string()
200}
201
202pub fn prefix_matches(names: &[String], token: &str, ignore_case: bool, drop_hidden: bool) -> Vec<String> {
205 let hide = drop_hidden && !token.starts_with('.');
206 let mut out: Vec<String> = names
207 .iter()
208 .filter(|n| {
209 if hide && n.starts_with('.') {
210 return false;
211 }
212 if ignore_case { n.to_lowercase().starts_with(&token.to_lowercase()) } else { n.starts_with(token) }
213 })
214 .cloned()
215 .collect();
216 out.sort();
217 out.dedup();
218 out
219}
220
221fn split_last(s: &str) -> (&str, &str) {
222 match s.rfind(|c| c == '/' || (cfg!(windows) && c == '\\')) {
223 Some(0) => {
224 let sep = &s[0..1];
225 (sep, &s[1..])
226 }
227 Some(i) => (&s[..i], &s[i + 1..]),
228 None => ("", s),
229 }
230}
231
232pub fn split_path(input: &str, cwd: &Path, source: &dyn PathSource) -> (String, String, PathBuf) {
236 if input == "~" {
237 return (String::new(), "~".into(), source.home().unwrap_or_else(|| PathBuf::from("~")));
238 }
239 if let Some(rest) = input.strip_prefix("~/")
240 && let Some(home) = source.home()
241 {
242 let (dir_rel, name) = split_last(rest);
243 let dir = if dir_rel.is_empty() { home } else { home.join(dir_rel) };
244 let stem = if dir_rel.is_empty() { "~/".into() } else { format!("~/{dir_rel}/") };
245 return (stem, name.to_string(), dir);
246 }
247 let abs = input.starts_with('/') || (cfg!(windows) && Path::new(input).is_absolute());
248 let (dir_s, name) = split_last(input);
249 if abs {
250 let dir = if dir_s.is_empty() || dir_s == "/" { PathBuf::from("/") } else { PathBuf::from(dir_s) };
251 let stem = if dir_s == "/" || dir_s.is_empty() { "/".into() } else { format!("{dir_s}/") };
252 return (stem, name.to_string(), dir);
253 }
254 let dir = if dir_s.is_empty() { cwd.to_path_buf() } else { cwd.join(dir_s) };
255 let stem = if dir_s.is_empty() { String::new() } else { format!("{dir_s}/") };
256 (stem, name.to_string(), dir)
257}
258
259pub fn path_matches(input: &str, cwd: &Path, source: &dyn PathSource, directories_only: bool) -> (String, String, Vec<String>) {
261 if input == "~" {
262 if source.home().is_some() {
263 return (String::new(), "~".into(), vec!["~/".into()]);
264 }
265 return (String::new(), "~".into(), Vec::new());
266 }
267 let (stem, token, dir) = split_path(input, cwd, source);
268 let drop_hidden = !token.starts_with('.');
269 let mut out = Vec::new();
270 for e in source.list(&dir) {
271 if drop_hidden && e.name.starts_with('.') {
272 continue;
273 }
274 if directories_only && !e.is_dir {
275 continue;
276 }
277 if !e.name.starts_with(&token) {
278 continue;
279 }
280 let mut v = e.name;
281 if e.is_dir {
282 v.push('/');
283 }
284 out.push(v);
285 }
286 out.sort();
287 out.dedup();
288 (stem, token, out)
289}
290
291pub fn value_matches(input: &str, values: &[String]) -> (String, String, Vec<String>) {
293 (String::new(), input.to_string(), prefix_matches(values, input, true, false))
294}
295
296#[derive(Debug, Clone)]
298pub enum Arg {
299 None,
300 Values(Vec<String>),
301 Path { directories_only: bool },
302}
303
304#[derive(Debug, Clone)]
306pub struct Cmd {
307 pub name: String,
308 pub arg: Arg,
309}
310
311fn split_cmd(input: &str) -> (String, String, bool) {
312 match input.find(char::is_whitespace) {
313 Some(i) => (input[..i].to_string(), input[i..].trim_start().to_string(), true),
314 None => (input.to_string(), String::new(), false),
315 }
316}
317
318pub fn command_matches(input: &str, commands: &[Cmd], cwd: &Path, source: &dyn PathSource) -> (String, String, Vec<String>) {
321 let raw = input.strip_prefix(':').unwrap_or(input);
322 let colon = if input.starts_with(':') { ":" } else { "" };
323 let (head, arg, has_arg) = split_cmd(raw);
324 if !has_arg {
325 let names: Vec<String> = commands.iter().map(|c| c.name.clone()).collect();
326 let matches = prefix_matches(&names, &head, true, false);
327 let matches: Vec<String> = matches
328 .into_iter()
329 .map(|n| {
330 let spacer = commands.iter().find(|c| c.name == n).is_some_and(|c| !matches!(&c.arg, Arg::None));
331 if spacer { format!("{colon}{n} ") } else { format!("{colon}{n}") }
332 })
333 .collect();
334 return (String::new(), input.to_string(), matches);
335 }
336 let Some(cmd) = commands.iter().find(|c| c.name.eq_ignore_ascii_case(&head)) else {
337 return (format!("{colon}{head} "), arg, Vec::new());
338 };
339 let stem = format!("{colon}{head} ");
340 match &cmd.arg {
341 Arg::None => (stem, arg, Vec::new()),
342 Arg::Values(v) => {
343 let matches = prefix_matches(v, &arg, true, false);
344 (stem, arg, matches)
345 }
346 Arg::Path { directories_only } => {
347 let (pstem, ptoken, matches) = path_matches(&arg, cwd, source, *directories_only);
348 (format!("{stem}{pstem}"), ptoken, matches)
349 }
350 }
351}
352
353pub fn executables(prefix: &str) -> Vec<String> {
355 let path = std::env::var_os("PATH").unwrap_or_default();
356 let mut names = Vec::new();
357 for dir in std::env::split_paths(&path) {
358 let Ok(rd) = std::fs::read_dir(&dir) else { continue };
359 for e in rd.flatten() {
360 let name = e.file_name().to_string_lossy().into_owned();
361 if !name.starts_with(prefix) || name.starts_with('.') {
362 continue;
363 }
364 #[cfg(unix)]
365 {
366 use std::os::unix::fs::PermissionsExt;
367 let Ok(meta) = e.metadata() else { continue };
368 if !meta.is_file() || meta.permissions().mode() & 0o111 == 0 {
369 continue;
370 }
371 }
372 names.push(name);
373 }
374 }
375 names.sort();
376 names.dedup();
377 names
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383 use std::fs;
384
385 struct Tmp(PathBuf);
386 impl Tmp {
387 fn new() -> Self {
388 let p = std::env::temp_dir().join(format!(
389 "mouser-complete-{}-{}",
390 std::process::id(),
391 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
392 ));
393 fs::create_dir_all(&p).unwrap();
394 Self(p)
395 }
396 fn path(&self) -> &Path {
397 &self.0
398 }
399 }
400 impl Drop for Tmp {
401 fn drop(&mut self) {
402 let _ = fs::remove_dir_all(&self.0);
403 }
404 }
405
406 fn tmp() -> (Tmp, PathBuf) {
407 let t = Tmp::new();
408 let p = t.path().to_path_buf();
409 (t, p)
410 }
411
412 fn names(dir: &Path, entries: &[(&str, bool)]) {
413 for (name, is_dir) in entries {
414 let p = dir.join(name);
415 if *is_dir {
416 fs::create_dir_all(&p).unwrap();
417 } else {
418 if let Some(parent) = p.parent() {
419 fs::create_dir_all(parent).unwrap();
420 }
421 fs::write(&p, b"").unwrap();
422 }
423 }
424 }
425
426 #[test]
427 fn common_prefix_and_no_matches() {
428 assert_eq!(common_prefix(&[("docs").into(), ("downloads").into()]), "do");
429 assert_eq!(common_prefix(&[("dest_shared_x/").into(), ("dest_shared_y/").into()]), "dest_shared_");
430 assert_eq!(common_prefix(&["only".into()]), "only");
431 assert_eq!(common_prefix(&[]), "");
432 let mut e = Engine::new();
433 let o = e.tab("zzz", "", "zzz", &[], false);
434 assert_eq!(o.text, "zzz");
435 assert_eq!(o.message.as_deref(), Some("no matches"));
436 assert!(o.candidates.is_empty());
437 }
438
439 #[test]
440 fn unique_match_and_cycle() {
441 let mut e = Engine::new();
442 let o = e.tab("de", "", "de", &["dest_a/".into(), "dest_b/".into()], false);
443 assert_eq!(o.text, "dest_");
444 assert_eq!(o.candidates.len(), 2);
445 assert_eq!(o.selected, None);
446 let o = e.tab(&o.text, "", "dest_", &["dest_a/".into(), "dest_b/".into()], false);
447 assert_eq!(o.text, "dest_a/");
448 assert_eq!(o.selected, Some(0));
449 let o = e.tab(&o.text, "", "dest_a/", &["dest_a/".into(), "dest_b/".into()], false);
450 assert_eq!(o.text, "dest_b/");
451 assert_eq!(o.selected, Some(1));
452 let o = e.tab(&o.text, "", "dest_b/", &["dest_a/".into(), "dest_b/".into()], true);
453 assert_eq!(o.text, "dest_a/");
454 let o = e.tab("dest_a/", "", "dest_a/", &["dest_a/".into()], false);
455 assert_eq!(o.text, "dest_a/");
456 assert_eq!(o.selected, Some(0));
457 }
458
459 #[test]
460 fn path_tilde_hidden_dirs_and_relative() {
461 let (_t, root) = tmp();
462 names(&root, &[("docs", true), ("downloads", true), ("notes.md", false), (".secret", false), (".hidden_dir", true)]);
463 let home = root.join("homeuser");
464 fs::create_dir_all(home.join("Documents")).unwrap();
465 fs::write(home.join("Documents").join("a.txt"), b"").unwrap();
466 let old_home = std::env::var_os("HOME");
467 unsafe { std::env::set_var("HOME", &home) };
469
470 let src = FsSource;
471 let (stem, token, matches) = path_matches("do", &root, &src, false);
472 assert_eq!(stem, "");
473 assert_eq!(token, "do");
474 assert_eq!(matches, vec!["docs/".to_string(), "downloads/".to_string()]);
475
476 let (_, _, files) = path_matches("n", &root, &src, false);
477 assert_eq!(files, vec!["notes.md".to_string()]);
478 let (_, _, only_dirs) = path_matches("n", &root, &src, true);
479 assert!(only_dirs.is_empty(), "notes.md is not a directory");
480
481 let (_, _, vis) = path_matches("", &root, &src, false);
482 assert!(!vis.iter().any(|n| n.starts_with('.')), "hidden skipped without a dot prefix: {vis:?}");
483 let (_, _, hid) = path_matches(".", &root, &src, false);
484 assert!(hid.contains(&".secret".to_string()) && hid.contains(&".hidden_dir/".to_string()), "{hid:?}");
485
486 let (stem, token, matches) = path_matches("~/Do", &root, &src, false);
487 assert_eq!(stem, "~/");
488 assert_eq!(token, "Do");
489 assert_eq!(matches, vec!["Documents/".to_string()]);
490
491 let mut e = Engine::new();
492 let o = e.tab("~", "", "~", &["~/".into()], false);
493 assert_eq!(o.text, "~/");
494
495 let (stem, token, matches) = path_matches("docs/", &root, &src, false);
496 assert_eq!((stem.as_str(), token.as_str()), ("docs/", ""));
497 let _ = matches;
498
499 match old_home {
500 Some(v) => unsafe { std::env::set_var("HOME", v) },
501 None => unsafe { std::env::remove_var("HOME") },
502 }
503 }
504
505 #[test]
506 fn command_name_then_path_arg() {
507 let (_t, root) = tmp();
508 names(&root, &[("themes", true)]);
509 let cmds = vec![
510 Cmd { name: "theme".into(), arg: Arg::Values(vec!["Omarchy".into(), "Red Star".into()]) },
511 Cmd { name: "import-theme".into(), arg: Arg::Path { directories_only: true } },
512 Cmd { name: "edit-theme".into(), arg: Arg::None },
513 ];
514 let src = FsSource;
515 let (_, _, m) = command_matches("imp", &cmds, &root, &src);
516 assert_eq!(m, vec!["import-theme ".to_string()]);
517 let (_, _, m) = command_matches("theme Om", &cmds, &root, &src);
518 assert_eq!(m, vec!["Omarchy".to_string()]);
519 let (stem, token, m) = command_matches("import-theme th", &cmds, &root, &src);
520 assert_eq!(stem, "import-theme ");
521 assert_eq!(token, "th");
522 assert_eq!(m, vec!["themes/".to_string()]);
523 let (_, _, m) = command_matches("edit-theme", &cmds, &root, &src);
524 assert_eq!(m, vec!["edit-theme".to_string()]);
525 }
526
527 #[test]
528 fn list_hint_marks_selection() {
529 let o = Outcome { text: "dest_b/".into(), candidates: vec!["dest_a/".into(), "dest_b/".into()], selected: Some(1), message: None };
530 let h = o.list_hint(80);
531 assert!(h.contains("[dest_b/]") && h.contains("dest_a/"), "{h}");
532 let empty = Outcome { text: "z".into(), candidates: vec![], selected: None, message: Some("no matches".into()) };
533 assert_eq!(empty.list_hint(40), "no matches");
534 }
535}