forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
79 lines (68 loc) · 1.83 KB
/
history.go
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
package prompt
import "strings"
// History stores the texts that are entered.
type History struct {
histories []string
tmp []string
selected int
}
// Add to add text in history.
func (h *History) Add(input string) {
h.histories = append(h.histories, input)
h.Clear()
}
// Clear to clear the history.
func (h *History) Clear() {
h.tmp = make([]string, len(h.histories))
for i := range h.histories {
h.tmp[i] = h.histories[i]
}
h.tmp = append(h.tmp, "")
h.selected = len(h.tmp) - 1
}
// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
// The changes of line buffers are stored until new history is created.
func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
if len(h.tmp) == 1 || h.selected == 0 {
return buf, false
}
h.tmp[h.selected] = buf.Text()
h.selected--
new = NewBuffer()
new.InsertText(h.tmp[h.selected], false, true)
return new, true
}
// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
// The changes of line buffers are stored until new history is created.
func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
if h.selected >= len(h.tmp)-1 {
return buf, false
}
h.tmp[h.selected] = buf.Text()
h.selected++
new = NewBuffer()
new.InsertText(h.tmp[h.selected], false, true)
return new, true
}
// SetCurrentCmd sets current command.
func (h *History) SetCurrentCmd(cmd string) {
h.tmp[h.selected] = cmd
}
// FindMatch finds last match of input in the specified prefix
// in current history state.
func (h *History) FindMatch(input string, prefix int) int {
for i := prefix; i >= 0; i-- {
if strings.Contains(h.tmp[i], input) {
return i
}
}
return -1
}
// NewHistory returns new history object.
func NewHistory() *History {
return &History{
histories: []string{},
tmp: []string{""},
selected: 0,
}
}