readline/complete_helper.go

66 lines
1.3 KiB
Go
Raw Normal View History

2015-09-25 19:31:09 +03:00
package readline
2015-10-04 16:56:34 +03:00
import "github.com/chzyer/readline/runes"
2015-09-25 19:31:09 +03:00
type PrefixCompleter struct {
Name []rune
Children []*PrefixCompleter
}
func NewPrefixCompleter(pc ...*PrefixCompleter) *PrefixCompleter {
return PcItem("", pc...)
}
func PcItem(name string, pc ...*PrefixCompleter) *PrefixCompleter {
2015-11-14 05:21:55 +03:00
name += " "
2015-09-25 19:31:09 +03:00
return &PrefixCompleter{
Name: []rune(name),
Children: pc,
}
}
func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int) {
line = line[:pos]
goNext := false
var lineCompleter *PrefixCompleter
for _, child := range p.Children {
if len(line) >= len(child.Name) {
2015-10-04 16:56:34 +03:00
if runes.HasPrefix(line, child.Name) {
2015-11-14 05:21:55 +03:00
if len(line) == len(child.Name) {
newLine = append(newLine, []rune{' '})
} else {
newLine = append(newLine, child.Name)
}
2015-09-25 19:31:09 +03:00
offset = len(child.Name)
lineCompleter = child
goNext = true
}
} else {
2015-10-04 16:56:34 +03:00
if runes.HasPrefix(child.Name, line) {
2015-09-25 19:31:09 +03:00
newLine = append(newLine, child.Name[len(line):])
offset = len(line)
lineCompleter = child
}
}
}
if len(newLine) != 1 {
return
}
tmpLine := make([]rune, 0, len(line))
for i := offset; i < len(line); i++ {
2015-09-26 19:10:26 +03:00
if line[i] == ' ' {
2015-09-25 19:31:09 +03:00
continue
}
tmpLine = append(tmpLine, line[i:]...)
return lineCompleter.Do(tmpLine, len(tmpLine))
}
if goNext {
return lineCompleter.Do(nil, 0)
}
return
}