terminal.go 22 KB

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