summaryrefslogtreecommitdiff
path: root/vendor/github.com/chzyer/readline/operation.go
blob: 4c31624f806a73577768d66d2be00b7d54339098 (plain)
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package readline

import (
	"errors"
	"io"
	"sync"
)

var (
	ErrInterrupt = errors.New("Interrupt")
)

type InterruptError struct {
	Line []rune
}

func (*InterruptError) Error() string {
	return "Interrupted"
}

type Operation struct {
	m       sync.Mutex
	cfg     *Config
	t       *Terminal
	buf     *RuneBuffer
	outchan chan []rune
	errchan chan error
	w       io.Writer

	history *opHistory
	*opSearch
	*opCompleter
	*opPassword
	*opVim
}

func (o *Operation) SetBuffer(what string) {
	o.buf.Set([]rune(what))
}

type wrapWriter struct {
	r      *Operation
	t      *Terminal
	target io.Writer
}

func (w *wrapWriter) Write(b []byte) (int, error) {
	if !w.t.IsReading() {
		return w.target.Write(b)
	}

	var (
		n   int
		err error
	)
	w.r.buf.Refresh(func() {
		n, err = w.target.Write(b)
	})

	if w.r.IsSearchMode() {
		w.r.SearchRefresh(-1)
	}
	if w.r.IsInCompleteMode() {
		w.r.CompleteRefresh()
	}
	return n, err
}

func NewOperation(t *Terminal, cfg *Config) *Operation {
	width := cfg.FuncGetWidth()
	op := &Operation{
		t:       t,
		buf:     NewRuneBuffer(t, cfg.Prompt, cfg, width),
		outchan: make(chan []rune),
		errchan: make(chan error, 1),
	}
	op.w = op.buf.w
	op.SetConfig(cfg)
	op.opVim = newVimMode(op)
	op.opCompleter = newOpCompleter(op.buf.w, op, width)
	op.opPassword = newOpPassword(op)
	op.cfg.FuncOnWidthChanged(func() {
		newWidth := cfg.FuncGetWidth()
		op.opCompleter.OnWidthChange(newWidth)
		op.opSearch.OnWidthChange(newWidth)
		op.buf.OnWidthChange(newWidth)
	})
	go op.ioloop()
	return op
}

func (o *Operation) SetPrompt(s string) {
	o.buf.SetPrompt(s)
}

func (o *Operation) SetMaskRune(r rune) {
	o.buf.SetMask(r)
}

func (o *Operation) GetConfig() *Config {
	o.m.Lock()
	cfg := *o.cfg
	o.m.Unlock()
	return &cfg
}

