1 // 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.
14 // EscapeCodes contains escape sequences that can be written to the terminal in
15 // order to achieve different styles of text.
16 type EscapeCodes struct {
18 Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
20 // Reset all attributes
24 var 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'},
34 Reset: []byte{keyEscape, '[', '0', 'm'},
37 // Terminal contains the state for running a VT100 terminal that is capable of
38 // reading lines of input.
39 type 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)
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.
52 // lock protects the terminal and the state in this object from
53 // concurrent processing of a key press and a Write() call.
59 // line is the current line being entered.
61 // pos is the logical position of the cursor in line
63 // echo is true if local echo is enabled
65 // pasteActive is true iff there is a bracketed paste operation in
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.
73 // maxLine is the greatest value of cursorY so far.
76 termWidth, termHeight int
78 // outBuf contains the terminal data to be sent.
80 // remainder contains the remainder of any partial key sequences after
81 // a read. It aliases into inBuf.
85 // history contains previously entered commands so that they can be
86 // accessed with the up and down keys.
88 // historyIndex stores the currently accessed history entry, where zero
89 // means the immediately previous entry.
91 // When navigating up and down the history it's possible to return to
92 // the incomplete, initial line. That value is stored in
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.
101 func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
103 Escape: &vt100EscapeCodes,
105 prompt: []rune(prompt),
119 keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
136 crlf = []byte{'\r', '\n'}
137 pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
138 pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
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.
143 func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
145 return utf8.RuneError, nil
151 return keyHome, b[1:]
155 return keyBackspace, b[1:]
157 return keyDeleteLine, b[1:]
159 return keyClearScreen, b[1:]
161 return keyDeleteWord, b[1:]
165 if b[0] != keyEscape {
166 if !utf8.FullRune(b) {
167 return utf8.RuneError, b
169 r, l := utf8.DecodeRune(b)
173 if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
178 return keyDown, b[3:]
180 return keyRight, b[3:]
182 return keyLeft, b[3:]
184 return keyHome, b[3:]
190 if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
193 return keyAltRight, b[6:]
195 return keyAltLeft, b[6:]
199 if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
200 return keyPasteStart, b[6:]
203 if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
204 return keyPasteEnd, b[6:]
207 // If we get here then we have a key that we don't recognise, or a
208 // partial sequence. It's not clear how one should find the end of a
209 // sequence without knowing them all, but it seems that [a-zA-Z~] only
210 // appears at the end of a sequence.
211 for i, c := range b[0:] {
212 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
213 return keyUnknown, b[i+1:]
217 return utf8.RuneError, b
220 // queue appends data to the end of t.outBuf
221 func (t *Terminal) queue(data []rune) {
222 t.outBuf = append(t.outBuf, []byte(string(data))...)
225 var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
226 var space = []rune{' '}
228 func isPrintable(key rune) bool {
229 isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
230 return key >= 32 && !isInSurrogateArea
233 // moveCursorToPos appends data to t.outBuf which will move the cursor to the
234 // given, logical position in the text.
235 func (t *Terminal) moveCursorToPos(pos int) {
240 x := visualLength(t.prompt) + pos
261 right = x - t.cursorX
266 t.move(up, down, left, right)
269 func (t *Terminal) move(up, down, left, right int) {
270 movement := make([]rune, 3*(up+down+left+right))
272 for i := 0; i < up; i++ {
278 for i := 0; i < down; i++ {
284 for i := 0; i < left; i++ {
290 for i := 0; i < right; i++ {
300 func (t *Terminal) clearLineToRight() {
301 op := []rune{keyEscape, '[', 'K'}
305 const maxLineLength = 4096
307 func (t *Terminal) setLine(newLine []rune, newPos int) {
311 for i := len(newLine); i < len(t.line); i++ {
314 t.moveCursorToPos(newPos)
320 func (t *Terminal) advanceCursor(places int) {
322 t.cursorY += t.cursorX / t.termWidth
323 if t.cursorY > t.maxLine {
324 t.maxLine = t.cursorY
326 t.cursorX = t.cursorX % t.termWidth
328 if places > 0 && t.cursorX == 0 {
329 // Normally terminals will advance the current position
330 // when writing a character. But that doesn't happen
331 // for the last character in a line. However, when
332 // writing a character (except a new line) that causes
333 // a line wrap, the position will be advanced two
336 // So, if we are stopping at the end of a line, we
337 // need to write a newline so that our cursor can be
338 // advanced to the next line.
339 t.outBuf = append(t.outBuf, '\r', '\n')
343 func (t *Terminal) eraseNPreviousChars(n int) {
352 t.moveCursorToPos(t.pos)
354 copy(t.line[t.pos:], t.line[n+t.pos:])
355 t.line = t.line[:len(t.line)-n]
357 t.writeLine(t.line[t.pos:])
358 for i := 0; i < n; i++ {
362 t.moveCursorToPos(t.pos)
366 // countToLeftWord returns then number of characters from the cursor to the
367 // start of the previous word.
368 func (t *Terminal) countToLeftWord() int {
375 if t.line[pos] != ' ' {
381 if t.line[pos] == ' ' {
391 // countToRightWord returns then number of characters from the cursor to the
392 // start of the next word.
393 func (t *Terminal) countToRightWord() int {
395 for pos < len(t.line) {
396 if t.line[pos] == ' ' {
401 for pos < len(t.line) {
402 if t.line[pos] != ' ' {
410 // visualLength returns the number of visible glyphs in s.
411 func visualLength(runes []rune) int {
415 for _, r := range runes {
418 if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
431 // handleKey processes the given key and, optionally, returns a line of text
432 // that the user has entered.
433 func (t *Terminal) handleKey(key rune) (line string, ok bool) {
434 if t.pasteActive && key != keyEnter {
444 t.eraseNPreviousChars(1)
446 // move left by a word.
447 t.pos -= t.countToLeftWord()
448 t.moveCursorToPos(t.pos)
450 // move right by a word.
451 t.pos += t.countToRightWord()
452 t.moveCursorToPos(t.pos)
458 t.moveCursorToPos(t.pos)
460 if t.pos == len(t.line) {
464 t.moveCursorToPos(t.pos)
470 t.moveCursorToPos(t.pos)
472 if t.pos == len(t.line) {
476 t.moveCursorToPos(t.pos)
478 entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
482 if t.historyIndex == -1 {
483 t.historyPending = string(t.line)
486 runes := []rune(entry)
487 t.setLine(runes, len(runes))
489 switch t.historyIndex {
493 runes := []rune(t.historyPending)
494 t.setLine(runes, len(runes))
497 entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
500 runes := []rune(entry)
501 t.setLine(runes, len(runes))
505 t.moveCursorToPos(len(t.line))
506 t.queue([]rune("\r\n"))
507 line = string(t.line)
515 // Delete zero or more spaces and then one or more characters.
516 t.eraseNPreviousChars(t.countToLeftWord())
518 // Delete everything from the current cursor position to the
520 for i := t.pos; i < len(t.line); i++ {
524 t.line = t.line[:t.pos]
525 t.moveCursorToPos(t.pos)
527 // Erase the character under the current position.
528 // The EOF case when the line is empty is handled in
530 if t.pos < len(t.line) {
532 t.eraseNPreviousChars(1)
535 t.eraseNPreviousChars(t.pos)
537 // Erases the screen and moves the cursor to the home position.
538 t.queue([]rune("\x1b[2J\x1b[H"))
540 t.cursorX, t.cursorY = 0, 0
541 t.advanceCursor(visualLength(t.prompt))
542 t.setLine(t.line, t.pos)
544 if t.AutoCompleteCallback != nil {
545 prefix := string(t.line[:t.pos])
546 suffix := string(t.line[t.pos:])
549 newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
553 t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
557 if !isPrintable(key) {
560 if len(t.line) == maxLineLength {
568 // addKeyToLine inserts the given key at the current position in the current
570 func (t *Terminal) addKeyToLine(key rune) {
571 if len(t.line) == cap(t.line) {
572 newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
573 copy(newLine, t.line)
576 t.line = t.line[:len(t.line)+1]
577 copy(t.line[t.pos+1:], t.line[t.pos:])
580 t.writeLine(t.line[t.pos:])
583 t.moveCursorToPos(t.pos)
586 func (t *Terminal) writeLine(line []rune) {
588 remainingOnLine := t.termWidth - t.cursorX
590 if todo > remainingOnLine {
591 todo = remainingOnLine
594 t.advanceCursor(visualLength(line[:todo]))
599 // writeWithCRLF writes buf to w but replaces all occurrences of \n with \r\n.
600 func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) {
602 i := bytes.IndexByte(buf, '\n')
609 nn, err = w.Write(buf[:todo])
617 if _, err = w.Write(crlf); err != nil {
628 func (t *Terminal) Write(buf []byte) (n int, err error) {
630 defer t.lock.Unlock()
632 if t.cursorX == 0 && t.cursorY == 0 {
633 // This is the easy case: there's nothing on the screen that we
634 // have to move out of the way.
635 return writeWithCRLF(t.c, buf)
638 // We have a prompt and possibly user input on the screen. We
639 // have to clear it first.
640 t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
645 t.move(1 /* up */, 0, 0, 0)
650 if _, err = t.c.Write(t.outBuf); err != nil {
653 t.outBuf = t.outBuf[:0]
655 if n, err = writeWithCRLF(t.c, buf); err != nil {
659 t.writeLine(t.prompt)
664 t.moveCursorToPos(t.pos)
666 if _, err = t.c.Write(t.outBuf); err != nil {
669 t.outBuf = t.outBuf[:0]
673 // ReadPassword temporarily changes the prompt and reads a password, without
674 // echo, from the terminal.
675 func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
677 defer t.lock.Unlock()
679 oldPrompt := t.prompt
680 t.prompt = []rune(prompt)
683 line, err = t.readLine()
691 // ReadLine returns a line of input from the terminal.
692 func (t *Terminal) ReadLine() (line string, err error) {
694 defer t.lock.Unlock()
699 func (t *Terminal) readLine() (line string, err error) {
700 // t.lock must be held at this point
702 if t.cursorX == 0 && t.cursorY == 0 {
703 t.writeLine(t.prompt)
705 t.outBuf = t.outBuf[:0]
708 lineIsPasted := t.pasteActive
715 key, rest = bytesToKey(rest, t.pasteActive)
716 if key == utf8.RuneError {
721 if len(t.line) == 0 {
725 if key == keyPasteStart {
727 if len(t.line) == 0 {
732 } else if key == keyPasteEnd {
733 t.pasteActive = false
739 line, lineOk = t.handleKey(key)
742 n := copy(t.inBuf[:], rest)
743 t.remainder = t.inBuf[:n]
748 t.outBuf = t.outBuf[:0]
755 err = ErrPasteIndicator
760 // t.remainder is a slice at the beginning of t.inBuf
761 // containing a partial key sequence
762 readBuf := t.inBuf[len(t.remainder):]
766 n, err = t.c.Read(readBuf)
773 t.remainder = t.inBuf[:n+len(t.remainder)]
777 // SetPrompt sets the prompt to be used when reading subsequent lines.
778 func (t *Terminal) SetPrompt(prompt string) {
780 defer t.lock.Unlock()
782 t.prompt = []rune(prompt)
785 func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
786 // Move cursor to column zero at the start of the line.
787 t.move(t.cursorY, 0, t.cursorX, 0)
788 t.cursorX, t.cursorY = 0, 0
790 for t.cursorY < numPrevLines {
796 // Move back to beginning.
797 t.move(t.cursorY, 0, 0, 0)
798 t.cursorX, t.cursorY = 0, 0
801 t.advanceCursor(visualLength(t.prompt))
803 t.moveCursorToPos(t.pos)
806 func (t *Terminal) SetSize(width, height int) error {
808 defer t.lock.Unlock()
814 oldWidth := t.termWidth
815 t.termWidth, t.termHeight = width, height
818 case width == oldWidth:
819 // If the width didn't change then nothing else needs to be
822 case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
823 // If there is nothing on current line and no prompt printed,
826 case width < oldWidth:
827 // Some terminals (e.g. xterm) will truncate lines that were
828 // too long when shinking. Others, (e.g. gnome-terminal) will
829 // attempt to wrap them. For the former, repainting t.maxLine
830 // works great, but that behaviour goes badly wrong in the case
831 // of the latter because they have doubled every full line.
833 // We assume that we are working on a terminal that wraps lines
834 // and adjust the cursor position based on every previous line
835 // wrapping and turning into two. This causes the prompt on
836 // xterms to move upwards, which isn't great, but it avoids a
837 // huge mess with gnome-terminal.
838 if t.cursorX >= t.termWidth {
839 t.cursorX = t.termWidth - 1
842 t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
843 case width > oldWidth:
844 // If the terminal expands then our position calculations will
845 // be wrong in the future because we think the cursor is
846 // |t.pos| chars into the string, but there will be a gap at
847 // the end of any wrapped line.
849 // But the position will actually be correct until we move, so
850 // we can move back to the beginning and repaint everything.
851 t.clearAndRepaintLinePlusNPrevious(t.maxLine)
854 _, err := t.c.Write(t.outBuf)
855 t.outBuf = t.outBuf[:0]
859 type pasteIndicatorError struct{}
861 func (pasteIndicatorError) Error() string {
862 return "terminal: ErrPasteIndicator not correctly handled"
865 // ErrPasteIndicator may be returned from ReadLine as the error, in addition
866 // to valid line data. It indicates that bracketed paste mode is enabled and
867 // that the returned line consists only of pasted data. Programs may wish to
868 // interpret pasted data more literally than typed data.
869 var ErrPasteIndicator = pasteIndicatorError{}
871 // SetBracketedPasteMode requests that the terminal bracket paste operations
872 // with markers. Not all terminals support this but, if it is supported, then
873 // enabling this mode will stop any autocomplete callback from running due to
874 // pastes. Additionally, any lines that are completely pasted will be returned
875 // from ReadLine with the error set to ErrPasteIndicator.
876 func (t *Terminal) SetBracketedPasteMode(on bool) {
878 io.WriteString(t.c, "\x1b[?2004h")
880 io.WriteString(t.c, "\x1b[?2004l")
884 // stRingBuffer is a ring buffer of strings.
885 type stRingBuffer struct {
886 // entries contains max elements.
889 // head contains the index of the element most recently added to the ring.
891 // size contains the number of elements in the ring.
895 func (s *stRingBuffer) Add(a string) {
896 if s.entries == nil {
897 const defaultNumEntries = 100
898 s.entries = make([]string, defaultNumEntries)
899 s.max = defaultNumEntries
902 s.head = (s.head + 1) % s.max
903 s.entries[s.head] = a
909 // NthPreviousEntry returns the value passed to the nth previous call to Add.
910 // If n is zero then the immediately prior value is returned, if one, then the
911 // next most recent, and so on. If such an element doesn't exist then ok is
913 func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
921 return s.entries[index], true
924 // readPasswordLine reads from reader until it finds \n or io.EOF.
925 // The slice returned does not include the \n.
926 // readPasswordLine also ignores any \r it finds.
927 func readPasswordLine(reader io.Reader) ([]byte, error) {
932 n, err := reader.Read(buf[:])
938 // remove \r from passwords on Windows
940 ret = append(ret, buf[0])
945 if err == io.EOF && len(ret) > 0 {