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
135
var pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
136
var pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
138
// bytesToKey tries to parse a key sequence from b. If successful, it returns
139
// the key and the remainder of the input. Otherwise it returns utf8.RuneError.
140
func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
142
return utf8.RuneError, nil
148
return keyHome, b[1:]
152
return keyBackspace, b[1:]
154
return keyDeleteLine, b[1:]
156
return keyClearScreen, b[1:]
158
return keyDeleteWord, b[1:]
162
if b[0] != keyEscape {
163
if !utf8.FullRune(b) {
164
return utf8.RuneError, b
166
r, l := utf8.DecodeRune(b)
170
if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
175
return keyDown, b[3:]
177
return keyRight, b[3:]
179
return keyLeft, b[3:]
181
return keyHome, b[3:]
187
if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
190
return keyAltRight, b[6:]
192
return keyAltLeft, b[6:]
196
if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
197
return keyPasteStart, b[6:]
200
if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
201
return keyPasteEnd, b[6:]
204
// If we get here then we have a key that we don't recognise, or a
205
// partial sequence. It's not clear how one should find the end of a
206
// sequence without knowing them all, but it seems that [a-zA-Z~] only
207
// appears at the end of a sequence.
208
for i, c := range b[0:] {
209
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
210
return keyUnknown, b[i+1:]
214
return utf8.RuneError, b
217
// queue appends data to the end of t.outBuf
218
func (t *Terminal) queue(data []rune) {
219
t.outBuf = append(t.outBuf, []byte(string(data))...)
222
var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
223
var space = []rune{' '}
225
func isPrintable(key rune) bool {
226
isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
227
return key >= 32 && !isInSurrogateArea
230
// moveCursorToPos appends data to t.outBuf which will move the cursor to the
231
// given, logical position in the text.
232
func (t *Terminal) moveCursorToPos(pos int) {
237
x := visualLength(t.prompt) + pos
258
right = x - t.cursorX
263
t.move(up, down, left, right)
266
func (t *Terminal) move(up, down, left, right int) {
267
movement := make([]rune, 3*(up+down+left+right))
269
for i := 0; i < up; i++ {
275
for i := 0; i < down; i++ {
281
for i := 0; i < left; i++ {
287
for i := 0; i < right; i++ {
297
func (t *Terminal) clearLineToRight() {
298
op := []rune{keyEscape, '[', 'K'}
302
const maxLineLength = 4096
304
func (t *Terminal) setLine(newLine []rune, newPos int) {
308
for i := len(newLine); i < len(t.line); i++ {
311
t.moveCursorToPos(newPos)
317
func (t *Terminal) advanceCursor(places int) {
319
t.cursorY += t.cursorX / t.termWidth
320
if t.cursorY > t.maxLine {
321
t.maxLine = t.cursorY
323
t.cursorX = t.cursorX % t.termWidth
325
if places > 0 && t.cursorX == 0 {
326
// Normally terminals will advance the current position
327
// when writing a character. But that doesn't happen
328
// for the last character in a line. However, when
329
// writing a character (except a new line) that causes
330
// a line wrap, the position will be advanced two
333
// So, if we are stopping at the end of a line, we
334
// need to write a newline so that our cursor can be
335
// advanced to the next line.
336
t.outBuf = append(t.outBuf, '\n')
340
func (t *Terminal) eraseNPreviousChars(n int) {
349
t.moveCursorToPos(t.pos)
351
copy(t.line[t.pos:], t.line[n+t.pos:])
352
t.line = t.line[:len(t.line)-n]
354
t.writeLine(t.line[t.pos:])
355
for i := 0; i < n; i++ {
359
t.moveCursorToPos(t.pos)
363
// countToLeftWord returns then number of characters from the cursor to the
364
// start of the previous word.
365
func (t *Terminal) countToLeftWord() int {
372
if t.line[pos] != ' ' {
378
if t.line[pos] == ' ' {
388
// countToRightWord returns then number of characters from the cursor to the
389
// start of the next word.
390
func (t *Terminal) countToRightWord() int {
392
for pos < len(t.line) {
393
if t.line[pos] == ' ' {
398
for pos < len(t.line) {
399
if t.line[pos] != ' ' {
407
// visualLength returns the number of visible glyphs in s.
408
func visualLength(runes []rune) int {
412
for _, r := range runes {
415
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
428
// handleKey processes the given key and, optionally, returns a line of text
429
// that the user has entered.
430
func (t *Terminal) handleKey(key rune) (line string, ok bool) {
431
if t.pasteActive && key != keyEnter {
441
t.eraseNPreviousChars(1)
443
// move left by a word.
444
t.pos -= t.countToLeftWord()
445
t.moveCursorToPos(t.pos)
447
// move right by a word.
448
t.pos += t.countToRightWord()
449
t.moveCursorToPos(t.pos)
455
t.moveCursorToPos(t.pos)
457
if t.pos == len(t.line) {
461
t.moveCursorToPos(t.pos)
467
t.moveCursorToPos(t.pos)
469
if t.pos == len(t.line) {
473
t.moveCursorToPos(t.pos)
475
entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
479
if t.historyIndex == -1 {
480
t.historyPending = string(t.line)
483
runes := []rune(entry)
484
t.setLine(runes, len(runes))
486
switch t.historyIndex {
490
runes := []rune(t.historyPending)
491
t.setLine(runes, len(runes))
494
entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
497
runes := []rune(entry)
498
t.setLine(runes, len(runes))
502
t.moveCursorToPos(len(t.line))
503
t.queue([]rune("\r\n"))
504
line = string(t.line)
512
// Delete zero or more spaces and then one or more characters.
513
t.eraseNPreviousChars(t.countToLeftWord())
515
// Delete everything from the current cursor position to the
517
for i := t.pos; i < len(t.line); i++ {
521
t.line = t.line[:t.pos]
522
t.moveCursorToPos(t.pos)
524
// Erase the character under the current position.
525
// The EOF case when the line is empty is handled in
527
if t.pos < len(t.line) {
529
t.eraseNPreviousChars(1)
532
t.eraseNPreviousChars(t.pos)
534
// Erases the screen and moves the cursor to the home position.
535
t.queue([]rune("\x1b[2J\x1b[H"))
537
t.cursorX, t.cursorY = 0, 0
538
t.advanceCursor(visualLength(t.prompt))
539
t.setLine(t.line, t.pos)
541
if t.AutoCompleteCallback != nil {
542
prefix := string(t.line[:t.pos])
543
suffix := string(t.line[t.pos:])
546
newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
550
t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
554
if !isPrintable(key) {
557
if len(t.line) == maxLineLength {
565
// addKeyToLine inserts the given key at the current position in the current
567
func (t *Terminal) addKeyToLine(key rune) {
568
if len(t.line) == cap(t.line) {
569
newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
570
copy(newLine, t.line)
573
t.line = t.line[:len(t.line)+1]
574
copy(t.line[t.pos+1:], t.line[t.pos:])
577
t.writeLine(t.line[t.pos:])
580
t.moveCursorToPos(t.pos)
583
func (t *Terminal) writeLine(line []rune) {
585
remainingOnLine := t.termWidth - t.cursorX
587
if todo > remainingOnLine {
588
todo = remainingOnLine
591
t.advanceCursor(visualLength(line[:todo]))
596
func (t *Terminal) Write(buf []byte) (n int, err error) {
598
defer t.lock.Unlock()
600
if t.cursorX == 0 && t.cursorY == 0 {
601
// This is the easy case: there's nothing on the screen that we
602
// have to move out of the way.
603
return t.c.Write(buf)
606
// We have a prompt and possibly user input on the screen. We
607
// have to clear it first.
608
t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
613
t.move(1 /* up */, 0, 0, 0)
618
if _, err = t.c.Write(t.outBuf); err != nil {
621
t.outBuf = t.outBuf[:0]
623
if n, err = t.c.Write(buf); err != nil {
627
t.writeLine(t.prompt)
632
t.moveCursorToPos(t.pos)
634
if _, err = t.c.Write(t.outBuf); err != nil {
637
t.outBuf = t.outBuf[:0]
641
// ReadPassword temporarily changes the prompt and reads a password, without
642
// echo, from the terminal.
643
func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
645
defer t.lock.Unlock()
647
oldPrompt := t.prompt
648
t.prompt = []rune(prompt)
651
line, err = t.readLine()
659
// ReadLine returns a line of input from the terminal.
660
func (t *Terminal) ReadLine() (line string, err error) {
662
defer t.lock.Unlock()
667
func (t *Terminal) readLine() (line string, err error) {
668
// t.lock must be held at this point
670
if t.cursorX == 0 && t.cursorY == 0 {
671
t.writeLine(t.prompt)
673
t.outBuf = t.outBuf[:0]
676
lineIsPasted := t.pasteActive
683
key, rest = bytesToKey(rest, t.pasteActive)
684
if key == utf8.RuneError {
689
if len(t.line) == 0 {
693
if key == keyPasteStart {
695
if len(t.line) == 0 {
700
} else if key == keyPasteEnd {
701
t.pasteActive = false
707
line, lineOk = t.handleKey(key)
710
n := copy(t.inBuf[:], rest)
711
t.remainder = t.inBuf[:n]
716
t.outBuf = t.outBuf[:0]
723
err = ErrPasteIndicator
728
// t.remainder is a slice at the beginning of t.inBuf
729
// containing a partial key sequence
730
readBuf := t.inBuf[len(t.remainder):]
734
n, err = t.c.Read(readBuf)
741
t.remainder = t.inBuf[:n+len(t.remainder)]
744
panic("unreachable") // for Go 1.0.
747
// SetPrompt sets the prompt to be used when reading subsequent lines.
748
func (t *Terminal) SetPrompt(prompt string) {
750
defer t.lock.Unlock()
752
t.prompt = []rune(prompt)
755
func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
756
// Move cursor to column zero at the start of the line.
757
t.move(t.cursorY, 0, t.cursorX, 0)
758
t.cursorX, t.cursorY = 0, 0
760
for t.cursorY < numPrevLines {
766
// Move back to beginning.
767
t.move(t.cursorY, 0, 0, 0)
768
t.cursorX, t.cursorY = 0, 0
771
t.advanceCursor(visualLength(t.prompt))
773
t.moveCursorToPos(t.pos)
776
func (t *Terminal) SetSize(width, height int) error {
778
defer t.lock.Unlock()
784
oldWidth := t.termWidth
785
t.termWidth, t.termHeight = width, height
788
case width == oldWidth:
789
// If the width didn't change then nothing else needs to be
792
case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
793
// If there is nothing on current line and no prompt printed,
796
case width < oldWidth:
797
// Some terminals (e.g. xterm) will truncate lines that were
798
// too long when shinking. Others, (e.g. gnome-terminal) will
799
// attempt to wrap them. For the former, repainting t.maxLine
800
// works great, but that behaviour goes badly wrong in the case
801
// of the latter because they have doubled every full line.
803
// We assume that we are working on a terminal that wraps lines
804
// and adjust the cursor position based on every previous line
805
// wrapping and turning into two. This causes the prompt on
806
// xterms to move upwards, which isn't great, but it avoids a
807
// huge mess with gnome-terminal.
808
if t.cursorX >= t.termWidth {
809
t.cursorX = t.termWidth - 1
812
t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
813
case width > oldWidth:
814
// If the terminal expands then our position calculations will
815
// be wrong in the future because we think the cursor is
816
// |t.pos| chars into the string, but there will be a gap at
817
// the end of any wrapped line.
819
// But the position will actually be correct until we move, so
820
// we can move back to the beginning and repaint everything.
821
t.clearAndRepaintLinePlusNPrevious(t.maxLine)
824
_, err := t.c.Write(t.outBuf)
825
t.outBuf = t.outBuf[:0]
829
type pasteIndicatorError struct{}
831
func (pasteIndicatorError) Error() string {
832
return "terminal: ErrPasteIndicator not correctly handled"
835
// ErrPasteIndicator may be returned from ReadLine as the error, in addition
836
// to valid line data. It indicates that bracketed paste mode is enabled and
837
// that the returned line consists only of pasted data. Programs may wish to
838
// interpret pasted data more literally than typed data.
839
var ErrPasteIndicator = pasteIndicatorError{}
841
// SetBracketedPasteMode requests that the terminal bracket paste operations
842
// with markers. Not all terminals support this but, if it is supported, then
843
// enabling this mode will stop any autocomplete callback from running due to
844
// pastes. Additionally, any lines that are completely pasted will be returned
845
// from ReadLine with the error set to ErrPasteIndicator.
846
func (t *Terminal) SetBracketedPasteMode(on bool) {
848
io.WriteString(t.c, "\x1b[?2004h")
850
io.WriteString(t.c, "\x1b[?2004l")
854
// stRingBuffer is a ring buffer of strings.
855
type stRingBuffer struct {
856
// entries contains max elements.
859
// head contains the index of the element most recently added to the ring.
861
// size contains the number of elements in the ring.
865
func (s *stRingBuffer) Add(a string) {
866
if s.entries == nil {
867
const defaultNumEntries = 100
868
s.entries = make([]string, defaultNumEntries)
869
s.max = defaultNumEntries
872
s.head = (s.head + 1) % s.max
873
s.entries[s.head] = a
879
// NthPreviousEntry returns the value passed to the nth previous call to Add.
880
// If n is zero then the immediately prior value is returned, if one, then the
881
// next most recent, and so on. If such an element doesn't exist then ok is
883
func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
891
return s.entries[index], true