func (o *Operation) ioloop() {
	for {
		keepInSearchMode := false
		keepInCompleteMode := false
		r := o.t.ReadRune()
		if o.GetConfig().FuncFilterInputRune != nil {
			var process bool
			r, process = o.GetConfig().FuncFilterInputRune(r)
			if !process {
				o.buf.Refresh(nil) // to refresh the line
				continue           // ignore this rune
			}
		}

		if r == 0 { // io.EOF
			if o.buf.Len() == 0 {
				o.buf.Clean()
				select {
				case o.errchan <- io.EOF:
				}
				break
			} else {
				// if stdin got io.EOF and there is something left in buffer,
				// let's flush them by sending CharEnter.
				// And we will got io.EOF int next loop.
				r = CharEnter
			}
		}
		isUpdateHistory := true

		if o.IsInCompleteSelectMode() {
			keepInCompleteMode = o.HandleCompleteSelect(r)
			if keepInCompleteMode {
				continue
			}

			o.buf.Refresh(nil)
			switch r {
			case CharEnter, CharCtrlJ:
				o.history.Update(o.buf.Runes(), false)
				fallthrough
			case CharInterrupt:
				o.t.KickRead()
				fallthrough
			case CharBell:
				continue
			}
		}

		if o.IsEnableVimMode() {
			r = o.HandleVim(r, o.t.ReadRune)
			if r == 0 {
				continue
			}
		}

		switch r {
		case CharBell:
			if o.IsSearchMode() {
				o.ExitSearchMode(true)
				o.buf.Refresh(nil)
			}
			if o.IsInCompleteMode() {
				o.ExitCompleteMode(true)
				o.buf.Refresh(nil)
			}
		case CharTab:
			if o.GetConfig().AutoComplete == nil {
				o.t.Bell()
				break
			}
			if o.OnComplete() {
				keepInCompleteMode = true
			} else {
				o.t.Bell()
				break
			}

		case CharBckSearch:
			if !o.SearchMode(S_DIR_BCK) {
				o.t.Bell()
				break
			}
			keepInSearchMode = true
		case CharCtrlU:
			o.buf.KillFront()
		case CharFwdSearch:
			if !o.SearchMode(S_DIR_FWD) {
				o.t.Bell()
				break
			}
			keepInSearchMode = true
		case CharKill:
			o.buf.Kill()
			keepInCompleteMode = true
		case MetaForward:
			o.buf.MoveToNextWord()
		case CharTranspose:
			o.buf.Transpose()
		case MetaBackward:
			o.buf.MoveToPrevWord()
		case MetaDelete:
			o.buf.DeleteWord()
		case CharLineStart:
			o.buf.MoveToLineStart()
		case CharLineEnd:
			o.buf.MoveToLineEnd()
		case CharBackspace, CharCtrlH:
			if o.IsSearchMode() {
				o.SearchBackspace()
				keepInSearchMode = true
				break
			}

			if o.buf.Len() == 0 {
				o.t.Bell()
				break
			}
			o.buf.Backspace()
			if o.IsInCompleteMode() {
				o.OnComplete()
			}
		case CharCtrlZ:
			o.buf.Clean()
			o.t.SleepToResume()
			o.Refresh()
		case CharCtrlL:
			ClearScreen(o.w)
			o.Refresh()
		case MetaBackspace, CharCtrlW:
			o.buf.BackEscapeWord()
		case CharCtrlY:
			o.buf.Yank()
		case CharEnter, CharCtrlJ:
			if o.IsSearchMode() {
				o.ExitSearchMode(false)
			}
			o.buf.MoveToLineEnd()
			var data []rune
			if !o.GetConfig().UniqueEditLine {
				o.buf.WriteRune('\n')
				data = o.buf.Reset()
				data = data[:len(data)-1] // trim \n
			} else {
				o.buf.Clean()
				data = o.buf.Reset()
			}
			o.outchan <- data
			if !o.GetConfig().DisableAutoSaveHistory {
				// ignore IO error
				_ = o.history.New(data)
			} else {
				isUpdateHistory = false
			}
		case CharBackward:
			o.buf.MoveBackward()
		case CharForward:
			o.buf.MoveForward()
		case CharPrev:
			buf := o.history.Prev()
			if buf != nil {
				o.buf.Set(buf)
			} else {
				o.t.Bell()
			}
		case CharNext:
			buf, ok := o.history.Next()
			if ok {
				o.buf.Set(buf)
			} else {
				o.t.Bell()
			}
		case CharDelete:
			if o.buf.Len() > 0 || !o.IsNormalMode() {
				o.t.KickRead()
				if !o.buf.Delete() {
					o.t.Bell()
				}
				break
			}

			// treat as EOF
			if !o.GetConfig().UniqueEditLine {
				o.buf.WriteString(o.GetConfig().EOFPrompt + "\n")
			}
			o.buf.Reset()
			isUpdateHistory = false
			o.history.Revert()
			o.errchan <- io.EOF
			if o.GetConfig().UniqueEditLine {
				o.buf.Clean()
			}
		case CharInterrupt:
			if o.IsSearchMode() {
				o.t.KickRead()
				o.ExitSearchMode(true)
				break
			}
			if o.IsInCompleteMode() {
				o.t.KickRead()
				o.ExitCompleteMode(true)
				o.buf.Refresh(nil)
				break
			}
			o.buf.MoveToLineEnd()
			o.buf.Refresh(nil)
			hint := o.GetConfig().InterruptPrompt + "\n"
			if !o.GetConfig().UniqueEditLine {
				o.buf.WriteString(hint)
			}
			remain := o.buf.Reset()
			if !o.GetConfig().UniqueEditLine {
				remain = remain[:len(remain)-len([]rune(hint))]
			}
			isUpdateHistory = false
			o.history.Revert()
			o.errchan <- &InterruptError{remain}
		default:
			if o.IsSearchMode() {
				o.SearchChar(r)
				keepInSearchMode = true
				break
			}
			o.buf.WriteRune(r)
			if o.IsInCompleteMode() {
				o.OnComplete()
				keepInCompleteMode = true
			}
		}

		listener := o.GetConfig().Listener
		if listener != nil {
			newLine, newPos, ok := listener.OnChange(o.buf.Runes(), o.buf.Pos(), r)
			if ok {
				o.buf.SetWithIdx(newPos, newLine)
			}
		}

		o.m.Lock()
		if !keepInSearchMode && o.IsSearchMode() {
			o.ExitSearchMode(false)
			o.buf.Refresh(nil)
		} else if o.IsInCompleteMode() {
			if !keepInCompleteMode {
				o.ExitCompleteMode(false)
				o.Refresh()
			} else {
				o.buf.Refresh(nil)
				o.CompleteRefresh()
			}
		}
		if isUpdateHistory && !o.IsSearchMode() {
			// it will cause null history
			o.history.Update(o.buf.Runes(), false)
		}
		o.m.Unlock()
	}
}

