terminal.go 22 KB

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