Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add aliases in autocompletion #109

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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