blob: 9d666ffcf0f1aeb10a0604534c385c16e95e0c5b [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package terminal
6
7import (
8 "bytes"
9 "io"
10 "sync"
11 "unicode/utf8"
12)
13
14// EscapeCodes contains escape sequences that can be written to the terminal in
15// order to achieve different styles of text.
16type EscapeCodes struct {
17 // Foreground colors
18 Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
19
20 // Reset all attributes
21 Reset []byte
22}
23
24var vt100EscapeCodes = EscapeCodes{
25 Black: []byte{keyEscape, '[', '3', '0', 'm'},
26 Red: []byte{keyEscape, '[', '3', '1', 'm'},
27 Green: []byte{keyEscape, '[', '3', '2', 'm'},
28 Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
29 Blue: []byte{keyEscape, '[', '3', '4', 'm'},
30 Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
31 Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
32 White: []byte{keyEscape, '[', '3', '7', 'm'},
33
34 Reset: []byte{keyEscape, '[', '0', 'm'},
35}
36
37// Terminal contains the state for running a VT100 terminal that is capable of
38// reading lines of input.
39type Terminal struct {
40 // AutoCompleteCallback, if non-null, is called for each keypress with
41 // the full input line and the current position of the cursor (in
42 // bytes, as an index into |line|). If it returns ok=false, the key
43 // press is processed normally. Otherwise it returns a replacement line
44 // and the new cursor position.
45 AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)
46
47 // Escape contains a pointer to the escape codes for this terminal.
48 // It's always a valid pointer, although the escape codes themselves
49 // may be empty if the terminal doesn't support them.
50 Escape *EscapeCodes
51
52 // lock protects the terminal and the state in this object from
53 // concurrent processing of a key press and a Write() call.
54 lock sync.Mutex
55
56 c io.ReadWriter
57 prompt []rune
58
59 // line is the current line being entered.
60 line []rune
61 // pos is the logical position of the cursor in line
62 pos int
63 // echo is true if local echo is enabled
64 echo bool
65 // pasteActive is true iff there is a bracketed paste operation in
66 // progress.
67 pasteActive bool
68
69 // cursorX contains the current X value of the cursor where the left
70 // edge is 0. cursorY contains the row number where the first row of
71 // the current line is 0.
72 cursorX, cursorY int
73 // maxLine is the greatest value of cursorY so far.
74 maxLine int
75
76 termWidth, termHeight int
77
78 // outBuf contains the terminal data to be sent.
79 outBuf []byte
80 // remainder contains the remainder of any partial key sequences after
81 // a read. It aliases into inBuf.
82 remainder []byte
83 inBuf [256]byte
84
85 // history contains previously entered commands so that they can be
86 // accessed with the up and down keys.
87 history stRingBuffer
88 // historyIndex stores the currently accessed history entry, where zero
89 // means the immediately previous entry.
90 historyIndex int
91 // When navigating up and down the history it's possible to return to
92 // the incomplete, initial line. That value is stored in
93 // historyPending.
94 historyPending string
95}
96
97// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
98// a local terminal, that terminal must first have been put into raw mode.
99// prompt is a string that is written at the start of each input line (i.e.
100// "> ").
101func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
102 return &Terminal{
103 Escape: &vt100EscapeCodes,
104 c: c,
105 prompt: []rune(prompt),
106 termWidth: 80,
107 termHeight: 24,
108 echo: true,
109 historyIndex: -1,
110 }
111}
112
113const (
114 keyCtrlD = 4
115 keyCtrlU = 21
116 keyEnter = '\r'
117 keyEscape = 27
118 keyBackspace = 127
119 keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
120 keyUp
121 keyDown
122 keyLeft
123 keyRight
124 keyAltLeft
125 keyAltRight
126 keyHome
127 keyEnd
128 keyDeleteWord
129 keyDeleteLine
130 keyClearScreen
131 keyPasteStart
132 keyPasteEnd
133)
134
135var (
136 crlf = []byte{'\r', '\n'}
137 pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
138 pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
139)
140
141// bytesToKey tries to parse a key sequence from b. If successful, it returns
142// the key and the remainder of the input. Otherwise it returns utf8.RuneError.
143func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
144 if len(b) == 0 {
145 return utf8.RuneError, nil
146 }
147
148 if !pasteActive {
149 switch b[0] {
150 case 1: // ^A
151 return keyHome, b[1:]
152 case 5: // ^E
153 return keyEnd, b[1:]
154 case 8: // ^H
155 return keyBackspace, b[1:]
156 case 11: // ^K
157 return keyDeleteLine, b[1:]
158 case 12: // ^L
159 return keyClearScreen, b[1:]
160 case 23: // ^W
161 return keyDeleteWord, b[1:]
Stephane Barbarie260a5632019-02-26 16:12:49 -0500162 case 14: // ^N
163 return keyDown, b[1:]
164 case 16: // ^P
165 return keyUp, b[1:]
sslobodrd046be82019-01-16 10:02:22 -0500166 }
167 }
168
169 if b[0] != keyEscape {
170 if !utf8.FullRune(b) {
171 return utf8.RuneError, b
172 }
173 r, l := utf8.DecodeRune(b)
174 return r, b[l:]
175 }
176
177 if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
178 switch b[2] {
179 case 'A':
180 return keyUp, b[3:]
181 case 'B':
182 return keyDown, b[3:]
183 case 'C':
184 return keyRight, b[3:]
185 case 'D':
186 return keyLeft, b[3:]
187 case 'H':
188 return keyHome, b[3:]
189 case 'F':
190 return keyEnd, b[3:]
191 }
192 }
193
194 if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
195 switch b[5] {
196 case 'C':
197 return keyAltRight, b[6:]
198 case 'D':
199 return keyAltLeft, b[6:]
200 }
201 }
202
203 if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
204 return keyPasteStart, b[6:]
205 }
206
207 if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
208 return keyPasteEnd, b[6:]
209 }
210
211 // If we get here then we have a key that we don't recognise, or a
212 // partial sequence. It's not clear how one should find the end of a
213 // sequence without knowing them all, but it seems that [a-zA-Z~] only
214 // appears at the end of a sequence.
215 for i, c := range b[0:] {
216 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
217 return keyUnknown, b[i+1:]
218 }
219 }
220
221 return utf8.RuneError, b
222}
223
224// queue appends data to the end of t.outBuf
225func (t *Terminal) queue(data []rune) {
226 t.outBuf = append(t.outBuf, []byte(string(data))...)
227}
228
229var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
230var space = []rune{' '}
231
232func isPrintable(key rune) bool {
233 isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
234 return key >= 32 && !isInSurrogateArea
235}
236
237// moveCursorToPos appends data to t.outBuf which will move the cursor to the
238// given, logical position in the text.
239func (t *Terminal) moveCursorToPos(pos int) {
240 if !t.echo {
241 return
242 }
243
244 x := visualLength(t.prompt) + pos
245 y := x / t.termWidth
246 x = x % t.termWidth
247
248 up := 0
249 if y < t.cursorY {
250 up = t.cursorY - y
251 }
252
253 down := 0
254 if y > t.cursorY {
255 down = y - t.cursorY
256 }
257
258 left := 0
259 if x < t.cursorX {
260 left = t.cursorX - x
261 }
262
263 right := 0
264 if x > t.cursorX {
265 right = x - t.cursorX
266 }
267
268 t.cursorX = x
269 t.cursorY = y
270 t.move(up, down, left, right)
271}
272
273func (t *Terminal) move(up, down, left, right int) {
274 movement := make([]rune, 3*(up+down+left+right))
275 m := movement
276 for i := 0; i < up; i++ {
277 m[0] = keyEscape
278 m[1] = '['
279 m[2] = 'A'
280 m = m[3:]
281 }
282 for i := 0; i < down; i++ {
283 m[0] = keyEscape
284 m[1] = '['
285 m[2] = 'B'
286 m = m[3:]
287 }
288 for i := 0; i < left; i++ {
289 m[0] = keyEscape
290 m[1] = '['
291 m[2] = 'D'
292 m = m[3:]
293 }
294 for i := 0; i < right; i++ {
295 m[0] = keyEscape
296 m[1] = '['
297 m[2] = 'C'
298 m = m[3:]
299 }
300
301 t.queue(movement)
302}
303
304func (t *Terminal) clearLineToRight() {
305 op := []rune{keyEscape, '[', 'K'}
306 t.queue(op)
307}
308
309const maxLineLength = 4096
310
311func (t *Terminal) setLine(newLine []rune, newPos int) {
312 if t.echo {
313 t.moveCursorToPos(0)
314 t.writeLine(newLine)
315 for i := len(newLine); i < len(t.line); i++ {
316 t.writeLine(space)
317 }
318 t.moveCursorToPos(newPos)
319 }
320 t.line = newLine
321 t.pos = newPos
322}
323
324func (t *Terminal) advanceCursor(places int) {
325 t.cursorX += places
326 t.cursorY += t.cursorX / t.termWidth
327 if t.cursorY > t.maxLine {
328 t.maxLine = t.cursorY
329 }
330 t.cursorX = t.cursorX % t.termWidth
331
332 if places > 0 && t.cursorX == 0 {
333 // Normally terminals will advance the current position
334 // when writing a character. But that doesn't happen
335 // for the last character in a line. However, when
336 // writing a character (except a new line) that causes
337 // a line wrap, the position will be advanced two
338 // places.
339 //
340 // So, if we are stopping at the end of a line, we
341 // need to write a newline so that our cursor can be
342 // advanced to the next line.
343 t.outBuf = append(t.outBuf, '\r', '\n')
344 }
345}
346
347func (t *Terminal) eraseNPreviousChars(n int) {
348 if n == 0 {
349 return
350 }
351
352 if t.pos < n {
353 n = t.pos
354 }
355 t.pos -= n
356 t.moveCursorToPos(t.pos)
357
358 copy(t.line[t.pos:], t.line[n+t.pos:])
359 t.line = t.line[:len(t.line)-n]
360 if t.echo {
361 t.writeLine(t.line[t.pos:])
362 for i := 0; i < n; i++ {
363 t.queue(space)
364 }
365 t.advanceCursor(n)
366 t.moveCursorToPos(t.pos)
367 }
368}
369
370// countToLeftWord returns then number of characters from the cursor to the
371// start of the previous word.
372func (t *Terminal) countToLeftWord() int {
373 if t.pos == 0 {
374 return 0
375 }
376
377 pos := t.pos - 1
378 for pos > 0 {
379 if t.line[pos] != ' ' {
380 break
381 }
382 pos--
383 }
384 for pos > 0 {
385 if t.line[pos] == ' ' {
386 pos++
387 break
388 }
389 pos--
390 }
391
392 return t.pos - pos
393}
394
395// countToRightWord returns then number of characters from the cursor to the
396// start of the next word.
397func (t *Terminal) countToRightWord() int {
398 pos := t.pos
399 for pos < len(t.line) {
400 if t.line[pos] == ' ' {
401 break
402 }
403 pos++
404 }
405 for pos < len(t.line) {
406 if t.line[pos] != ' ' {
407 break
408 }
409 pos++
410 }
411 return pos - t.pos
412}
413
414// visualLength returns the number of visible glyphs in s.
415func visualLength(runes []rune) int {
416 inEscapeSeq := false
417 length := 0
418
419 for _, r := range runes {
420 switch {
421 case inEscapeSeq:
422 if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
423 inEscapeSeq = false
424 }
425 case r == '\x1b':
426 inEscapeSeq = true
427 default:
428 length++
429 }
430 }
431
432 return length
433}
434
435// handleKey processes the given key and, optionally, returns a line of text
436// that the user has entered.
437func (t *Terminal) handleKey(key rune) (line string, ok bool) {
438 if t.pasteActive && key != keyEnter {
439 t.addKeyToLine(key)
440 return
441 }
442
443 switch key {
444 case keyBackspace:
445 if t.pos == 0 {
446 return
447 }
448 t.eraseNPreviousChars(1)
449 case keyAltLeft:
450 // move left by a word.
451 t.pos -= t.countToLeftWord()
452 t.moveCursorToPos(t.pos)
453 case keyAltRight:
454 // move right by a word.
455 t.pos += t.countToRightWord()
456 t.moveCursorToPos(t.pos)
457 case keyLeft:
458 if t.pos == 0 {
459 return
460 }
461 t.pos--
462 t.moveCursorToPos(t.pos)
463 case keyRight:
464 if t.pos == len(t.line) {
465 return
466 }
467 t.pos++
468 t.moveCursorToPos(t.pos)
469 case keyHome:
470 if t.pos == 0 {
471 return
472 }
473 t.pos = 0
474 t.moveCursorToPos(t.pos)
475 case keyEnd:
476 if t.pos == len(t.line) {
477 return
478 }
479 t.pos = len(t.line)
480 t.moveCursorToPos(t.pos)
481 case keyUp:
482 entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
483 if !ok {
484 return "", false
485 }
486 if t.historyIndex == -1 {
487 t.historyPending = string(t.line)
488 }
489 t.historyIndex++
490 runes := []rune(entry)
491 t.setLine(runes, len(runes))
492 case keyDown:
493 switch t.historyIndex {
494 case -1:
495 return
496 case 0:
497 runes := []rune(t.historyPending)
498 t.setLine(runes, len(runes))
499 t.historyIndex--
500 default:
501 entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
502 if ok {
503 t.historyIndex--
504 runes := []rune(entry)
505 t.setLine(runes, len(runes))
506 }
507 }
508 case keyEnter:
509 t.moveCursorToPos(len(t.line))
510 t.queue([]rune("\r\n"))
511 line = string(t.line)
512 ok = true
513 t.line = t.line[:0]
514 t.pos = 0
515 t.cursorX = 0
516 t.cursorY = 0
517 t.maxLine = 0
518 case keyDeleteWord:
519 // Delete zero or more spaces and then one or more characters.
520 t.eraseNPreviousChars(t.countToLeftWord())
521 case keyDeleteLine:
522 // Delete everything from the current cursor position to the
523 // end of line.
524 for i := t.pos; i < len(t.line); i++ {
525 t.queue(space)
526 t.advanceCursor(1)
527 }
528 t.line = t.line[:t.pos]
529 t.moveCursorToPos(t.pos)
530 case keyCtrlD:
531 // Erase the character under the current position.
532 // The EOF case when the line is empty is handled in
533 // readLine().
534 if t.pos < len(t.line) {
535 t.pos++
536 t.eraseNPreviousChars(1)
537 }
538 case keyCtrlU:
539 t.eraseNPreviousChars(t.pos)
540 case keyClearScreen:
541 // Erases the screen and moves the cursor to the home position.
542 t.queue([]rune("\x1b[2J\x1b[H"))
543 t.queue(t.prompt)
544 t.cursorX, t.cursorY = 0, 0
545 t.advanceCursor(visualLength(t.prompt))
546 t.setLine(t.line, t.pos)
547 default:
548 if t.AutoCompleteCallback != nil {
549 prefix := string(t.line[:t.pos])
550 suffix := string(t.line[t.pos:])
551
552 t.lock.Unlock()
553 newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
554 t.lock.Lock()
555
556 if completeOk {
557 t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
558 return
559 }
560 }
561 if !isPrintable(key) {
562 return
563 }
564 if len(t.line) == maxLineLength {
565 return
566 }
567 t.addKeyToLine(key)
568 }
569 return
570}
571
572// addKeyToLine inserts the given key at the current position in the current
573// line.
574func (t *Terminal) addKeyToLine(key rune) {
575 if len(t.line) == cap(t.line) {
576 newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
577 copy(newLine, t.line)
578 t.line = newLine
579 }
580 t.line = t.line[:len(t.line)+1]
581 copy(t.line[t.pos+1:], t.line[t.pos:])
582 t.line[t.pos] = key
583 if t.echo {
584 t.writeLine(t.line[t.pos:])
585 }
586 t.pos++
587 t.moveCursorToPos(t.pos)
588}
589
590func (t *Terminal) writeLine(line []rune) {
591 for len(line) != 0 {
592 remainingOnLine := t.termWidth - t.cursorX
593 todo := len(line)
594 if todo > remainingOnLine {
595 todo = remainingOnLine
596 }
597 t.queue(line[:todo])
598 t.advanceCursor(visualLength(line[:todo]))
599 line = line[todo:]
600 }
601}
602
603// writeWithCRLF writes buf to w but replaces all occurrences of \n with \r\n.
604func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) {
605 for len(buf) > 0 {
606 i := bytes.IndexByte(buf, '\n')
607 todo := len(buf)
608 if i >= 0 {
609 todo = i
610 }
611
612 var nn int
613 nn, err = w.Write(buf[:todo])
614 n += nn
615 if err != nil {
616 return n, err
617 }
618 buf = buf[todo:]
619
620 if i >= 0 {
621 if _, err = w.Write(crlf); err != nil {
622 return n, err
623 }
624 n++
625 buf = buf[1:]
626 }
627 }
628
629 return n, nil
630}
631
632func (t *Terminal) Write(buf []byte) (n int, err error) {
633 t.lock.Lock()
634 defer t.lock.Unlock()
635
636 if t.cursorX == 0 && t.cursorY == 0 {
637 // This is the easy case: there's nothing on the screen that we
638 // have to move out of the way.
639 return writeWithCRLF(t.c, buf)
640 }
641
642 // We have a prompt and possibly user input on the screen. We
643 // have to clear it first.
644 t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
645 t.cursorX = 0
646 t.clearLineToRight()
647
648 for t.cursorY > 0 {
649 t.move(1 /* up */, 0, 0, 0)
650 t.cursorY--
651 t.clearLineToRight()
652 }
653
654 if _, err = t.c.Write(t.outBuf); err != nil {
655 return
656 }
657 t.outBuf = t.outBuf[:0]
658
659 if n, err = writeWithCRLF(t.c, buf); err != nil {
660 return
661 }
662
663 t.writeLine(t.prompt)
664 if t.echo {
665 t.writeLine(t.line)
666 }
667
668 t.moveCursorToPos(t.pos)
669
670 if _, err = t.c.Write(t.outBuf); err != nil {
671 return
672 }
673 t.outBuf = t.outBuf[:0]
674 return
675}
676
677// ReadPassword temporarily changes the prompt and reads a password, without
678// echo, from the terminal.
679func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
680 t.lock.Lock()
681 defer t.lock.Unlock()
682
683 oldPrompt := t.prompt
684 t.prompt = []rune(prompt)
685 t.echo = false
686
687 line, err = t.readLine()
688
689 t.prompt = oldPrompt
690 t.echo = true
691
692 return
693}
694
695// ReadLine returns a line of input from the terminal.
696func (t *Terminal) ReadLine() (line string, err error) {
697 t.lock.Lock()
698 defer t.lock.Unlock()
699
700 return t.readLine()
701}
702
703func (t *Terminal) readLine() (line string, err error) {
704 // t.lock must be held at this point
705
706 if t.cursorX == 0 && t.cursorY == 0 {
707 t.writeLine(t.prompt)
708 t.c.Write(t.outBuf)
709 t.outBuf = t.outBuf[:0]
710 }
711
712 lineIsPasted := t.pasteActive
713
714 for {
715 rest := t.remainder
716 lineOk := false
717 for !lineOk {
718 var key rune
719 key, rest = bytesToKey(rest, t.pasteActive)
720 if key == utf8.RuneError {
721 break
722 }
723 if !t.pasteActive {
724 if key == keyCtrlD {
725 if len(t.line) == 0 {
726 return "", io.EOF
727 }
728 }
729 if key == keyPasteStart {
730 t.pasteActive = true
731 if len(t.line) == 0 {
732 lineIsPasted = true
733 }
734 continue
735 }
736 } else if key == keyPasteEnd {
737 t.pasteActive = false
738 continue
739 }
740 if !t.pasteActive {
741 lineIsPasted = false
742 }
743 line, lineOk = t.handleKey(key)
744 }
745 if len(rest) > 0 {
746 n := copy(t.inBuf[:], rest)
747 t.remainder = t.inBuf[:n]
748 } else {
749 t.remainder = nil
750 }
751 t.c.Write(t.outBuf)
752 t.outBuf = t.outBuf[:0]
753 if lineOk {
754 if t.echo {
755 t.historyIndex = -1
756 t.history.Add(line)
757 }
758 if lineIsPasted {
759 err = ErrPasteIndicator
760 }
761 return
762 }
763
764 // t.remainder is a slice at the beginning of t.inBuf
765 // containing a partial key sequence
766 readBuf := t.inBuf[len(t.remainder):]
767 var n int
768
769 t.lock.Unlock()
770 n, err = t.c.Read(readBuf)
771 t.lock.Lock()
772
773 if err != nil {
774 return
775 }
776
777 t.remainder = t.inBuf[:n+len(t.remainder)]
778 }
779}
780
781// SetPrompt sets the prompt to be used when reading subsequent lines.
782func (t *Terminal) SetPrompt(prompt string) {
783 t.lock.Lock()
784 defer t.lock.Unlock()
785
786 t.prompt = []rune(prompt)
787}
788
789func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
790 // Move cursor to column zero at the start of the line.
791 t.move(t.cursorY, 0, t.cursorX, 0)
792 t.cursorX, t.cursorY = 0, 0
793 t.clearLineToRight()
794 for t.cursorY < numPrevLines {
795 // Move down a line
796 t.move(0, 1, 0, 0)
797 t.cursorY++
798 t.clearLineToRight()
799 }
800 // Move back to beginning.
801 t.move(t.cursorY, 0, 0, 0)
802 t.cursorX, t.cursorY = 0, 0
803
804 t.queue(t.prompt)
805 t.advanceCursor(visualLength(t.prompt))
806 t.writeLine(t.line)
807 t.moveCursorToPos(t.pos)
808}
809
810func (t *Terminal) SetSize(width, height int) error {
811 t.lock.Lock()
812 defer t.lock.Unlock()
813
814 if width == 0 {
815 width = 1
816 }
817
818 oldWidth := t.termWidth
819 t.termWidth, t.termHeight = width, height
820
821 switch {
822 case width == oldWidth:
823 // If the width didn't change then nothing else needs to be
824 // done.
825 return nil
826 case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
827 // If there is nothing on current line and no prompt printed,
828 // just do nothing
829 return nil
830 case width < oldWidth:
831 // Some terminals (e.g. xterm) will truncate lines that were
832 // too long when shinking. Others, (e.g. gnome-terminal) will
833 // attempt to wrap them. For the former, repainting t.maxLine
834 // works great, but that behaviour goes badly wrong in the case
835 // of the latter because they have doubled every full line.
836
837 // We assume that we are working on a terminal that wraps lines
838 // and adjust the cursor position based on every previous line
839 // wrapping and turning into two. This causes the prompt on
840 // xterms to move upwards, which isn't great, but it avoids a
841 // huge mess with gnome-terminal.
842 if t.cursorX >= t.termWidth {
843 t.cursorX = t.termWidth - 1
844 }
845 t.cursorY *= 2
846 t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
847 case width > oldWidth:
848 // If the terminal expands then our position calculations will
849 // be wrong in the future because we think the cursor is
850 // |t.pos| chars into the string, but there will be a gap at
851 // the end of any wrapped line.
852 //
853 // But the position will actually be correct until we move, so
854 // we can move back to the beginning and repaint everything.
855 t.clearAndRepaintLinePlusNPrevious(t.maxLine)
856 }
857
858 _, err := t.c.Write(t.outBuf)
859 t.outBuf = t.outBuf[:0]
860 return err
861}
862
863type pasteIndicatorError struct{}
864
865func (pasteIndicatorError) Error() string {
866 return "terminal: ErrPasteIndicator not correctly handled"
867}
868
869// ErrPasteIndicator may be returned from ReadLine as the error, in addition
870// to valid line data. It indicates that bracketed paste mode is enabled and
871// that the returned line consists only of pasted data. Programs may wish to
872// interpret pasted data more literally than typed data.
873var ErrPasteIndicator = pasteIndicatorError{}
874
875// SetBracketedPasteMode requests that the terminal bracket paste operations
876// with markers. Not all terminals support this but, if it is supported, then
877// enabling this mode will stop any autocomplete callback from running due to
878// pastes. Additionally, any lines that are completely pasted will be returned
879// from ReadLine with the error set to ErrPasteIndicator.
880func (t *Terminal) SetBracketedPasteMode(on bool) {
881 if on {
882 io.WriteString(t.c, "\x1b[?2004h")
883 } else {
884 io.WriteString(t.c, "\x1b[?2004l")
885 }
886}
887
888// stRingBuffer is a ring buffer of strings.
889type stRingBuffer struct {
890 // entries contains max elements.
891 entries []string
892 max int
893 // head contains the index of the element most recently added to the ring.
894 head int
895 // size contains the number of elements in the ring.
896 size int
897}
898
899func (s *stRingBuffer) Add(a string) {
900 if s.entries == nil {
901 const defaultNumEntries = 100
902 s.entries = make([]string, defaultNumEntries)
903 s.max = defaultNumEntries
904 }
905
906 s.head = (s.head + 1) % s.max
907 s.entries[s.head] = a
908 if s.size < s.max {
909 s.size++
910 }
911}
912
913// NthPreviousEntry returns the value passed to the nth previous call to Add.
914// If n is zero then the immediately prior value is returned, if one, then the
915// next most recent, and so on. If such an element doesn't exist then ok is
916// false.
917func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
918 if n >= s.size {
919 return "", false
920 }
921 index := s.head - n
922 if index < 0 {
923 index += s.max
924 }
925 return s.entries[index], true
926}
927
928// readPasswordLine reads from reader until it finds \n or io.EOF.
929// The slice returned does not include the \n.
930// readPasswordLine also ignores any \r it finds.
931func readPasswordLine(reader io.Reader) ([]byte, error) {
932 var buf [1]byte
933 var ret []byte
934
935 for {
936 n, err := reader.Read(buf[:])
937 if n > 0 {
938 switch buf[0] {
939 case '\n':
940 return ret, nil
941 case '\r':
942 // remove \r from passwords on Windows
943 default:
944 ret = append(ret, buf[0])
945 }
946 continue
947 }
948 if err != nil {
949 if err == io.EOF && len(ret) > 0 {
950 return ret, nil
951 }
952 return ret, err
953 }
954 }
955}