Skip to content

Commit

Permalink
Add aliases in autocompletion
Browse files Browse the repository at this point in the history
  • Loading branch information
denisvm committed Jan 29, 2019
1 parent 8b8aa74 commit 70e4953
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 13 additions & 8 deletions completer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package ishell
import (
"strings"

"github.com/flynn-archive/go-shlex"
shlex "github.com/flynn-archive/go-shlex"
)

type iCompleter struct {
Expand All @@ -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 {
Expand All @@ -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
}
2 changes: 1 addition & 1 deletion example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
})
Expand Down

0 comments on commit 70e4953

Please sign in to comment.