func (o *Operation) Stderr() io.Writer {
	return &wrapWriter{target: o.GetConfig().Stderr, r: o, t: o.t}
}

func (o *Operation) Stdout() io.Writer {
	return &wrapWriter{target: o.GetConfig().Stdout, r: o, t: o.t}
}

func (o *Operation) String() (string, error) {
	r, err := o.Runes()
	return string(r), err
}

func (o *Operation) Runes() ([]rune, error) {
	o.t.EnterRawMode()
	defer o.t.ExitRawMode()

	listener := o.GetConfig().Listener
	if listener != nil {
		listener.OnChange(nil, 0, 0)
	}

	o.buf.Refresh(nil) // print prompt
	o.t.KickRead()
	select {
	case r := <-o.outchan:
		return r, nil
	case err := <-o.errchan:
		if e, ok := err.(*InterruptError); ok {
			return e.Line, ErrInterrupt
		}
		return nil, err
	}
}

func (o *Operation) PasswordEx(prompt string, l Listener) ([]byte, error) {
	cfg := o.GenPasswordConfig()
	cfg.Prompt = prompt
	cfg.Listener = l
	return o.PasswordWithConfig(cfg)
}

func (o *Operation) GenPasswordConfig() *Config {
	return o.opPassword.PasswordConfig()
}

func (o *Operation) PasswordWithConfig(cfg *Config) ([]byte, error) {
	if err := o.opPassword.EnterPasswordMode(cfg); err != nil {
		return nil, err
	}
	defer o.opPassword.ExitPasswordMode()
	return o.Slice()
}

func (o *Operation) Password(prompt string) ([]byte, error) {
	return o.PasswordEx(prompt, nil)
}

func (o *Operation) SetTitle(t string) {
	o.w.Write([]byte("\033[2;" + t + "\007"))
}

func (o *Operation) Slice() ([]byte, error) {
	r, err := o.Runes()
	if err != nil {
		return nil, err
	}
	return []byte(string(r)), nil
}

func (o *Operation) Close() {
	o.history.Close()
}

func (o *Operation) SetHistoryPath(path string) {
	if o.history != nil {
		o.history.Close()
	}
	o.cfg.HistoryFile = path
	o.history = newOpHistory(o.cfg)
}

func (o *Operation) IsNormalMode() bool {
	return !o.IsInCompleteMode() && !o.IsSearchMode()
}

func (op *Operation) SetConfig(cfg *Config) (*Config, error) {
	op.m.Lock()
	defer op.m.Unlock()
	if op.cfg == cfg {
		return op.cfg, nil
	}
	if err := cfg.Init(); err != nil {
		return op.cfg, err
	}
	old := op.cfg
	op.cfg = cfg
	op.SetPrompt(cfg.Prompt)
	op.SetMaskRune(cfg.MaskRune)
	op.buf.SetConfig(cfg)
	width := op.cfg.FuncGetWidth()

	if cfg.opHistory == nil {
		op.SetHistoryPath(cfg.HistoryFile)
		cfg.opHistory = op.history
		cfg.opSearch = newOpSearch(op.buf.w, op.buf, op.history, cfg, width)
	}
	op.history = cfg.opHistory

	// SetHistoryPath will close opHistory which already exists
	// so if we use it next time, we need to reopen it by `InitHistory()`
	op.history.Init()

	if op.cfg.AutoComplete != nil {
		op.opCompleter = newOpCompleter(op.buf.w, op, width)
	}

	op.opSearch = cfg.opSearch
	return old, nil
}

func (o *Operation) ResetHistory() {
	o.history.Reset()
}

// if err is not nil, it just mean it fail to write to file
// other things goes fine.
func (o *Operation) SaveHistory(content string) error {
	return o.history.New([]rune(content))
}

func (o *Operation) Refresh() {
	if o.t.IsReading() {
		o.buf.Refresh(nil)
	}
}

func (o *Operation) Clean() {
	o.buf.Clean()
}

func FuncListener(f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)) Listener {
	return &DumpListener{f: f}
}

type DumpListener struct {
	f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)
}

func (d *DumpListener) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
	return d.f(line, pos, key)
}

type Listener interface {
	OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)
}

type Painter interface {
	Paint(line []rune, pos int) []rune
}

type defaultPainter struct{}

func (p *defaultPainter) Paint(line []rune, _ int) []rune {
	return line
}