-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
526 lines (439 loc) · 10.2 KB
/
main.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"github.com/docopt/docopt-go"
"github.com/mattn/go-isatty"
"github.com/mgutz/ansi"
"github.com/nsf/termbox-go"
"github.com/reconquest/executil-go"
"github.com/reconquest/karma-go"
)
var (
release = "dev"
version = "dev-0-000000"
)
const (
defaultRegexpCursor = `[!-~]+`
defaultRegexpCandidate = `[^<> ]+`
)
var usage = `tmux-autocomplete - provides autocomplete interface for pane contents.
Usage:
tmux-autocomplete -h | --help
tmux-autocomplete [options]
tmux-autocomplete [options] -W <pane> <cursor-x> <cursor-y>
Options:
-c --regexp-cursor <regexp> Identifier regexp to match.
[default: ` + defaultRegexpCursor + `]
-r --regexp-candidate <regexp> Candidate regexp to match.
[default: ` + defaultRegexpCandidate + `]
-n --no-prefix Don't use identifier under cursor as prefix.
-e --exec <program> Exec specified program and pass specified candidate as argument.
--theme <name> Name of theme to use. [default: light]
--theme-path <dir> Path to directories with themes. Default:
* ` + defaultSystemThemePath + `
* ` + defaultUserThemePath + `
You can specify multiple directories using : separator.
--debug <file> Print debug messages into specified file.
-v --version Print version.
-h --help Show this help.
`
var debug = log.New(ioutil.Discard, "", 0)
func main() {
args, err := docopt.Parse(
usage,
nil,
true,
"tmux-autocomplete "+version,
false,
)
if err != nil {
panic(err)
}
if path, ok := args["--debug"].(string); ok {
out, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer out.Close()
debug = log.New(out, "", log.Lshortfile|log.Ltime)
}
themePath, ok := args["--theme-path"].(string)
if !ok {
themePath = defaultThemePath
}
theme, err := LoadTheme(themePath, args["--theme"].(string))
if err != nil {
fatalln(
karma.
Describe("path", themePath).
Describe("theme", args["--theme"].(string)).
Format(err, "unable to load theme"),
2,
)
}
tmux := &Tmux{}
if !args["-W"].(bool) {
if isatty.IsTerminal(os.Stdin.Fd()) {
printIntroductionMessage()
os.Exit(1)
}
err := start(args, themePath, tmux)
if err != nil {
fatalln(
karma.Format(
err,
"unable to start tmux-autocomplete",
),
3,
)
}
return
}
var (
cursorX int
cursorY int
program, _ = args["--exec"].(string)
withPrefix = !args["--no-prefix"].(bool)
)
_, err = fmt.Sscan(args["<cursor-x>"].(string), &cursorX)
if err != nil {
log.Fatalln(err)
}
_, err = fmt.Sscan(args["<cursor-y>"].(string), &cursorY)
if err != nil {
log.Fatalln(err)
}
pane, err := CapturePane(tmux, args["<pane>"].(string), "-eJ")
if err != nil {
log.Fatalln(err)
}
lines := pane.GetPrintable()
x, y := pane.GetBufferXY(lines, cursorX, cursorY)
report.CursorX = cursorX
report.CursorY = cursorY
report.Pane = pane
report.Lines = lines
defer func() {
writeReport(recover())
}()
var identifier *Identifier
if withPrefix {
identifier, err = getIdentifierToComplete(args["--regexp-cursor"].(string), lines, x, y)
if err != nil {
log.Fatalln(err)
}
if identifier == nil {
return
}
}
moveCursor(cursorX, cursorY)
candidates, err := getCompletionCandidates(
args["--regexp-candidate"].(string),
lines,
identifier,
)
if err != nil {
log.Fatalln(err)
}
if len(candidates) == 0 {
return
}
candidates = getUniqueCandidates(candidates)
if identifier == nil {
identifier = candidates[len(candidates)-1].Identifier
}
selectDefaultCandidate(candidates, identifier.X, identifier.Y)
if len(candidates) == 1 {
useCurrentCandidate(
tmux,
pane,
identifier,
candidates,
program,
withPrefix,
)
return
}
err = termbox.Init()
if err != nil {
log.Fatalln(err)
}
for {
renderPane(pane, theme)
renderIdentifier(lines, pane, theme, identifier)
renderCandidates(lines, pane, theme, candidates)
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
switch {
case ev.Ch == 'k':
fallthrough
case ev.Key == termbox.KeyArrowUp:
selectNextCandidate(candidates, 0, -1)
case ev.Ch == 'j':
fallthrough
case ev.Key == termbox.KeyArrowDown:
selectNextCandidate(candidates, 0, 1)
case ev.Ch == 'h':
fallthrough
case ev.Key == termbox.KeyArrowLeft:
selectNextCandidate(candidates, -1, 0)
case ev.Ch == 'l':
fallthrough
case ev.Key == termbox.KeyArrowRight:
selectNextCandidate(candidates, 1, 0)
case ev.Key == termbox.KeyEnter:
useCurrentCandidate(
tmux,
pane,
identifier,
candidates,
program,
withPrefix,
)
return
case ev.Key == termbox.KeyCtrlC:
return
}
case termbox.EventError:
log.Fatalln(ev.Err)
}
}
}
func fatalln(err interface{}, exitcode int) {
fmt.Println(err)
log.Println(err)
os.Exit(exitcode)
}
func start(args map[string]interface{}, themePath string, tmux *Tmux) error {
var (
pane string
cursorX string
cursorY string
)
err := tmux.Eval(
map[string]interface{}{
"pane_id": &pane,
"cursor_x": &cursorX,
"cursor_y": &cursorY,
},
)
if err != nil {
return karma.Format(
err,
"unable to get current pane/cursor",
)
}
logsPipe, err := mkfifo()
if err != nil {
return karma.Format(
err,
"unable to make fifo",
)
}
defer os.Remove(logsPipe)
cmd := []string{os.Args[0]}
for flag, value := range args {
switch flag {
case "--theme-path":
cmd = append(cmd, flag, fmt.Sprintf("%q", themePath))
case "--regexp":
cmd = append(cmd, flag, fmt.Sprintf("%q", value))
case "--debug":
if value != nil {
cmd = append(cmd, flag, fmt.Sprintf("%q", value))
}
default:
switch typed := value.(type) {
case string:
cmd = append(cmd, flag, fmt.Sprintf("%q", typed))
case bool:
if typed {
cmd = append(cmd, flag)
}
case nil:
//
default:
panic(
fmt.Sprintf(
"unexpected type of flag %s: %#v (%T)",
flag, value, value,
),
)
}
}
}
cmd = append(cmd, pane, cursorX, cursorY, "-W", "2>"+logsPipe)
err = tmux.NewWindow(cmd...)
if err != nil {
return karma.
Format(
err,
"unable to create new tmux window",
)
}
file, err := os.Open(logsPipe)
if err != nil {
return karma.Format(
err,
"unable to open logs file",
)
}
// Fd() does side effect - set nonblocking mode
// set nonblocking mode
// https://github.com/golang/go/issues/24164#issuecomment-370097226
file.Fd()
logs, err := ioutil.ReadAll(file)
if err != nil {
return karma.Format(
err,
"unable to read logs fifo",
)
}
if len(logs) > 0 {
return errors.New(string(logs))
}
return nil
}
func renderPane(pane *Pane, theme *Theme) {
moveCursor(0, 0)
fmt.Print(ansi.ColorCode(theme.Fog.Text))
text := reEscapeSequence.ReplaceAllStringFunc(
pane.String(),
func(sequence string) string {
return decolorize(sequence, theme)
},
)
fmt.Print(text)
}
func decolorize(sequence string, theme *Theme) string {
var (
matches = reEscapeSequence.FindStringSubmatch(sequence)
code = matches[1]
)
switch code {
// 49 means reset background color to default,
// we remove background color and set dim color for foreground
case "49":
return ansi.DefaultBG + ansi.ColorCode(theme.Fog.Text)
// 39 means reset foreground color to default,
// 0 means reset all style to default,
// we reset style and set dim color for foreground
case "0", "39":
return ansi.Reset + ansi.ColorCode(theme.Fog.Text)
// 1 means bold,
// we remove bold
case "1":
return ""
// 7 means reverse,
// we set dim background color
case "7":
return ansi.ColorCode(theme.Fog.Background)
default:
// all single-number codes,
// we remove
if len(code) == 1 {
return ""
}
// all foreground theme,
// we replace with dim foreground color
if code[0] == '3' || code[0] == '9' {
return ansi.ColorCode(theme.Fog.Text)
}
// all background theme,
// we replace with dim background color
if code[0] == '4' || code[0] == '1' {
return ansi.ColorCode(theme.Fog.Background)
}
}
return ansi.Reset
}
func renderIdentifier(
lines []string,
pane *Pane,
theme *Theme,
identifier *Identifier,
) {
moveCursor(pane.GetScreenXY(lines, identifier.X, identifier.Y))
fmt.Print(ansi.ColorFunc(theme.Identifier)(identifier.Value))
}
func renderCandidates(
lines []string,
pane *Pane,
theme *Theme,
candidates []*Candidate,
) {
// first we need to draw existing candidates
for _, candidate := range candidates {
if !candidate.Selected {
renderCandidate(lines, pane, theme, candidate)
}
}
// and only then we draw selected one
// otherwise we can have incorrect color for selected candidate (it will
// partially look like 'normal' candidate)
for _, candidate := range candidates {
if candidate.Selected {
renderCandidate(lines, pane, theme, candidate)
}
}
}
func renderCandidate(
lines []string,
pane *Pane,
theme *Theme,
candidate *Candidate,
) {
x := candidate.X
y := candidate.Y
moveCursor(pane.GetScreenXY(lines, x, y))
var color string
switch {
case candidate.Selected:
color = theme.Candidate.Selected
// case candidate.Parent != "":
// color = theme.Candidate.Nested
default:
color = theme.Candidate.Normal
}
fmt.Print(ansi.ColorFunc(color)(candidate.Value))
}
func useCurrentCandidate(
tmux *Tmux,
pane *Pane,
identifier *Identifier,
candidates []*Candidate,
program string,
withPrefix bool,
) {
selected := getSelectedCandidate(candidates)
if selected == nil {
return
}
var text string
if program != "" {
// if we want to run program then we don't need to remove existing
// identifier prefix
text = selected.Value
} else {
text = selected.Value
if withPrefix {
text = string([]rune(text)[identifier.Length():])
}
}
if program != "" {
_, _, err := executil.Run(exec.Command(program, text))
if err != nil {
log.Fatalln(err)
}
} else {
err := tmux.Paste(text, "-t", pane.ID)
if err != nil {
log.Fatalln(err)
}
}
}