Hack to allow dynamic content in autocompletion.

Signed-off-by: Dan Cripe <dan@quattronetworks.com>
This commit is contained in:
Dan Cripe 2016-01-06 15:41:13 -06:00
parent 94a70819f4
commit cd2d269a73
1 changed files with 40 additions and 4 deletions

View File

@ -7,9 +7,16 @@ import (
"github.com/chzyer/readline/runes" "github.com/chzyer/readline/runes"
) )
type DynChildrenFunc func() [][]rune
type PrefixCompleter struct { type PrefixCompleter struct {
Name []rune Name []rune
Children []*PrefixCompleter Children []*PrefixCompleter
DynChildren DynChildrenFunc
}
func empty() [][]rune {
return [][]rune{}
} }
func (p *PrefixCompleter) Tree(prefix string) string { func (p *PrefixCompleter) Tree(prefix string) string {
@ -38,15 +45,25 @@ func NewPrefixCompleter(pc ...*PrefixCompleter) *PrefixCompleter {
return PcItem("", pc...) return PcItem("", pc...)
} }
func PcDyn(name string, term DynChildrenFunc) *PrefixCompleter {
name += " "
return &PrefixCompleter{
Name: []rune(name),
DynChildren: term,
}
}
func PcItem(name string, pc ...*PrefixCompleter) *PrefixCompleter { func PcItem(name string, pc ...*PrefixCompleter) *PrefixCompleter {
name += " " name += " "
return &PrefixCompleter{ return &PrefixCompleter{
Name: []rune(name), Name: []rune(name),
Children: pc, Children: pc,
DynChildren: empty,
} }
} }
func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int) { func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int) {
end := PcItem("")
line = line[:pos] line = line[:pos]
goNext := false goNext := false
var lineCompleter *PrefixCompleter var lineCompleter *PrefixCompleter
@ -70,6 +87,25 @@ func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int
} }
} }
} }
for _, dynChild := range p.DynChildren() {
if len(line) >= len(dynChild) {
if runes.HasPrefix(line, dynChild) {
if len(line) == len(dynChild) {
newLine = append(newLine, []rune{' '})
} else {
newLine = append(newLine, dynChild)
}
offset = len(dynChild)
lineCompleter = end
}
} else {
if runes.HasPrefix(dynChild, line) {
newLine = append(newLine, dynChild[len(line):])
offset = len(line)
lineCompleter = end
}
}
}
if len(newLine) != 1 { if len(newLine) != 1 {
return return