terminal.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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.
  4. package terminal
  5. import (
  6. "io"
  7. "sync"
  8. "unicode/utf8"
  9. )
  10. // EscapeCodes contains escape sequences that can be written to the terminal in
  11. // order to achieve different styles of text.
  12. type EscapeCodes struct {
  13. // Foreground colors
  14. Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
  15. // Reset all attributes
  16. Reset []byte
  17. }
  18. var vt100EscapeCodes = EscapeCodes{
  19. Black: []byte{keyEscape, '[', '3', '0', 'm'},
  20. Red: []byte{keyEscape, '[', '3', '1', 'm'},
  21. Green: []byte{keyEscape, '[', '3', '2', 'm'},
  22. Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
  23. Blue: []byte{keyEscape, '[', '3', '4', 'm'},
  24. Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
  25. Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
  26. White: []byte{keyEscape, '[', '3', '7', 'm'},
  27. Reset: []byte{keyEscape, '[', '0', 'm'},
  28. }
  29. // Terminal contains the state for running a VT100 terminal that is capable of
  30. // reading lines of input.
  31. type Terminal struct {
  32. // AutoCompleteCallback, if non-null, is called for each keypress with
  33. // the full input line and the current position of the cursor (in
  34. // bytes, as an index into |line|). If it returns ok=false, the key
  35. // press is processed normally. Otherwise it returns a replacement line
  36. // and the new cursor position.
  37. AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)
  38. // Escape contains a pointer to the escape codes for this terminal.
  39. // It's always a valid pointer, although the escape codes themselves
  40. // may be empty if the terminal doesn't support them.
  41. Escape *EscapeCodes
  42. // lock protects the terminal and the state in this object from
  43. // concurrent processing of a key press and a Write() call.
  44. lock sync.Mutex
  45. c io.ReadWriter
  46. prompt string
  47. // line is the current line being entered.
  48. line []rune
  49. // pos is the logical position of the cursor in line
  50. pos int
  51. // echo is true if local echo is enabled
  52. echo bool
  53. // cursorX contains the current X value of the cursor where the left
  54. // edge is 0. cursorY contains the row number where the first row of
  55. // the current line is 0.
  56. cursorX, cursorY int
  57. // maxLine is the greatest value of cursorY so far.
  58. maxLine int
  59. termWidth, termHeight int
  60. // outBuf contains the terminal data to be sent.
  61. outBuf []byte
  62. // remainder contains the remainder of any partial key sequences after
  63. // a read. It aliases into inBuf.
  64. remainder []byte
  65. inBuf [256]byte
  66. // history contains previously entered commands so that they can be
  67. // accessed with the up and down keys.
  68. history stRingBuffer
  69. // historyIndex stores the currently accessed history entry, where zero
  70. // means the immediately previous entry.
  71. historyIndex int
  72. // When navigating up and down the history it's possible to return to
  73. // the incomplete, initial line. That value is stored in
  74. // historyPending.
  75. historyPending string
  76. }
  77. // NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
  78. // a local terminal, that terminal must first have been put into raw mode.
  79. // prompt is a string that is written at the start of each input line (i.e.
  80. // "> ").
  81. func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
  82. return &Terminal{
  83. Escape: &vt100EscapeCodes,
  84. c: c,
  85. prompt: prompt,
  86. termWidth: 80,
  87. termHeight: 24,
  88. echo: true,
  89. historyIndex: -1,
  90. }
  91. }
  92. const (
  93. keyCtrlD = 4
  94. keyCtrlU = 21
  95. keyEnter = '\r'
  96. keyEscape = 27
  97. keyBackspace = 127
  98. keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
  99. keyUp
  100. keyDown
  101. keyLeft
  102. keyRight
  103. keyAltLeft
  104. keyAltRight
  105. keyHome
  106. keyEnd
  107. keyDeleteWord
  108. keyDeleteLine
  109. keyClearScreen
  110. )
  111. // bytesToKey tries to parse a key sequence from b. If successful, it returns
  112. // the key and the remainder of the input. Otherwise it returns utf8.RuneError.
  113. func bytesToKey(b []byte) (rune, []byte) {
  114. if len(b) == 0 {
  115. return utf8.RuneError, nil
  116. }
  117. switch b[0] {
  118. case 1: // ^A
  119. return keyHome, b[1:]
  120. case 5: // ^E
  121. return keyEnd, b[1:]
  122. case 8: // ^H
  123. return keyBackspace, b[1:]
  124. case 11: // ^K
  125. return keyDeleteLine, b[1:]
  126. case 12: // ^L
  127. return keyClearScreen, b[1:]
  128. case 23: // ^W
  129. return keyDeleteWord, b[1:]
  130. }
  131. if b[0] != keyEscape {
  132. if !utf8.FullRune(b) {
  133. return utf8.RuneError, b
  134. }
  135. r, l := utf8.DecodeRune(b)
  136. return r, b[l:]
  137. }
  138. if len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
  139. switch b[2] {
  140. case 'A':
  141. return keyUp, b[3:]
  142. case 'B':
  143. return keyDown, b[3:]
  144. case 'C':
  145. return keyRight, b[3:]
  146. case 'D':
  147. return keyLeft, b[3:]
  148. }
  149. }
  150. if len(b) >= 3 && b[0] == keyEscape && b[1] == 'O' {
  151. switch b[2] {
  152. case 'H':
  153. return keyHome, b[3:]
  154. case 'F':
  155. return keyEnd, b[3:]
  156. }
  157. }
  158. if len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
  159. switch b[5] {
  160. case 'C':
  161. return keyAltRight, b[6:]
  162. case 'D':
  163. return keyAltLeft, b[6:]
  164. }
  165. }
  166. // If we get here then we have a key that we don't recognise, or a
  167. // partial sequence. It's not clear how one should find the end of a
  168. // sequence without knowing them all, but it seems that [a-zA-Z] only
  169. // appears at the end of a sequence.
  170. for i, c := range b[0:] {
  171. if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
  172. return keyUnknown, b[i+1:]
  173. }
  174. }
  175. return utf8.RuneError, b
  176. }
  177. // queue appends data to the end of t.outBuf
  178. func (t *Terminal) queue(data []rune) {
  179. t.outBuf = append(t.outBuf, []byte(string(data))...)
  180. }
  181. var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
  182. var space = []rune{' '}
  183. func isPrintable(key rune) bool {
  184. isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
  185. return key >= 32 && !isInSurrogateArea
  186. }
  187. // moveCursorToPos appends data to t.outBuf which will move the cursor to the
  188. // given, logical position in the text.
  189. func (t *Terminal) moveCursorToPos(pos int) {
  190. if !t.echo {
  191. return
  192. }
  193. x := len(t.prompt) + pos
  194. y := x / t.termWidth
  195. x = x % t.termWidth
  196. up := 0
  197. if y < t.cursorY {
  198. up = t.cursorY - y
  199. }
  200. down := 0
  201. if y > t.cursorY {
  202. down = y - t.cursorY
  203. }
  204. left := 0
  205. if x < t.cursorX {
  206. left = t.cursorX - x
  207. }
  208. right := 0
  209. if x > t.cursorX {
  210. right = x - t.cursorX
  211. }
  212. t.cursorX = x
  213. t.cursorY = y
  214. t.move(up, down, left, right)
  215. }
  216. func (t *Terminal) move(up, down, left, right int) {
  217. movement := make([]rune, 3*(up+down+left+right))
  218. m := movement
  219. for i := 0; i < up; i++ {
  220. m[0] = keyEscape
  221. m[1] = '['
  222. m[2] = 'A'
  223. m = m[3:]
  224. }
  225. for i := 0; i < down; i++ {
  226. m[0] = keyEscape
  227. m[1] = '['
  228. m[2] = 'B'
  229. m = m[3:]
  230. }
  231. for i := 0; i < left; i++ {
  232. m[0] = keyEscape
  233. m[1] = '['
  234. m[2] = 'D'
  235. m = m[3:]
  236. }
  237. for i := 0; i < right; i++ {
  238. m[0] = keyEscape
  239. m[1] = '['
  240. m[2] = 'C'
  241. m = m[3:]
  242. }
  243. t.queue(movement)
  244. }
  245. func (t *Terminal) clearLineToRight() {
  246. op := []rune{keyEscape, '[', 'K'}
  247. t.queue(op)
  248. }
  249. const maxLineLength = 4096
  250. func (t *Terminal) setLine(newLine []rune, newPos int) {
  251. if t.echo {
  252. t.moveCursorToPos(0)
  253. t.writeLine(newLine)
  254. for i := len(newLine); i < len(t.line); i++ {
  255. t.writeLine(space)
  256. }
  257. t.moveCursorToPos(newPos)
  258. }
  259. t.line = newLine
  260. t.pos = newPos
  261. }
  262. func (t *Terminal) eraseNPreviousChars(n int) {
  263. if n == 0 {
  264. return
  265. }
  266. if t.pos < n {
  267. n = t.pos
  268. }
  269. t.pos -= n
  270. t.moveCursorToPos(t.pos)
  271. copy(t.line[t.pos:], t.line[n+t.pos:])
  272. t.line = t.line[:len(t.line)-n]
  273. if t.echo {
  274. t.writeLine(t.line[t.pos:])
  275. for i := 0; i < n; i++ {
  276. t.queue(space)
  277. }
  278. t.cursorX += n
  279. t.moveCursorToPos(t.pos)
  280. }
  281. }
  282. // countToLeftWord returns then number of characters from the cursor to the
  283. // start of the previous word.
  284. func (t *Terminal) countToLeftWord() int {
  285. if t.pos == 0 {
  286. return 0
  287. }
  288. pos := t.pos - 1
  289. for pos > 0 {
  290. if t.line[pos] != ' ' {
  291. break
  292. }
  293. pos--
  294. }
  295. for pos > 0 {
  296. if t.line[pos] == ' ' {
  297. pos++
  298. break
  299. }
  300. pos--
  301. }
  302. return t.pos - pos
  303. }
  304. // countToRightWord returns then number of characters from the cursor to the
  305. // start of the next word.
  306. func (t *Terminal) countToRightWord() int {
  307. pos := t.pos
  308. for pos < len(t.line) {
  309. if t.line[pos] == ' ' {
  310. break
  311. }
  312. pos++
  313. }
  314. for pos < len(t.line) {
  315. if t.line[pos] != ' ' {
  316. break
  317. }
  318. pos++
  319. }
  320. return pos - t.pos
  321. }
  322. // handleKey processes the given key and, optionally, returns a line of text
  323. // that the user has entered.
  324. func (t *Terminal) handleKey(key rune) (line string, ok bool) {
  325. switch key {
  326. case keyBackspace:
  327. if t.pos == 0 {
  328. return
  329. }
  330. t.eraseNPreviousChars(1)
  331. case keyAltLeft:
  332. // move left by a word.
  333. t.pos -= t.countToLeftWord()
  334. t.moveCursorToPos(t.pos)
  335. case keyAltRight:
  336. // move right by a word.
  337. t.pos += t.countToRightWord()
  338. t.moveCursorToPos(t.pos)
  339. case keyLeft:
  340. if t.pos == 0 {
  341. return
  342. }
  343. t.pos--
  344. t.moveCursorToPos(t.pos)
  345. case keyRight:
  346. if t.pos == len(t.line) {
  347. return
  348. }
  349. t.pos++
  350. t.moveCursorToPos(t.pos)
  351. case keyHome:
  352. if t.pos == 0 {
  353. return
  354. }
  355. t.pos = 0
  356. t.moveCursorToPos(t.pos)
  357. case keyEnd:
  358. if t.pos == len(t.line) {
  359. return
  360. }
  361. t.pos = len(t.line)
  362. t.moveCursorToPos(t.pos)
  363. case keyUp:
  364. entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
  365. if !ok {
  366. return "", false
  367. }
  368. if t.historyIndex == -1 {
  369. t.historyPending = string(t.line)
  370. }
  371. t.historyIndex++
  372. runes := []rune(entry)
  373. t.setLine(runes, len(runes))
  374. case keyDown:
  375. switch t.historyIndex {
  376. case -1:
  377. return
  378. case 0:
  379. runes := []rune(t.historyPending)
  380. t.setLine(runes, len(runes))
  381. t.historyIndex--
  382. default:
  383. entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
  384. if ok {
  385. t.historyIndex--
  386. runes := []rune(entry)
  387. t.setLine(runes, len(runes))
  388. }
  389. }
  390. case keyEnter:
  391. t.moveCursorToPos(len(t.line))
  392. t.queue([]rune("\r\n"))
  393. line = string(t.line)
  394. ok = true
  395. t.line = t.line[:0]
  396. t.pos = 0
  397. t.cursorX = 0
  398. t.cursorY = 0
  399. t.maxLine = 0
  400. case keyDeleteWord:
  401. // Delete zero or more spaces and then one or more characters.
  402. t.eraseNPreviousChars(t.countToLeftWord())
  403. case keyDeleteLine:
  404. // Delete everything from the current cursor position to the
  405. // end of line.
  406. for i := t.pos; i < len(t.line); i++ {
  407. t.queue(space)
  408. t.cursorX++
  409. }
  410. t.line = t.line[:t.pos]
  411. t.moveCursorToPos(t.pos)
  412. case keyCtrlD:
  413. // Erase the character under the current position.
  414. // The EOF case when the line is empty is handled in
  415. // readLine().
  416. if t.pos < len(t.line) {
  417. t.pos++
  418. t.eraseNPreviousChars(1)
  419. }
  420. case keyCtrlU:
  421. t.eraseNPreviousChars(t.pos)
  422. case keyClearScreen:
  423. // Erases the screen and moves the cursor to the home position.
  424. t.queue([]rune("\x1b[2J\x1b[H"))
  425. t.queue([]rune(t.prompt))
  426. t.cursorX = len(t.prompt)
  427. t.cursorY = 0
  428. t.setLine(t.line, t.pos)
  429. default:
  430. if t.AutoCompleteCallback != nil {
  431. prefix := string(t.line[:t.pos])
  432. suffix := string(t.line[t.pos:])
  433. t.lock.Unlock()
  434. newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
  435. t.lock.Lock()
  436. if completeOk {
  437. t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
  438. return
  439. }
  440. }
  441. if !isPrintable(key) {
  442. return
  443. }
  444. if len(t.line) == maxLineLength {
  445. return
  446. }
  447. if len(t.line) == cap(t.line) {
  448. newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
  449. copy(newLine, t.line)
  450. t.line = newLine
  451. }
  452. t.line = t.line[:len(t.line)+1]
  453. copy(t.line[t.pos+1:], t.line[t.pos:])
  454. t.line[t.pos] = key
  455. if t.echo {
  456. t.writeLine(t.line[t.pos:])
  457. }
  458. t.pos++
  459. t.moveCursorToPos(t.pos)
  460. }
  461. return
  462. }
  463. func (t *Terminal) writeLine(line []rune) {
  464. for len(line) != 0 {
  465. remainingOnLine := t.termWidth - t.cursorX
  466. todo := len(line)
  467. if todo > remainingOnLine {
  468. todo = remainingOnLine
  469. }
  470. t.queue(line[:todo])
  471. t.cursorX += todo
  472. line = line[todo:]
  473. if t.cursorX == t.termWidth {
  474. t.cursorX = 0
  475. t.cursorY++
  476. if t.cursorY > t.maxLine {
  477. t.maxLine = t.cursorY
  478. }
  479. }
  480. }
  481. }
  482. func (t *Terminal) Write(buf []byte) (n int, err error) {
  483. t.lock.Lock()
  484. defer t.lock.Unlock()
  485. if t.cursorX == 0 && t.cursorY == 0 {
  486. // This is the easy case: there's nothing on the screen that we
  487. // have to move out of the way.
  488. return t.c.Write(buf)
  489. }
  490. // We have a prompt and possibly user input on the screen. We
  491. // have to clear it first.
  492. t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
  493. t.cursorX = 0
  494. t.clearLineToRight()
  495. for t.cursorY > 0 {
  496. t.move(1 /* up */, 0, 0, 0)
  497. t.cursorY--
  498. t.clearLineToRight()
  499. }
  500. if _, err = t.c.Write(t.outBuf); err != nil {
  501. return
  502. }
  503. t.outBuf = t.outBuf[:0]
  504. if n, err = t.c.Write(buf); err != nil {
  505. return
  506. }
  507. t.queue([]rune(t.prompt))
  508. chars := len(t.prompt)
  509. if t.echo {
  510. t.queue(t.line)
  511. chars += len(t.line)
  512. }
  513. t.cursorX = chars % t.termWidth
  514. t.cursorY = chars / t.termWidth
  515. t.moveCursorToPos(t.pos)
  516. if _, err = t.c.Write(t.outBuf); err != nil {
  517. return
  518. }
  519. t.outBuf = t.outBuf[:0]
  520. return
  521. }
  522. // ReadPassword temporarily changes the prompt and reads a password, without
  523. // echo, from the terminal.
  524. func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
  525. t.lock.Lock()
  526. defer t.lock.Unlock()
  527. oldPrompt := t.prompt
  528. t.prompt = prompt
  529. t.echo = false
  530. line, err = t.readLine()
  531. t.prompt = oldPrompt
  532. t.echo = true
  533. return
  534. }
  535. // ReadLine returns a line of input from the terminal.
  536. func (t *Terminal) ReadLine() (line string, err error) {
  537. t.lock.Lock()
  538. defer t.lock.Unlock()
  539. return t.readLine()
  540. }
  541. func (t *Terminal) readLine() (line string, err error) {
  542. // t.lock must be held at this point
  543. if t.cursorX == 0 && t.cursorY == 0 {
  544. t.writeLine([]rune(t.prompt))
  545. t.c.Write(t.outBuf)
  546. t.outBuf = t.outBuf[:0]
  547. }
  548. for {
  549. rest := t.remainder
  550. lineOk := false
  551. for !lineOk {
  552. var key rune
  553. key, rest = bytesToKey(rest)
  554. if key == utf8.RuneError {
  555. break
  556. }
  557. if key == keyCtrlD {
  558. if len(t.line) == 0 {
  559. return "", io.EOF
  560. }
  561. }
  562. line, lineOk = t.handleKey(key)
  563. }
  564. if len(rest) > 0 {
  565. n := copy(t.inBuf[:], rest)
  566. t.remainder = t.inBuf[:n]
  567. } else {
  568. t.remainder = nil
  569. }
  570. t.c.Write(t.outBuf)
  571. t.outBuf = t.outBuf[:0]
  572. if lineOk {
  573. if t.echo {
  574. t.historyIndex = -1
  575. t.history.Add(line)
  576. }
  577. return
  578. }
  579. // t.remainder is a slice at the beginning of t.inBuf
  580. // containing a partial key sequence
  581. readBuf := t.inBuf[len(t.remainder):]
  582. var n int
  583. t.lock.Unlock()
  584. n, err = t.c.Read(readBuf)
  585. t.lock.Lock()
  586. if err != nil {
  587. return
  588. }
  589. t.remainder = t.inBuf[:n+len(t.remainder)]
  590. }
  591. panic("unreachable") // for Go 1.0.
  592. }
  593. // SetPrompt sets the prompt to be used when reading subsequent lines.
  594. func (t *Terminal) SetPrompt(prompt string) {
  595. t.lock.Lock()
  596. defer t.lock.Unlock()
  597. t.prompt = prompt
  598. }
  599. func (t *Terminal) SetSize(width, height int) {
  600. t.lock.Lock()
  601. defer t.lock.Unlock()
  602. t.termWidth, t.termHeight = width, height
  603. }
  604. // stRingBuffer is a ring buffer of strings.
  605. type stRingBuffer struct {
  606. // entries contains max elements.
  607. entries []string
  608. max int
  609. // head contains the index of the element most recently added to the ring.
  610. head int
  611. // size contains the number of elements in the ring.
  612. size int
  613. }
  614. func (s *stRingBuffer) Add(a string) {
  615. if s.entries == nil {
  616. const defaultNumEntries = 100
  617. s.entries = make([]string, defaultNumEntries)
  618. s.max = defaultNumEntries
  619. }
  620. s.head = (s.head + 1) % s.max
  621. s.entries[s.head] = a
  622. if s.size < s.max {
  623. s.size++
  624. }
  625. }
  626. // NthPreviousEntry returns the value passed to the nth previous call to Add.
  627. // If n is zero then the immediately prior value is returned, if one, then the
  628. // next most recent, and so on. If such an element doesn't exist then ok is
  629. // false.
  630. func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
  631. if n >= s.size {
  632. return "", false
  633. }
  634. index := s.head - n
  635. if index < 0 {
  636. index += s.max
  637. }
  638. return s.entries[index], true
  639. }