This repository has been archived by the owner on Aug 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selecta.go
120 lines (102 loc) · 2.37 KB
/
selecta.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
package main
import (
"fmt"
"github.com/codegangsta/cli"
"github.com/nsf/termbox-go"
"github.com/thomasboyt/go-selecta/selecta"
"io/ioutil"
"os"
"strings"
"unicode"
)
func main() {
app := cli.NewApp()
app.Name = "selecta"
app.Usage = "fuzzy find whatever you want"
app.Flags = []cli.Flag {
cli.StringFlag{"search, s", "", "initial search to fill in"},
}
app.Action = func(c *cli.Context) {
// parse choices
bytes, _ := ioutil.ReadAll(os.Stdin)
choices := strings.Split(string(bytes), "\n")
// create a search
initialSearch := c.String("search")
// set up termbox
err := termbox.Init()
if err != nil {
panic(err)
}
_, height := termbox.Size()
search := selecta.BlankSearch(choices, initialSearch, height - 1)
termbox.SetInputMode(termbox.InputEsc)
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
DrawApp(search)
EventLoop(search)
termbox.Close()
fmt.Fprint(os.Stdout, search.SelectedChoice())
}
app.Run(os.Args)
}
func EventLoop(s *selecta.Search) {
for !s.Done {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyCtrlC:
termbox.Close()
os.Exit(0)
case termbox.KeyBackspace, termbox.KeyBackspace2:
s.Backspace()
case termbox.KeyEnter:
s.Done = true
case termbox.KeyCtrlN:
s.Down()
case termbox.KeyCtrlP:
s.Up()
case termbox.KeyCtrlW:
s.DeleteWord()
default:
char := rune(ev.Ch)
if !unicode.IsControl(char) {
s.AppendQuery(string(char))
} else if ev.Key == termbox.KeySpace {
s.AppendQuery(" ")
}
}
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
DrawApp(s)
}
}
}
// Rendering
func DrawApp(s *selecta.Search) {
WriteLine(0, "> "+s.Query, false)
termbox.SetCursor(2+len(s.Query), 0)
for i, match := range s.Matches {
if i >= s.VisibleChoices {
break
}
choice := match.Value
highlight := false
if s.Index == i {
highlight = true
}
WriteLine(i+1, choice, highlight)
}
termbox.Flush()
}
func WriteLine(row int, str string, highlight bool) {
bgColor := termbox.ColorDefault
width, _ := termbox.Size()
if highlight {
bgColor = termbox.ColorBlack
}
for col := 0; col < width; col++ {
if col < len(str) {
termbox.SetCell(col, row, rune(str[col]), termbox.ColorDefault, bgColor)
} else {
termbox.SetCell(col, row, ' ', termbox.ColorDefault, bgColor)
}
}
}