From 70e49535193208b543c26f82e33bde3044e00a56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=AAnis=20Volpato=20Martins?= Date: Tue, 29 Jan 2019 17:36:39 -0200 Subject: [PATCH] Add aliases in autocompletion --- command.go | 2 +- completer.go | 21 +++++++++++++-------- example/main.go | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/command.go b/command.go index 4ede7e6..082eae0 100644 --- a/command.go +++ b/command.go @@ -26,7 +26,7 @@ type Cmd struct { // By default all commands get autocomplete of // subcommands. // A non-nil Completer overrides the default behaviour. - Completer func(args []string) []string + Completer func(cmd *Cmd, args []string, prefix string) []string // subcommands. children map[string]*Cmd diff --git a/completer.go b/completer.go index 2071af0..eabae41 100644 --- a/completer.go +++ b/completer.go @@ -3,7 +3,7 @@ package ishell import ( "strings" - "github.com/flynn-archive/go-shlex" + shlex "github.com/flynn-archive/go-shlex" ) type iCompleter struct { @@ -23,14 +23,12 @@ func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) { words = strings.Fields(string(line)) } - var cWords []string prefix := "" if len(words) > 0 && pos > 0 && line[pos-1] != ' ' { prefix = words[len(words)-1] - cWords = ic.getWords(words[:len(words)-1]) - } else { - cWords = ic.getWords(words) + words = words[:len(words)-1] } + cWords := ic.getWords(words, prefix) var suggestions [][]rune for _, w := range cWords { @@ -44,16 +42,23 @@ func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) { return suggestions, len(prefix) } -func (ic iCompleter) getWords(w []string) (s []string) { +func (ic iCompleter) getWords(w []string, prefix string) (s []string) { cmd, args := ic.cmd.FindCmd(w) if cmd == nil { cmd, args = ic.cmd, w } if cmd.Completer != nil { - return cmd.Completer(args) + return cmd.Completer(cmd, args, prefix) } - for k := range cmd.children { + for k, child := range cmd.children { s = append(s, k) + + // add aliases when command name won't match + if !strings.HasPrefix(k, prefix) { + for _, a := range child.Aliases { + s = append(s, a) + } + } } return } diff --git a/example/main.go b/example/main.go index fcb1822..64bff6b 100644 --- a/example/main.go +++ b/example/main.go @@ -195,7 +195,7 @@ This is an example of a long help.`, autoCmd.AddCmd(&ishell.Cmd{ Name: "words", Help: "add words with 'suggest add', then tab after typing 'suggest words '", - Completer: func([]string) []string { + Completer: func(cmd *ishell.Cmd, args []string, prefix string) []string { return words }, })