Skip to content

Commit f2ad97a

Browse files
rhussabiosoft
authored andcommitted
feature(completer): Add a new option to provide the prefix also to the completer function (#119)
1 parent 8b8aa74 commit f2ad97a

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

command.go

+7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ type Cmd struct {
2828
// A non-nil Completer overrides the default behaviour.
2929
Completer func(args []string) []string
3030

31+
// CompleterWithPrefix is custom autocomplete like
32+
// for Completer, but also provides the prefix
33+
// already so far to the completion function
34+
// If both Completer and CompleterWithPrefix are given,
35+
// CompleterWithPrefix takes precedence
36+
CompleterWithPrefix func(prefix string, args []string) []string
37+
3138
// subcommands.
3239
children map[string]*Cmd
3340
}

completer.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) {
2727
prefix := ""
2828
if len(words) > 0 && pos > 0 && line[pos-1] != ' ' {
2929
prefix = words[len(words)-1]
30-
cWords = ic.getWords(words[:len(words)-1])
30+
cWords = ic.getWords(prefix, words[:len(words)-1])
3131
} else {
32-
cWords = ic.getWords(words)
32+
cWords = ic.getWords(prefix, words)
3333
}
3434

3535
var suggestions [][]rune
@@ -44,11 +44,14 @@ func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) {
4444
return suggestions, len(prefix)
4545
}
4646

47-
func (ic iCompleter) getWords(w []string) (s []string) {
47+
func (ic iCompleter) getWords(prefix string, w []string) (s []string) {
4848
cmd, args := ic.cmd.FindCmd(w)
4949
if cmd == nil {
5050
cmd, args = ic.cmd, w
5151
}
52+
if cmd.CompleterWithPrefix != nil {
53+
return cmd.CompleterWithPrefix(prefix, args)
54+
}
5255
if cmd.Completer != nil {
5356
return cmd.Completer(args)
5457
}

0 commit comments

Comments
 (0)