aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/chzyer/readline/complete_segment.go
blob: 5ceadd80f9794a0f09be3868dc20e93111e96545 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package readline

type SegmentCompleter interface {
	// a
	// |- a1
	// |--- a11
	// |- a2
	// b
	// input:
	//   DoTree([], 0) [a, b]
	//   DoTree([a], 1) [a]
	//   DoTree([a, ], 0) [a1, a2]
	//   DoTree([a, a], 1) [a1, a2]
	//   DoTree([a, a1], 2) [a1]
	//   DoTree([a, a1, ], 0) [a11]
	//   DoTree([a, a1, a], 1) [a11]
	DoSegment([][]rune, int) [][]rune
}

type dumpSegmentCompleter struct {
	f func([][]rune, int) [][]rune
}

func (d *dumpSegmentCompleter) DoSegment(segment [][]rune, n int) [][]rune {
	return d.f(segment, n)
}

func SegmentFunc(f func([][]rune, int) [][]rune) AutoCompleter {
	return &SegmentComplete{&dumpSegmentCompleter{f}}
}

func SegmentAutoComplete(completer SegmentCompleter) *SegmentComplete {
	return &SegmentComplete{
		SegmentCompleter: completer,
	}
}

type SegmentComplete struct {
	SegmentCompleter
}

func RetSegment(segments [][]rune, cands [][]rune, idx int) ([][]rune, int) {
	ret := make([][]rune, 0, len(cands))
	lastSegment := segments[len(segments)-1]
	for _, cand := range cands {
		if !runes.HasPrefix(cand, lastSegment) {
			continue
		}
		ret = append(ret, cand[len(lastSegment):])
	}
	return ret, idx
}

func SplitSegment(line []rune, pos int) ([][]rune, int) {
	segs := [][]rune{}
	lastIdx := -1
	line = line[:pos]
	pos = 0
	for idx, l := range line {
		if l == ' ' {
			pos = 0
			segs = append(segs, line[lastIdx+1:idx])
			lastIdx = idx
		} else {
			pos++
		}
	}
	segs = append(segs, line[lastIdx+1:])
	return segs, pos
}

func (c *SegmentComplete) Do(line []rune, pos int) (newLine [][]rune, offset int) {

	segment, idx := SplitSegment(line, pos)

	cands := c.DoSegment(segment, idx)
	newLine, offset = RetSegment(segment, cands, idx)
	for idx := range newLine {
		newLine[idx] = append(newLine[idx], ' ')
	}
	return newLine, offset
}