From f657e6e916ef8a31662ac09c5bb69f7574133a64 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 16 Sep 2022 14:17:07 +0530 Subject: [PATCH] Allow using a base directory other than the cwd when completing files --- tools/completion/files.go | 18 ++++++++++++++---- tools/completion/files_test.go | 2 +- tools/completion/kitty.go | 2 +- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tools/completion/files.go b/tools/completion/files.go index 934f13380..78681b125 100644 --- a/tools/completion/files.go +++ b/tools/completion/files.go @@ -30,7 +30,14 @@ type FileEntry struct { is_dir, is_symlink, is_empty_dir bool } -func complete_files(prefix string, callback func(*FileEntry)) error { +func complete_files(prefix string, callback func(*FileEntry), cwd string) error { + if cwd == "" { + var err error + cwd, err = os.Getwd() + if err != nil { + return err + } + } location := absolutize_path(prefix) base_dir := "" joinable_prefix := "" @@ -48,7 +55,7 @@ func complete_files(prefix string, callback func(*FileEntry)) error { base_dir = location joinable_prefix = "~/" case "": - base_dir = "." + base_dir = cwd joinable_prefix = "" default: if strings.HasSuffix(prefix, utils.Sep) { @@ -63,7 +70,10 @@ func complete_files(prefix string, callback func(*FileEntry)) error { } } if base_dir == "" { - base_dir = "." + base_dir = cwd + } + if !strings.HasPrefix(base_dir, "~") && !filepath.IsAbs(base_dir) { + base_dir = filepath.Join(cwd, base_dir) } // fmt.Printf("prefix=%#v base_dir=%#v joinable_prefix=%#v\n", prefix, base_dir, joinable_prefix) entries, err := os.ReadDir(base_dir) @@ -167,7 +177,7 @@ func complete_by_fnmatch(prefix string, patterns []string) []string { if matches(q) { ans = append(ans, entry.completion_candidate) } - }) + }, "") return ans } diff --git a/tools/completion/files_test.go b/tools/completion/files_test.go index 958c624e2..0d6589f27 100644 --- a/tools/completion/files_test.go +++ b/tools/completion/files_test.go @@ -44,7 +44,7 @@ func TestCompleteFiles(t *testing.T) { if _, err := os.Stat(entry.abspath); err != nil { t.Fatalf("Abspath does not exist: %#v", entry.abspath) } - }) + }, "") sort.Strings(actual) if !reflect.DeepEqual(expected, actual) { t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual) diff --git a/tools/completion/kitty.go b/tools/completion/kitty.go index 3e1c61aa6..d4e691313 100644 --- a/tools/completion/kitty.go +++ b/tools/completion/kitty.go @@ -41,6 +41,6 @@ func complete_kitty(completions *Completions, word string, arg_num int) { } else if unix.Access(entry.abspath, unix.X_OK) == nil { mg.add_match(entry.completion_candidate) } - }) + }, "") } }