/
histlist.go
129 lines (109 loc) · 2.54 KB
/
histlist.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package history
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/u-root/u-root/cmds/elvish/edit/eddefs"
"github.com/u-root/u-root/cmds/elvish/edit/ui"
)
// Command history listing mode.
// errStoreOffline is thrown when an operation requires the storage backend, but
// it is offline.
var errStoreOffline = errors.New("store offline")
type histlist struct {
all []string
dedup bool
caseInsensitive bool
last map[string]int
shown []string
index []int
indexWidth int
}
func newHistlist(cmds []string) *histlist {
last := make(map[string]int)
for i, entry := range cmds {
last[entry] = i
}
return &histlist{
// This has to be here for the initialization to work :(
all: cmds,
dedup: true,
last: last,
indexWidth: len(strconv.Itoa(len(cmds) - 1)),
}
}
func (hl *histlist) Teardown() {
*hl = histlist{}
}
func (hl *histlist) ModeTitle(i int) string {
s := " HISTORY "
if hl.dedup {
s += "(dedup on) "
}
if hl.caseInsensitive {
s += "(case-insensitive) "
}
return s
}
func (*histlist) CursorOnModeLine() bool {
return true
}
func (hl *histlist) Len() int {
return len(hl.shown)
}
func (hl *histlist) Show(i int) (string, ui.Styled) {
return fmt.Sprintf("%d", hl.index[i]), ui.Unstyled(hl.shown[i])
}
func (hl *histlist) Filter(filter string) int {
hl.shown = nil
hl.index = nil
dedup := hl.dedup
if hl.caseInsensitive {
filter = strings.ToLower(filter)
}
for i, entry := range hl.all {
fentry := entry
if hl.caseInsensitive {
fentry = strings.ToLower(entry)
}
if (!dedup || hl.last[entry] == i) && strings.Contains(fentry, filter) {
hl.index = append(hl.index, i)
hl.shown = append(hl.shown, entry)
}
}
// TODO: Maintain old selection
return len(hl.shown) - 1
}
// Editor interface.
func (hl *histlist) Accept(i int, ed eddefs.Editor) {
line := hl.shown[i]
buffer, _ := ed.Buffer()
if len(buffer) > 0 {
line = "\n" + line
}
ed.InsertAtDot(line)
}
func (hl *histlist) start(ed eddefs.Editor, fuser *Fuser, binding eddefs.BindingMap) {
cmds, err := getCmds(fuser)
if err != nil {
ed.Notify("%v", err)
return
}
*hl = *newHistlist(cmds)
ed.SetModeListing(binding, hl)
}
func getCmds(fuser *Fuser) ([]string, error) {
if fuser == nil {
return nil, errStoreOffline
}
return fuser.AllCmds()
}
func (hl *histlist) toggleDedup(ed eddefs.Editor) {
hl.dedup = !hl.dedup
ed.RefreshListing()
}
func (hl *histlist) toggleCaseSensitivity(ed eddefs.Editor) {
hl.caseInsensitive = !hl.caseInsensitive
ed.RefreshListing()
}