-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
488 lines (438 loc) · 12.2 KB
/
reader.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
package ns
import (
"fmt"
"io"
"os"
"os/exec"
"regexp"
"runtime/debug"
"strings"
"sync"
"syscall"
"golang.org/x/term"
)
type ProcessingCode int8
var EscapeFinder = regexp.MustCompile("\033\\[[^m]+m")
const (
CodeContinue ProcessingCode = iota
CodeComplete
CodeCancel
CodeTerminate
)
type LineReader struct {
lastSearchText []rune
nilShell *NilShell
isReverseSearch bool
prompt string
promptLength int
completer Completer
bufferOffset int
resizeChan chan os.Signal
buffer []rune
lock *sync.Mutex
winWidth int
winHeight int
cursorRow int
}
var reverseSearchPrompt = "(reverse-i- search: `"
// NewLineReader creates a new LineReader object
func NewLineReader(completer Completer, resizeChan chan os.Signal, nilShell *NilShell) *LineReader {
lr := &LineReader{
completer: completer,
resizeChan: resizeChan,
buffer: []rune{},
lock: &sync.Mutex{},
nilShell: nilShell,
}
go lr.resizeWatcher()
lr.resizeWindow(false)
return lr
}
// Read will read a single command from the command line and can be interrupted by pressing <enter>, <ctrl+c>, or <ctrl+d>.
// Read responds to changes in the terminal window size.
func (lr *LineReader) Read() (string, bool, error) {
fd := int(os.Stdin.Fd())
preState, err := term.MakeRaw(fd)
if err != nil {
return "", false, err
}
lr.nilShell.preState = preState
// Try our best not to leave the terminal in raw mode
defer func() {
err := recover()
term.Restore(fd, lr.nilShell.preState)
if err != nil {
fmt.Printf("Caught panic before exiting\n%v\n", err)
if lr.nilShell.Debug {
fmt.Println(string(debug.Stack()))
}
}
if err != nil {
os.Exit(1)
}
}()
cursorRow, _ := getCursorPos()
hideCursor()
setCursorPos(cursorRow, 1)
lr.cursorRow = cursorRow
lr.bufferOffset = 0
lr.buffer = []rune{}
fmt.Printf("%s", lr.nilShell.Prompt)
lr.promptLength = len([]rune(EscapeFinder.ReplaceAllString(lr.nilShell.Prompt, "")))
showCursor()
iBuf := make([]byte, 20)
for {
n, err := os.Stdin.Read(iBuf)
if err != nil {
return "", false, err
}
iString := string(iBuf[:n])
code := lr.processInput(iString, lr.nilShell)
switch code {
case CodeComplete:
lr.isReverseSearch = false
return string(lr.buffer), false, nil
case CodeCancel:
return "", false, nil
case CodeTerminate:
lr.resizeChan <- syscall.SIGTERM
return "", true, nil
}
}
}
// resizeWatcher waits for input on the resize channel and resizes accordingly. when the channel receives a SIGTERM the thread exists.
// the SIGTERM originates internally, not from outside the process.
func (lr *LineReader) resizeWatcher() {
for {
sig := <-lr.resizeChan
if sig == syscall.SIGTERM {
return
}
lr.resizeWindow(true)
}
}
// processInput executes one iteration of input processing which would occur in the interactive read loop
func (lr *LineReader) processInput(input string, n *NilShell) ProcessingCode {
lr.lock.Lock()
defer lr.lock.Unlock()
switch input {
case KEY_CTRL_R:
lr.isReverseSearch = true
lr.renderComplete()
case KEY_CTRL_T:
if err := lr.openInEditor(); err != nil {
fmt.Fprintf(os.Stderr, "\r\n%s\n", err)
// Carriage Return (\r) to return the cursor to the left hand side (like a typewriter)
// Line Feed (\n) to bring us to a new line
// Print the error, and a final Line Feed to ensure the next prompt is up on a new line
return CodeCancel // Return CodeCancel to generate a new prompt.
}
case KEY_UP_ARROW:
if n.History.Any() {
cmd := n.History.Older()
lr.setText([]rune(cmd))
}
case KEY_DOWN_ARROW:
if n.History.Any() {
cmd := n.History.Newer()
lr.setText([]rune(cmd))
}
case KEY_LEFT_ARROW:
if lr.bufferOffset > 0 {
lr.bufferOffset--
}
lr.setCursorPos()
case KEY_RIGHT_ARROW:
if lr.bufferOffset < len(lr.buffer) {
lr.bufferOffset++
}
lr.setCursorPos()
case KEY_HOME:
lr.bufferOffset = 0
lr.setCursorPos()
case KEY_END:
lr.bufferOffset = len(lr.buffer)
lr.setCursorPos()
case KEY_ENTER:
if lr.isReverseSearch {
buffer := make([]rune, len(lr.lastSearchText))
copy(buffer, lr.lastSearchText)
lr.buffer = buffer
}
fmt.Printf("\n")
return CodeComplete
case KEY_CTRL_C:
fmt.Printf("\n")
return CodeCancel
case KEY_CTRL_D:
fmt.Printf("\r\n")
return CodeTerminate
case KEY_CTRL_L:
clear()
// Tell LineReader that we are back at the first row,
// since it keeps track of the cursor itself.
lr.cursorRow = 1
lr.renderComplete()
case KEY_DEL:
lr.deleteAtCurrentPos()
case KEY_TAB:
if lr.isReverseSearch {
buffer := make([]rune, len(lr.lastSearchText))
copy(buffer, lr.lastSearchText)
lr.buffer = buffer
lr.isReverseSearch = false
lr.bufferOffset = len(lr.buffer)
lr.setCursorPos()
lr.renderComplete()
} else {
autoComplete := lr.completer(string(lr.buffer[:lr.bufferOffset]), string(lr.buffer[lr.bufferOffset:]), string(lr.buffer))
if autoComplete != nil {
if len(autoComplete) == 1 {
ac := autoComplete[0]
lr.completeText([]rune(ac.Name))
} else if len(autoComplete) > 1 && len(autoComplete) <= n.AutoCompleteLimit {
lr.displayAutocomplete(autoComplete, n)
} else if len(autoComplete) > n.AutoCompleteLimit {
lr.displayTooManyAutocomplete(autoComplete, n)
}
}
}
case KEY_BACKSPACE:
if lr.bufferOffset > 0 {
lr.bufferOffset--
lr.deleteAtCurrentPos()
}
default:
lr.insertText([]rune(input))
}
return CodeContinue
}
// displayTooManyAutocomplete displays the too many autocomplete suggestions message
func (lr *LineReader) displayTooManyAutocomplete(autoComplete []*AutoComplete, ns *NilShell) {
y, _ := getCursorPos()
fmt.Printf("\r\n")
y++
fmt.Printf("%s%d suggestions, too many to display...%s", ns.AutoCompleteTooMuchStyle, len(autoComplete), CODE_RESET)
y++
fmt.Printf("\r\n")
if y > lr.winHeight {
y = lr.winHeight
}
lr.cursorRow = y
lr.renderComplete()
}
// displayAutocomplete displays the autocomplete suggestions
func (lr *LineReader) displayAutocomplete(autoComplete []*AutoComplete, ns *NilShell) {
y, _ := getCursorPos()
fmt.Printf("\r\n%s", ns.AutoCompleteSuggestStyle)
y++
total := 0
for _, ac := range autoComplete {
text := ac.Name
if len(text) > 12 {
text = text[:12] + "..."
}
total += 18
if total > lr.winWidth {
y++
fmt.Printf("\r\n")
total = 18
}
fmt.Printf("%-20s", text)
}
y++
fmt.Printf("%s\n\r", CODE_RESET)
if y > lr.winHeight {
y = lr.winHeight
}
lr.cursorRow = y
lr.renderComplete()
}
// setText sets the current input text
func (lr *LineReader) setText(input []rune) {
lr.buffer = input
lr.bufferOffset = len(lr.buffer)
lr.renderComplete()
}
// insertText inserts text at the current cursor position
func (lr *LineReader) insertText(input []rune) {
runeBuffer := []rune{}
runeBuffer = append(runeBuffer, lr.buffer[:lr.bufferOffset]...)
runeBuffer = append(runeBuffer, input...)
runeBuffer = append(runeBuffer, lr.buffer[lr.bufferOffset:]...)
lr.buffer = runeBuffer
newBufferOffset := lr.bufferOffset + len(input)
hideCursor()
lr.renderFromCursor()
lr.bufferOffset = newBufferOffset
lr.setCursorPos()
showCursor()
}
// completeText performs an autocomplete operation
func (lr *LineReader) completeText(input []rune) {
// hunt back to the previous either space, or beginning of the text from the current cursor position
inputStr := string(input)
for i := lr.bufferOffset - 1; i >= 0; i-- {
if lr.buffer[i] == ' ' || i == 0 {
j := i
if lr.buffer[i] == ' ' {
j++
}
strPrefix := string(lr.buffer[j:lr.bufferOffset])
if !strings.HasPrefix(inputStr, strPrefix) {
return
}
runePrefix := []rune(strPrefix)
lr.insertText(input[len(runePrefix):])
}
}
}
// deleteAtCurrentPos deletes a single character at the current cursor position
func (lr *LineReader) deleteAtCurrentPos() {
if lr.bufferOffset < len(lr.buffer) {
runeBuffer := []rune{}
runeBuffer = append(runeBuffer, lr.buffer[:lr.bufferOffset]...)
runeBuffer = append(runeBuffer, lr.buffer[lr.bufferOffset+1:]...)
lr.buffer = runeBuffer
hideCursor()
lr.renderFromCursor()
lr.setCursorPos()
showCursor()
}
}
// renderFromCursor renders the input line starting from the current cursor position
func (lr *LineReader) renderFromCursor() {
if lr.isReverseSearch {
lr.renderComplete()
} else {
lr.setCursorPos()
fmt.Printf("%s", string(lr.buffer[lr.bufferOffset:]))
lr.renderEraseForward(true)
}
}
// renderEraseForward renders the erase forward pattern so that input does not "drag" when deletion occurs
func (lr *LineReader) renderEraseForward(justOne bool) {
var totalOffset int
if lr.isReverseSearch {
totalOffset = len(reverseSearchPrompt) + 4 + len(lr.buffer) + len(lr.lastSearchText)
} else {
totalOffset = lr.promptLength + len(lr.buffer)
}
remainder := lr.winWidth - (totalOffset % lr.winWidth)
if remainder > 0 {
if justOne {
remainder = 1
}
remBuf := make([]byte, remainder)
for i := 0; i < remainder; i++ {
remBuf[i] = ' '
}
os.Stdout.Write(remBuf)
}
}
// renderComplete renders the complete input text regardless of the cursor position
func (lr *LineReader) renderComplete() {
hideCursor()
if lr.isReverseSearch {
lr.lastSearchText = []rune(lr.nilShell.History.FindMostRecentMatch(string(lr.buffer)))
setCursorPos(lr.cursorRow, 1)
fmt.Printf("%s%s`): %s", reverseSearchPrompt, string(lr.buffer), string(lr.lastSearchText))
lr.renderEraseForward(false)
lr.setCursorPos()
} else {
setCursorPos(lr.cursorRow, 1)
fmt.Printf("%s", lr.nilShell.Prompt)
fmt.Printf("%s", string(lr.buffer))
lr.renderEraseForward(false)
lr.setCursorPos()
}
showCursor()
}
// resizeWindow re-renders according to the window size
func (lr *LineReader) resizeWindow(render bool) {
lr.lock.Lock()
defer lr.lock.Unlock()
lr.winHeight, lr.winWidth = getWindowDimensions()
if render {
lr.renderComplete()
}
}
// setCursorPos sets the current cursor position based on the linear offset in the command input
func (lr *LineReader) setCursorPos() {
// Determine the linear cursor position, including the prompt
var promptOffset int
if lr.isReverseSearch {
promptOffset = len(reverseSearchPrompt)
} else {
promptOffset = lr.promptLength
}
linearCursorPos := promptOffset + lr.bufferOffset
curCursorRow := lr.cursorRow + int(linearCursorPos/lr.winWidth)
curCursorCol := (linearCursorPos % lr.winWidth) + 1
// deal with the end of terminal (vertical situation)
if curCursorRow > lr.winHeight {
lr.cursorRow -= (curCursorRow - lr.winHeight)
curCursorRow = lr.winHeight
}
setCursorPos(curCursorRow, curCursorCol)
}
// Reset the LineReader buffer and return its contents.
func (lr *LineReader) reset() []rune {
ret := make([]rune, len(lr.buffer))
copy(ret, lr.buffer)
lr.buffer = lr.buffer[:0]
lr.bufferOffset = 0
return ret
}
// openInEditor takes the contents of the LineReader buffer and stores it in a temp file, which is
// then opened in the user's $EDITOR. After the editor is closed the contents of the file are put
// back into the LineReader buffer.
func (lr *LineReader) openInEditor() (err error) {
// Create a temp file to store the buffer in.
tmpFile, err := os.CreateTemp("", "ns-*")
if err != nil {
return
}
defer os.Remove(tmpFile.Name())
// Get the user's editor, and open the file in it.
editorName := os.Getenv("EDITOR")
if editorName == "" {
editorName = "vi"
}
// Setup the exec
editor := exec.Command(editorName, tmpFile.Name())
editor.Stdin = os.Stdin
editor.Stdout = os.Stdout
editor.Stderr = os.Stderr
// Clear the buffer and return it.
currentBuffer := lr.reset()
tmpFile.WriteString(string(currentBuffer))
tmpFile.Close()
err = editor.Run() // Run the editor
if err != nil {
return
}
// Open that temp file again, and put its contents back into the buffer.
tmpFile, err = os.Open(tmpFile.Name())
if err != nil {
return
}
defer tmpFile.Close()
contents, err := io.ReadAll(tmpFile)
if err != nil {
return
}
contentsAsRunes := convertAndTrim(contents)
lr.buffer = contentsAsRunes
lr.bufferOffset = len(contentsAsRunes)
lr.renderComplete()
return
}
// convertAndTrim returns a rune slice for a given byte slice, minus a final line feed character.
func convertAndTrim(b []byte) []rune {
s := string(b)
if len(s) > 0 && s[len(s)-1] == '\n' {
s = s[:len(s)-1]
}
return []rune(s)
}