forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt.go
511 lines (452 loc) · 12.4 KB
/
prompt.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
package prompt
import (
"bytes"
"fmt"
"net"
"os"
"time"
"github.com/tarantool/go-prompt/internal/debug"
)
// Executor is called when user input something text.
type Executor func(string)
// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker
// function criteria:
// - immediate exit (if breakline is false) without executor called
// - exit after typing <return> (meaning breakline is true), and the executor is called first,
// before exit.
// Exit means exit go-prompt (not the overall Go program).
type ExitChecker func(in string, breakline bool) bool
// Completer should return the suggest item from Document.
type Completer func(Document) []Suggest
// location indicates the relative location of the cursor on the screen.
type location struct {
row int
col int
}
// renderCtx describes render context.
type renderCtx struct {
cmd *Buffer
cursor location
endCursor location
completion *CompletionManager
prefixColor Color
prefix string
renderCompletion bool
renderEvent int
}
// fillCtx fills render context.
func (p *Prompt) fillCtx(renderEvent int) renderCtx {
cmd, _ := p.getCmdToRender()
prefix := p.getCurrentPrefix()
ctx := renderCtx{
cmd: cmd,
cursor: p.cursor,
endCursor: p.endCursor,
completion: p.completion,
prefixColor: p.renderer.prefixTextColor,
prefix: prefix,
renderCompletion: !p.inReverseSearchMode() &&
!(p.buf.NewLineCount() > 0),
renderEvent: renderEvent,
}
return ctx
}
// Prompt is core struct of go-prompt.
type Prompt struct {
in ConsoleParser
buf *Buffer
cursor location
endCursor location
renderer *Render
executor Executor
history *History
completion *CompletionManager
keyBindings []KeyBind
ASCIICodeBindings []ASCIICodeBind
keyBindMode KeyBindMode
completionOnDown bool
exitChecker ExitChecker
skipTearDown bool
prefix string
livePrefixCallback func() (prefix string, useLivePrefix bool)
title string
// reverseSearch is a pointer to the current reverse-search state.
// not nil pointer means that reverse-search mode is active.
reverseSearch *reverseSearchState
// isReverseSearchEnabled is true if such option was provided.
isReverseSearchEnabled bool
// isAutoHistoryEnabled is true if automatic writing to the history is enabled.
isAutoHistoryEnabled bool
// notifyConn is a connection used for rendering notifications.
notifyConn net.Conn
}
// Exec is the struct contains user input context.
type Exec struct {
input string
}
// ClearScreen clears the screen.
func (p *Prompt) ClearScreen() {
p.renderer.ClearScreen()
}
// Run starts prompt.
func (p *Prompt) Run() {
p.skipTearDown = false
defer debug.Teardown()
debug.Log("start prompt")
p.setUp()
defer p.tearDown()
if p.completion.showAtStart {
p.completion.Update(*p.buf.Document())
}
p.render(basicRenderEvent)
bufCh := make(chan []byte, 128)
stopReadBufCh := make(chan struct{})
go p.readBuffer(bufCh, stopReadBufCh)
exitCh := make(chan int)
winSizeCh := make(chan *WinSize)
stopHandleSignalCh := make(chan struct{})
go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
for {
select {
case b := <-bufCh:
shouldExit, e := p.feed(b)
// Run onUpdate hook.
p.onInputUpdate()
if shouldExit {
p.render(breakLineRenderEvent)
p.notifyRender()
stopReadBufCh <- struct{}{}
stopHandleSignalCh <- struct{}{}
return
} else if e != nil {
// Stop goroutine to run readBuffer function
stopReadBufCh <- struct{}{}
stopHandleSignalCh <- struct{}{}
// Unset raw mode
// Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
debug.AssertNoError(p.in.TearDown())
p.executor(e.input)
p.render(basicRenderEvent)
p.notifyRender()
if p.exitChecker != nil && p.exitChecker(e.input, true) {
p.skipTearDown = true
return
}
// Set raw mode
debug.AssertNoError(p.in.Setup())
go p.readBuffer(bufCh, stopReadBufCh)
go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
} else {
p.render(basicRenderEvent)
p.notifyRender()
}
case w := <-winSizeCh:
p.onInputUpdate()
p.renderer.UpdateWinSize(w)
p.render(windowResizeRenderEvent)
p.notifyRender()
case code := <-exitCh:
p.onInputUpdate()
p.render(breakLineRenderEvent)
p.notifyRender()
p.tearDown()
os.Exit(code)
default:
time.Sleep(10 * time.Millisecond)
}
}
}
func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
key := GetKey(b)
p.buf.lastKeyStroke = key
// completion
completing := p.completion.Completing()
p.handleCompletionKeyBinding(key, completing)
switch key {
case Enter, ControlJ, ControlM:
execCmd := p.buf.Text()
if p.inReverseSearchMode() {
// Execute last matched command in case of enabled reverse search.
execCmd = p.reverseSearch.matchedCmd
p.disableReverseSearch()
// Render executed command before breakline.
p.render(basicRenderEvent)
}
p.render(breakLineRenderEvent)
p.buf = NewBuffer()
exec = &Exec{input: execCmd}
if exec.input != "" && p.isAutoHistoryEnabled {
p.history.Add(exec.input)
}
case ControlC:
if p.inReverseSearchMode() {
p.disableReverseSearch()
}
p.render(breakLineRenderEvent)
p.buf = NewBuffer()
p.history.Clear()
case Up, ControlP:
if p.inReverseSearchMode() {
p.disableReverseSearch()
} else if !completing { // Don't use p.completion.Completing() because it takes double
// operation when switch to selected=-1.
if newBuf, changed := p.history.Older(p.buf); changed {
p.buf = newBuf
}
}
case Down, ControlN:
if p.inReverseSearchMode() {
p.disableReverseSearch()
} else if !completing { // Don't use p.completion.Completing() because it takes double
// operation when switch to selected=-1.
if newBuf, changed := p.history.Newer(p.buf); changed {
p.buf = newBuf
}
}
case Left, Right, ControlB, ControlF:
if p.inReverseSearchMode() {
p.disableReverseSearch()
}
case ControlD:
if p.buf.Text() == "" {
shouldExit = true
return
}
case ControlR:
if p.inReverseSearchMode() {
p.reverseSearch.reducePrefix()
} else {
p.enableReverseSearch()
}
case NotDefined:
if p.handleASCIICodeBinding(b) {
return
}
p.buf.InsertText(string(b), false, true)
}
shouldExit = p.handleKeyBinding(key)
return
}
func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
switch key {
case Down:
if completing || p.completionOnDown {
p.completion.Next()
}
case Tab, ControlI:
p.completion.Next()
case Up:
if completing {
p.completion.Previous()
}
case BackTab:
p.completion.Previous()
default:
if s, ok := p.completion.GetSelectedSuggestion(); ok {
w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
if w != "" {
p.buf.DeleteBeforeCursor(len([]rune(w)))
}
p.buf.InsertText(s.Text, false, true)
}
p.completion.Reset()
}
}
func (p *Prompt) handleKeyBinding(key Key) bool {
shouldExit := false
for i := range commonKeyBindings {
kb := commonKeyBindings[i]
if kb.Key == key {
kb.Fn(p.buf)
}
}
if p.keyBindMode == EmacsKeyBind {
for i := range emacsKeyBindings {
kb := emacsKeyBindings[i]
if kb.Key == key {
kb.Fn(p.buf)
}
}
}
// Custom key bindings
for i := range p.keyBindings {
kb := p.keyBindings[i]
if kb.Key == key {
kb.Fn(p.buf)
}
}
if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
shouldExit = true
}
return shouldExit
}
func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
checked := false
for _, kb := range p.ASCIICodeBindings {
if bytes.Equal(kb.ASCIICode, b) {
kb.Fn(p.buf)
checked = true
}
}
return checked
}
// Input just returns user input text.
func (p *Prompt) Input() string {
defer debug.Teardown()
debug.Log("start prompt")
p.setUp()
defer p.tearDown()
if p.completion.showAtStart {
p.completion.Update(*p.buf.Document())
}
p.render(basicRenderEvent)
bufCh := make(chan []byte, 128)
stopReadBufCh := make(chan struct{})
go p.readBuffer(bufCh, stopReadBufCh)
for {
select {
case b := <-bufCh:
if shouldExit, e := p.feed(b); shouldExit {
p.render(breakLineRenderEvent)
stopReadBufCh <- struct{}{}
return ""
} else if e != nil {
// Stop goroutine to run readBuffer function
stopReadBufCh <- struct{}{}
return e.input
} else {
p.onInputUpdate()
p.render(basicRenderEvent)
}
default:
time.Sleep(10 * time.Millisecond)
}
}
}
func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
debug.Log("start reading buffer")
for {
select {
case <-stopCh:
debug.Log("stop reading buffer")
return
default:
if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
bufCh <- b
}
}
time.Sleep(10 * time.Millisecond)
}
}
func (p *Prompt) setUp() {
debug.AssertNoError(p.in.Setup())
p.renderer.Setup(p.title)
p.renderer.UpdateWinSize(p.in.GetWinSize())
}
// tearDown restores the terminal state when prompt is turned off.
func (p *Prompt) tearDown() {
if !p.skipTearDown {
debug.AssertNoError(p.in.TearDown())
}
p.renderer.TearDown()
}
// getCmdToRender builds command to render.
// Returns (buffer with command to render, prefix length in bytes).
func (p *Prompt) getCmdToRender() (cmd *Buffer, prefixLen int) {
input := p.buf.Text()
prefix := p.getCurrentPrefix()
cmdBuf := NewBuffer()
cmdBuf.InsertText(prefix, false, true)
if p.inReverseSearchMode() {
cmdBuf.InsertText(p.reverseSearch.matchedCmd, false, true)
} else {
cmdBuf.InsertText(input, false, true)
cmdBuf.setCursorPosition(len(prefix) + p.buf.cursorPosition)
}
return cmdBuf, len(prefix)
}
// getCurrentPrefix returns current prefix.
// If reverse search is enabled, its prefix extracted.
// If live-prefix is enabled, return live-prefix.
func (p *Prompt) getCurrentPrefix() string {
if p.inReverseSearchMode() {
rsPrefixFmt := matchSearchPrefixFmt
if p.reverseSearch.matchedIndex == -1 {
rsPrefixFmt = failSearchPrefixFmt
}
return fmt.Sprintf(rsPrefixFmt, p.buf.Text())
}
if prefix, ok := p.livePrefixCallback(); ok {
return prefix
}
return p.prefix
}
// onInputUpdate does necessary actions at the input update moment.
func (p *Prompt) onInputUpdate() {
p.buf = p.buf.ReplaceTabs(defaultTabWidth)
if p.inReverseSearchMode() {
p.reverseSearch.update(p.buf.Text())
return
}
p.history.SetCurrentCmd(p.buf.Text())
p.completion.Update(*p.buf.Document())
}
// render renders current prompt state to the attached renderer,
// updates current cursor position.
func (p *Prompt) render(event int) {
ctx := p.fillCtx(event)
p.cursor, p.endCursor = p.renderer.Render(ctx)
}
// inReverseSearchMode returns true if the prompt is in reverse-search mode.
func (p *Prompt) inReverseSearchMode() bool {
return p.reverseSearch != nil
}
// enableReverseSearch enables reverse-search mode.
func (p *Prompt) enableReverseSearch() {
if !p.isReverseSearchEnabled || p.inReverseSearchMode() {
return
}
p.buf = NewBuffer()
p.reverseSearch = NewReverseSearch(p.history)
}
// disableReverseSearch disables reverse-search mode,
// sets history pointer to the last matched command.
func (p *Prompt) disableReverseSearch() {
if !p.isReverseSearchEnabled || !p.inReverseSearchMode() {
return
}
matchedIndex := p.reverseSearch.matchedIndex
matchedCmd := p.reverseSearch.matchedCmd
p.history.Clear()
p.buf = NewBuffer()
if matchedIndex != -1 {
p.history.selected = matchedIndex
p.history.SetCurrentCmd(matchedCmd)
p.buf.InsertText(matchedCmd, false, true)
}
p.reverseSearch = nil
}
// pushToHistory takes command, replaces tabs with spaces,
// pushes it to the history.
func (p *Prompt) pushToHistory(cmd string) {
cmdBuf := NewBuffer()
cmdBuf.InsertText(cmd, false, true)
cmdBuf = cmdBuf.ReplaceTabs(defaultTabWidth)
p.history.Add(cmdBuf.Text())
}
// PushToHistory pushes to the history, if auto history is disabled.
func (p *Prompt) PushToHistory(cmd string) error {
if p.isAutoHistoryEnabled {
return fmt.Errorf("external pushes to the history are forbidden, " +
"use `OptionDisableAutoHistory`")
}
p.pushToHistory(cmd)
return nil
}
// notifyAboutRender notifying about rendering if such option was provided.
func (p *Prompt) notifyRender() {
if p.notifyConn != nil {
p.notifyConn.Write([]byte{67})
}
}