You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

terminal.go 23KB

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