readline.go 5.09 KB
Newer Older
Patrick Devine's avatar
Patrick Devine committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package readline

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type Prompt struct {
	Prompt         string
	AltPrompt      string
	Placeholder    string
	AltPlaceholder string
	UseAlt         bool
}

Michael Yang's avatar
Michael Yang committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func (p *Prompt) prompt() string {
	if p.UseAlt {
		return p.AltPrompt
	}
	return p.Prompt
}

func (p *Prompt) placeholder() string {
	if p.UseAlt {
		return p.AltPlaceholder
	}
	return p.Placeholder
}

Patrick Devine's avatar
Patrick Devine committed
32
33
type Terminal struct {
	outchan chan rune
34
35
	rawmode bool
	termios any
Patrick Devine's avatar
Patrick Devine committed
36
37
38
39
40
41
}

type Instance struct {
	Prompt   *Prompt
	Terminal *Terminal
	History  *History
42
	Pasting  bool
Patrick Devine's avatar
Patrick Devine committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
}

func New(prompt Prompt) (*Instance, error) {
	term, err := NewTerminal()
	if err != nil {
		return nil, err
	}

	history, err := NewHistory()
	if err != nil {
		return nil, err
	}

	return &Instance{
		Prompt:   &prompt,
		Terminal: term,
		History:  history,
	}, nil
}

func (i *Instance) Readline() (string, error) {
64
	if !i.Terminal.rawmode {
Michael Yang's avatar
Michael Yang committed
65
		fd := os.Stdin.Fd()
66
67
68
69
70
71
72
73
		termios, err := SetRawMode(fd)
		if err != nil {
			return "", err
		}
		i.Terminal.rawmode = true
		i.Terminal.termios = termios
	}

Michael Yang's avatar
Michael Yang committed
74
75
76
	prompt := i.Prompt.prompt()
	if i.Pasting {
		// force alt prompt when pasting
Patrick Devine's avatar
Patrick Devine committed
77
78
		prompt = i.Prompt.AltPrompt
	}
79
	fmt.Print(prompt)
Patrick Devine's avatar
Patrick Devine committed
80

81
	defer func() {
Michael Yang's avatar
Michael Yang committed
82
		fd := os.Stdin.Fd()
Michael Yang's avatar
Michael Yang committed
83
		//nolint:errcheck
84
85
86
		UnsetRawMode(fd, i.Terminal.termios)
		i.Terminal.rawmode = false
	}()
Patrick Devine's avatar
Patrick Devine committed
87
88
89
90
91
92
93
94
95
96

	buf, _ := NewBuffer(i.Prompt)

	var esc bool
	var escex bool
	var metaDel bool

	var currentLineBuf []rune

	for {
97
98
99
		// don't show placeholder when pasting unless we're in multiline mode
		showPlaceholder := !i.Pasting || i.Prompt.UseAlt
		if buf.IsEmpty() && showPlaceholder {
Michael Yang's avatar
Michael Yang committed
100
			ph := i.Prompt.placeholder()
Michael Yang's avatar
lint  
Michael Yang committed
101
			fmt.Print(ColorGrey + ph + CursorLeftN(len(ph)) + ColorDefault)
Patrick Devine's avatar
Patrick Devine committed
102
103
		}

104
		r, err := i.Terminal.Read()
Patrick Devine's avatar
Patrick Devine committed
105

106
107
		if buf.IsEmpty() {
			fmt.Print(ClearToEOL)
Patrick Devine's avatar
Patrick Devine committed
108
109
		}

110
111
112
113
		if err != nil {
			return "", io.EOF
		}

Patrick Devine's avatar
Patrick Devine committed
114
115
116
117
118
		if escex {
			escex = false

			switch r {
			case KeyUp:
119
				i.historyPrev(buf, &currentLineBuf)
Patrick Devine's avatar
Patrick Devine committed
120
			case KeyDown:
121
				i.historyNext(buf, &currentLineBuf)
Patrick Devine's avatar
Patrick Devine committed
122
123
124
125
126
			case KeyLeft:
				buf.MoveLeft()
			case KeyRight:
				buf.MoveRight()
			case CharBracketedPaste:
127
				var code string
Michael Yang's avatar
lint  
Michael Yang committed
128
				for range 3 {
129
130
131
132
133
					r, err = i.Terminal.Read()
					if err != nil {
						return "", io.EOF
					}

134
135
136
					code += string(r)
				}
				if code == CharBracketedPasteStart {
137
					i.Pasting = true
138
				} else if code == CharBracketedPasteEnd {
139
					i.Pasting = false
140
				}
Patrick Devine's avatar
Patrick Devine committed
141
			case KeyDel:
142
				if buf.DisplaySize() > 0 {
Patrick Devine's avatar
Patrick Devine committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
					buf.Delete()
				}
				metaDel = true
			case MetaStart:
				buf.MoveToStart()
			case MetaEnd:
				buf.MoveToEnd()
			default:
				// skip any keys we don't know about
				continue
			}
			continue
		} else if esc {
			esc = false

			switch r {
			case 'b':
				buf.MoveLeftWord()
			case 'f':
				buf.MoveRightWord()
163
164
			case CharBackspace:
				buf.DeleteWord()
Patrick Devine's avatar
Patrick Devine committed
165
166
167
168
169
170
171
			case CharEscapeEx:
				escex = true
			}
			continue
		}

		switch r {
172
173
		case CharNull:
			continue
Patrick Devine's avatar
Patrick Devine committed
174
175
176
177
		case CharEsc:
			esc = true
		case CharInterrupt:
			return "", ErrInterrupt
178
179
180
181
		case CharPrev:
			i.historyPrev(buf, &currentLineBuf)
		case CharNext:
			i.historyNext(buf, &currentLineBuf)
Patrick Devine's avatar
Patrick Devine committed
182
183
184
185
186
187
188
189
190
191
192
193
		case CharLineStart:
			buf.MoveToStart()
		case CharLineEnd:
			buf.MoveToEnd()
		case CharBackward:
			buf.MoveLeft()
		case CharForward:
			buf.MoveRight()
		case CharBackspace, CharCtrlH:
			buf.Remove()
		case CharTab:
			// todo: convert back to real tabs
Michael Yang's avatar
lint  
Michael Yang committed
194
			for range 8 {
Patrick Devine's avatar
Patrick Devine committed
195
196
197
				buf.Add(' ')
			}
		case CharDelete:
198
			if buf.DisplaySize() > 0 {
Patrick Devine's avatar
Patrick Devine committed
199
200
201
202
203
204
205
206
207
208
209
210
				buf.Delete()
			} else {
				return "", io.EOF
			}
		case CharKill:
			buf.DeleteRemaining()
		case CharCtrlU:
			buf.DeleteBefore()
		case CharCtrlL:
			buf.ClearScreen()
		case CharCtrlW:
			buf.DeleteWord()
Michael Yang's avatar
Michael Yang committed
211
		case CharCtrlZ:
Michael Yang's avatar
Michael Yang committed
212
			fd := os.Stdin.Fd()
213
			return handleCharCtrlZ(fd, i.Terminal.termios)
214
		case CharEnter, CharCtrlJ:
215
216
			output := buf.String()
			if output != "" {
Michael Yang's avatar
Michael Yang committed
217
				i.History.Add(output)
218
219
220
			}
			buf.MoveToEnd()
			fmt.Println()
221

222
			return output, nil
Patrick Devine's avatar
Patrick Devine committed
223
224
225
226
227
		default:
			if metaDel {
				metaDel = false
				continue
			}
228
			if r >= CharSpace || r == CharEnter || r == CharCtrlJ {
Patrick Devine's avatar
Patrick Devine committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
				buf.Add(r)
			}
		}
	}
}

