Repository navigation
Expand file tree
/
Copy pathinput.go
More file actions
342 lines (321 loc) · 8.15 KB
/
Copy pathinput.go
File metadata and controls
342 lines (321 loc) · 8.15 KB
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
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)
package main
import (
"io"
"os"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
)
type keyKind int
const (
keyUnknown keyKind = iota
keyRune // a printable rune, in key.r
keyEnter
keyBackspace
keyTab
keyShiftTab
keyEsc
keyUp
keyDown
keyLeft
keyRight
keyHome
keyEnd
keyPageUp
keyPageDown
keyInsert
keyDelete
keyCtrlC
keyCtrlS
keyCtrlX
keyCtrlU
keyCtrlF
keyCtrlR
)
type key struct {
kind keyKind
r rune // valid when kind == keyRune
ctrl bool // a Ctrl modifier rode along with a navigation key
}
// reader decodes terminal input into keys. A background goroutine reads the
// input source and feeds its bytes onto a channel; the decoder pulls from the
// channel one byte at a time. This keeps the decoder portable — distinguishing
// a bare Escape from an arrow's escape sequence is a channel receive with a
// timeout (see waitByte), not a platform-specific readiness poll. peek holds a
// single byte staged by waitByte but not yet consumed.
type reader struct {
bytes chan byte
peek int // a pushed-back byte, or -1 when none
}
func newReader() *reader { return newReaderFrom(os.Stdin) }
// newReaderFrom starts a reader over an arbitrary source (os.Stdin in normal
// use; a pipe in tests). The pump goroutine lives until the source reaches EOF,
// at which point it closes the channel and readByte reports end of input.
func newReaderFrom(in io.Reader) *reader {
rd := &reader{bytes: make(chan byte, 1024), peek: -1}
go rd.pump(in)
return rd
}
func (rd *reader) pump(in io.Reader) {
var buf [256]byte
for {
n, err := in.Read(buf[:])
for _, b := range buf[:n] {
rd.bytes <- b
}
if err != nil {
close(rd.bytes)
return
}
}
}
func (rd *reader) readByte() (byte, bool) {
if rd.peek >= 0 {
b := byte(rd.peek)
rd.peek = -1
return b, true
}
b, ok := <-rd.bytes
return b, ok
}
// peekByte returns the byte waitByte staged, without consuming it, so readKey
// can look at the character after an ESC before deciding to parse a sequence.
func (rd *reader) peekByte() (byte, bool) {
if rd.peek >= 0 {
return byte(rd.peek), true
}
return 0, false
}
// escTimeout is how long readKey waits after a lone ESC for the rest of an
// escape sequence before deciding the ESC was the Escape key itself. A terminal
// sends an arrow's bytes back-to-back, so a gap this long means a real Escape.
const escTimeout = 50 * time.Millisecond
// waitByte reports whether a byte is available within d, staging it in peek if
// so. It is how readKey distinguishes a bare Escape from the lead byte of an
// arrow sequence that arrived a moment later.
func (rd *reader) waitByte(d time.Duration) bool {
if rd.peek >= 0 {
return true
}
select {
case b, ok := <-rd.bytes:
if !ok {
return false
}
rd.peek = int(b)
return true
case <-time.After(d):
return false
}
}
// readKey returns the next decoded key. ok is false at end of input.
func (rd *reader) readKey() (key, bool) {
b, ok := rd.readByte()
if !ok {
return key{}, false
}
switch {
case b == 0x1b: // ESC: sequence lead-in, or the bare Escape key
if rd.waitByte(escTimeout) {
if pb, _ := rd.peekByte(); pb == '[' {
rd.readByte()
return rd.readCSI(), true
}
if pb, _ := rd.peekByte(); pb == 'O' { // application-cursor arrows
rd.readByte()
return rd.readSS3(), true
}
}
return key{kind: keyEsc}, true
case b == '\r', b == '\n':
return key{kind: keyEnter}, true
case b == 0x7f, b == 0x08:
return key{kind: keyBackspace}, true
case b == '\t':
return key{kind: keyTab}, true
case b == 0x03:
return key{kind: keyCtrlC}, true
case b == 0x13:
return key{kind: keyCtrlS}, true
case b == 0x18:
return key{kind: keyCtrlX}, true
case b == 0x15:
return key{kind: keyCtrlU}, true
case b == 0x06:
return key{kind: keyCtrlF}, true
case b == 0x12:
return key{kind: keyCtrlR}, true
case b < 0x20:
return key{kind: keyUnknown}, true
case b < 0x80:
return key{kind: keyRune, r: rune(b)}, true
default:
return rd.readUTF8(b), true
}
}
// readCSI parses the body of an ESC [ … sequence (the leading ESC [ already
// consumed): parameter bytes terminated by a final byte in 0x40–0x7e.
func (rd *reader) readCSI() key {
var params []byte
for {
b, ok := rd.readByte()
if !ok {
return key{kind: keyEsc}
}
if b >= 0x40 && b <= 0x7e {
return classifyCSI(params, b)
}
params = append(params, b)
}
}
// classifyCSI maps a parsed CSI sequence to a key. The modifier parameter is
// 1 + a bitmask (Shift 1, Alt 2, Ctrl 4), so a "5" second parameter means Ctrl.
func classifyCSI(params []byte, final byte) key {
nums := parseParams(params)
ctrl := false
if len(nums) >= 2 {
ctrl = (nums[1]-1)&4 != 0
}
switch final {
case 'A':
return key{kind: keyUp, ctrl: ctrl}
case 'B':
return key{kind: keyDown, ctrl: ctrl}
case 'C':
return key{kind: keyRight, ctrl: ctrl}
case 'D':
return key{kind: keyLeft, ctrl: ctrl}
case 'H':
return key{kind: keyHome, ctrl: ctrl}
case 'F':
return key{kind: keyEnd, ctrl: ctrl}
case 'Z': // CSI Z — Shift-Tab (back-tab)
return key{kind: keyShiftTab}
case '~':
n := 0
if len(nums) >= 1 {
n = nums[0]
}
switch n {
case 2:
return key{kind: keyInsert, ctrl: ctrl}
case 3:
return key{kind: keyDelete, ctrl: ctrl}
case 5:
return key{kind: keyPageUp, ctrl: ctrl}
case 6:
return key{kind: keyPageDown, ctrl: ctrl}
}
}
return key{kind: keyUnknown}
}
// readSS3 parses ESC O <letter>, the application-cursor-mode arrow form some
// terminals send instead of ESC [ <letter>.
func (rd *reader) readSS3() key {
b, ok := rd.readByte()
if !ok {
return key{kind: keyEsc}
}
switch b {
case 'A':
return key{kind: keyUp}
case 'B':
return key{kind: keyDown}
case 'C':
return key{kind: keyRight}
case 'D':
return key{kind: keyLeft}
case 'H':
return key{kind: keyHome}
case 'F':
return key{kind: keyEnd}
}
return key{kind: keyUnknown}
}
func parseParams(p []byte) []int {
if len(p) == 0 {
return nil
}
parts := strings.Split(string(p), ";")
nums := make([]int, len(parts))
for i, s := range parts {
nums[i], _ = strconv.Atoi(s)
}
return nums
}
// readUTF8 gathers the continuation bytes of a multi-byte rune whose lead byte
// has already been read.
func (rd *reader) readUTF8(lead byte) key {
var n int
switch {
case lead&0xe0 == 0xc0:
n = 2
case lead&0xf0 == 0xe0:
n = 3
case lead&0xf8 == 0xf0:
n = 4
default:
return key{kind: keyUnknown} // stray continuation byte
}
bytes := make([]byte, 1, 4)
bytes[0] = lead
for len(bytes) < n {
b, ok := rd.readByte()
if !ok {
break
}
bytes = append(bytes, b)
}
r, _ := utf8.DecodeRune(bytes)
if r == utf8.RuneError {
return key{kind: keyUnknown}
}
return key{kind: keyRune, r: r}
}
// readLine reads a plain line for a prompt (e.g. the filename ask), echoing as
// it goes. ok is false when cancelled with Ctrl+C or at end of input.
func readLine(rd *reader, prompt string) (string, bool) {
line, end := readLineStopping(rd, prompt, nil)
return line, end == keyEnter
}
// readLineStopping is readLine with extra terminators: any key kind in stop ends
// the line where Enter would, keeping what was typed, and the kind that ended it
// is returned — keyEnter for an ordinary line, keyCtrlC for a cancel, keyUnknown
// at end of input. An append reads its block through here so Ctrl+S and Ctrl+X
// can end it; the plain prompts pass no stop keys, which leaves those chords
// swallowed there as every other unhandled key is.
func readLineStopping(rd *reader, prompt string, stop []keyKind) (string, keyKind) {
os.Stdout.WriteString(prompt)
var line []rune
for {
k, ok := rd.readKey()
if !ok {
os.Stdout.WriteString("\r\n")
return "", keyUnknown
}
if slices.Contains(stop, k.kind) {
os.Stdout.WriteString("\r\n")
return string(line), k.kind
}
switch k.kind {
case keyCtrlC:
os.Stdout.WriteString("\r\n")
return "", keyCtrlC
case keyEnter:
os.Stdout.WriteString("\r\n")
return string(line), keyEnter
case keyBackspace:
if len(line) > 0 {
line = line[:len(line)-1]
os.Stdout.WriteString("\b \b")
}
case keyRune:
line = append(line, k.r)
os.Stdout.WriteString(string(k.r))
}
}
}