readline.go 4.39 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
18
19
20
21
22
23
24
25
26
package readline

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

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

type Terminal struct {
	outchan chan rune
}

type Instance struct {
	Prompt   *Prompt
	Terminal *Terminal
	History  *History
27
	Pasting  bool
Patrick Devine's avatar
Patrick Devine committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
}

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) {
	prompt := i.Prompt.Prompt
50
	if i.Prompt.UseAlt || i.Pasting {
Patrick Devine's avatar
Patrick Devine committed
51
52
		prompt = i.Prompt.AltPrompt
	}
53
	fmt.Print(prompt)
Patrick Devine's avatar
Patrick Devine committed
54

55
56
	fd := int(syscall.Stdin)
	termios, err := SetRawMode(fd)
Patrick Devine's avatar
Patrick Devine committed
57
58
59
	if err != nil {
		return "", err
	}
60
	defer UnsetRawMode(fd, termios)
Patrick Devine's avatar
Patrick Devine committed
61
62
63
64
65
66
67
68
69
70

	buf, _ := NewBuffer(i.Prompt)

	var esc bool
	var escex bool
	var metaDel bool

	var currentLineBuf []rune

	for {
71
72
73
		// don't show placeholder when pasting unless we're in multiline mode
		showPlaceholder := !i.Pasting || i.Prompt.UseAlt
		if buf.IsEmpty() && showPlaceholder {
Patrick Devine's avatar
Patrick Devine committed
74
75
76
77
78
79
80
			ph := i.Prompt.Placeholder
			if i.Prompt.UseAlt {
				ph = i.Prompt.AltPlaceholder
			}
			fmt.Printf(ColorGrey + ph + fmt.Sprintf(CursorLeftN, len(ph)) + ColorDefault)
		}

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

83
84
		if buf.IsEmpty() {
			fmt.Print(ClearToEOL)
Patrick Devine's avatar
Patrick Devine committed
85
86
		}

87
88
89
90
		if err != nil {
			return "", io.EOF
		}

Patrick Devine's avatar
Patrick Devine committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
		if escex {
			escex = false

			switch r {
			case KeyUp:
				if i.History.Pos > 0 {
					if i.History.Pos == i.History.Size() {
						currentLineBuf = []rune(buf.String())
					}
					buf.Replace(i.History.Prev())
				}
			case KeyDown:
				if i.History.Pos < i.History.Size() {
					buf.Replace(i.History.Next())
					if i.History.Pos == i.History.Size() {
						buf.Replace(currentLineBuf)
					}
				}
			case KeyLeft:
				buf.MoveLeft()
			case KeyRight:
				buf.MoveRight()
			case CharBracketedPaste:
114
115
				var code string
				for cnt := 0; cnt < 3; cnt++ {
116
117
118
119
120
					r, err = i.Terminal.Read()
					if err != nil {
						return "", io.EOF
					}

121
122
123
					code += string(r)
				}
				if code == CharBracketedPasteStart {
124
					i.Pasting = true
125
				} else if code == CharBracketedPasteEnd {
126
					i.Pasting = false
127
				}
Patrick Devine's avatar
Patrick Devine committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
			case KeyDel:
				if buf.Size() > 0 {
					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()
150
151
			case CharBackspace:
				buf.DeleteWord()
Patrick Devine's avatar
Patrick Devine committed
152
153
154
155
156
157
158
			case CharEscapeEx:
				escex = true
			}
			continue
		}

		switch r {
159
160
		case CharNull:
			continue
Patrick Devine's avatar
Patrick Devine committed
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
		case CharEsc:
			esc = true
		case CharInterrupt:
			return "", ErrInterrupt
		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
			for cnt := 0; cnt < 8; cnt++ {
				buf.Add(' ')
			}
		case CharDelete:
			if buf.Size() > 0 {
				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
194
195
196
197
198
199
200
201
202
		case CharCtrlZ:
			if err := UnsetRawMode(fd, termios); err != nil {
				return "", err
			}

			syscall.Kill(0, syscall.SIGSTOP)

			// on resume...
			return "", nil
Patrick Devine's avatar
Patrick Devine committed
203
		case CharEnter:
204
205
206
207
208
209
			output := buf.String()
			if output != "" {
				i.History.Add([]rune(output))
			}
			buf.MoveToEnd()
			fmt.Println()
210

211
			return output, nil
Patrick Devine's avatar
Patrick Devine committed
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
		default:
			if metaDel {
				metaDel = false
				continue
			}
			if r >= CharSpace || r == CharEnter {
				buf.Add(r)
			}
		}
	}
}

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

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

func NewTerminal() (*Terminal, error) {
	t := &Terminal{
		outchan: make(chan rune),
	}

	go t.ioloop()

	return t, nil
}

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

	for {
		r, _, err := buf.ReadRune()
		if err != nil {
248
			close(t.outchan)
Patrick Devine's avatar
Patrick Devine committed
249
250
251
252
253
254
			break
		}
		t.outchan <- r
	}
}

255
func (t *Terminal) Read() (rune, error) {
Patrick Devine's avatar
Patrick Devine committed
256
257
	r, ok := <-t.outchan
	if !ok {
258
		return 0, io.EOF
Patrick Devine's avatar
Patrick Devine committed
259
	}
260
261

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