func (i *Instance) HistoryEnable() {
	i.History.Enabled = true
}

func (i *Instance) HistoryDisable() {
	i.History.Enabled = false
}

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
func (i *Instance) historyPrev(buf *Buffer, currentLineBuf *[]rune) {
	if i.History.Pos > 0 {
		if i.History.Pos == i.History.Size() {
			*currentLineBuf = []rune(buf.String())
		}
		buf.Replace([]rune(i.History.Prev()))
	}
}

func (i *Instance) historyNext(buf *Buffer, currentLineBuf *[]rune) {
	if i.History.Pos < i.History.Size() {
		buf.Replace([]rune(i.History.Next()))
		if i.History.Pos == i.History.Size() {
			buf.Replace(*currentLineBuf)
		}
	}
}

Patrick Devine's avatar
Patrick Devine committed
261
func NewTerminal() (*Terminal, error) {
Michael Yang's avatar
Michael Yang committed
262
	fd := os.Stdin.Fd()
263
264
265
266
267
	termios, err := SetRawMode(fd)
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
268
269
	t := &Terminal{
		outchan: make(chan rune),
270
271
		rawmode: true,
		termios: termios,
Patrick Devine's avatar
Patrick Devine committed
272
273
274
275
276
277
278
279
280
281
282
283
284
	}

	go t.ioloop()

	return t, nil
}

func (t *Terminal) ioloop() {
	buf := bufio.NewReader(os.Stdin)

	for {
		r, _, err := buf.ReadRune()
		if err != nil {
285
			close(t.outchan)
Patrick Devine's avatar
Patrick Devine committed
286
287
288
289
290
291
			break
		}
		t.outchan <- r
	}
}

292
func (t *Terminal) Read() (rune, error) {
Patrick Devine's avatar
Patrick Devine committed
293
294
	r, ok := <-t.outchan
	if !ok {
295
		return 0, io.EOF
Patrick Devine's avatar
Patrick Devine committed
296
	}
297
298

	return r, nil
Patrick Devine's avatar
Patrick Devine committed
299
}