forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_search.go
54 lines (48 loc) · 1.32 KB
/
reverse_search.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
package prompt
import (
"strings"
)
const (
matchSearchPrefixFmt = "(reverse-i-search)`%s':"
failSearchPrefixFmt = "(failed reverse-i-search)`%s':"
)
// reverseSearchState contains info about reverseSearch state.
type reverseSearchState struct {
// history, with which reverse-search works.
history *History
// searchFromIndex is the last history index, included to the search scope.
searchFromIndex int
// matchedIndex is the index of the last matched.
matchedIndex int
// matchedCmd is the last matched command.
matchedCmd string
}
// NewReverseSearch returns new reverseSearchState instance.
func NewReverseSearch(history *History) *reverseSearchState {
return &reverseSearchState{
history: history,
searchFromIndex: history.selected,
matchedIndex: -1,
matchedCmd: "",
}
}
// reducePrefix reduces the search scope.
func (rs *reverseSearchState) reducePrefix() {
if rs.matchedIndex != -1 {
rs.searchFromIndex = rs.matchedIndex - 1
}
if rs.searchFromIndex < 0 {
rs.searchFromIndex = 0
}
}
// update updates current reverse-search state.
func (rs *reverseSearchState) update(input string) {
rs.matchedIndex = rs.history.FindMatch(
strings.TrimSpace(input), rs.searchFromIndex,
)
if rs.matchedIndex != -1 {
rs.matchedCmd = rs.history.tmp[rs.matchedIndex]
} else {
rs.matchedCmd = ""
}
}