terminal.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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 []rune
  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: []rune(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 := visualLength(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) advanceCursor(places int) {
  263. t.cursorX += places
  264. t.cursorY += t.cursorX / t.termWidth
  265. if t.cursorY > t.maxLine {
  266. t.maxLine = t.cursorY
  267. }
  268. t.cursorX = t.cursorX % t.termWidth
  269. if places > 0 && t.cursorX == 0 {
  270. // Normally terminals will advance the current position
  271. // when writing a character. But that doesn't happen
  272. // for the last character in a line. However, when
  273. // writing a character (except a new line) that causes
  274. // a line wrap, the position will be advanced two
  275. // places.
  276. //
  277. // So, if we are stopping at the end of a line, we
  278. // need to write a newline so that our cursor can be
  279. // advanced to the next line.
  280. t.outBuf = append(t.outBuf, '\n')
  281. }
  282. }
  283. func (t *Terminal) eraseNPreviousChars(n int) {
  284. if n == 0 {
  285. return
  286. }
  287. if t.pos < n {
  288. n = t.pos
  289. }
  290. t.pos -= n
  291. t.moveCursorToPos(t.pos)
  292. copy(t.line[t.pos:], t.line[n+t.pos:])
  293. t.line = t.line[:len(t.line)-n]
  294. if t.echo {
  295. t.writeLine(t.line[t.pos:])
  296. for i := 0; i < n; i++ {
  297. t.queue(space)
  298. }
  299. t.advanceCursor(n)
  300. t.moveCursorToPos(t.pos)
  301. }
  302. }
  303. // countToLeftWord returns then number of characters from the cursor to the
  304. // start of the previous word.
  305. func (t *Terminal) countToLeftWord() int {
  306. if t.pos == 0 {
  307. return 0
  308. }
  309. pos := t.pos - 1
  310. for pos > 0 {
  311. if t.line[pos] != ' ' {
  312. break
  313. }
  314. pos--
  315. }
  316. for pos > 0 {
  317. if t.line[pos] == ' ' {
  318. pos++
  319. break
  320. }
  321. pos--
  322. }
  323. return t.pos - pos
  324. }
  325. // countToRightWord returns then number of characters from the cursor to the
  326. // start of the next word.
  327. func (t *Terminal) countToRightWord() int {
  328. pos := t.pos
  329. for pos < len(t.line) {
  330. if t.line[pos] == ' ' {
  331. break
  332. }
  333. pos++
  334. }
  335. for pos < len(t.line) {
  336. if t.line[pos] != ' ' {
  337. break
  338. }
  339. pos++
  340. }
  341. return pos - t.pos
  342. }
  343. // visualLength returns the number of visible glyphs in s.
  344. func visualLength(runes []rune) int {
  345. inEscapeSeq := false
  346. length := 0
  347. for _, r := range runes {
  348. switch {
  349. case inEscapeSeq:
  350. if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
  351. inEscapeSeq = false
  352. }
  353. case r == '\x1b':
  354. inEscapeSeq = true
  355. default:
  356. length++
  357. }
  358. }
  359. return length
  360. }
  361. // handleKey processes the given key and, optionally, returns a line of text
  362. // that the user has entered.
  363. func (t *Terminal) handleKey(key rune) (line string, ok bool) {
  364. switch key {
  365. case keyBackspace:
  366. if t.pos == 0 {
  367. return
  368. }
  369. t.eraseNPreviousChars(1)
  370. case keyAltLeft:
  371. // move left by a word.
  372. t.pos -= t.countToLeftWord()
  373. t.moveCursorToPos(t.pos)
  374. case keyAltRight:
  375. // move right by a word.
  376. t.pos += t.countToRightWord()
  377. t.moveCursorToPos(t.pos)
  378. case keyLeft:
  379. if t.pos == 0 {
  380. return
  381. }
  382. t.pos--
  383. t.moveCursorToPos(t.pos)
  384. case keyRight:
  385. if t.pos == len(t.line) {
  386. return
  387. }
  388. t.pos++
  389. t.moveCursorToPos(t.pos)
  390. case keyHome:
  391. if t.pos == 0 {
  392. return
  393. }
  394. t.pos = 0
  395. t.moveCursorToPos(t.pos)
  396. case keyEnd:
  397. if t.pos == len(t.line) {
  398. return
  399. }
  400. t.pos = len(t.line)
  401. t.moveCursorToPos(t.pos)
  402. case keyUp:
  403. entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
  404. if !ok {
  405. return "", false
  406. }
  407. if t.historyIndex == -1 {
  408. t.historyPending = string(t.line)
  409. }
  410. t.historyIndex++
  411. runes := []rune(entry)
  412. t.setLine(runes, len(runes))
  413. case keyDown:
  414. switch t.historyIndex {
  415. case -1:
  416. return
  417. case 0:
  418. runes := []rune(t.historyPending)
  419. t.setLine(runes, len(runes))
  420. t.historyIndex--
  421. default:
  422. entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
  423. if ok {
  424. t.historyIndex--
  425. runes := []rune(entry)
  426. t.setLine(runes, len(runes))
  427. }
  428. }
  429. case keyEnter:
  430. t.moveCursorToPos(len(t.line))
  431. t.queue([]rune("\r\n"))
  432. line = string(t.line)
  433. ok = true
  434. t.line = t.line[:0]
  435. t.pos = 0
  436. t.cursorX = 0
  437. t.cursorY = 0
  438. t.maxLine = 0
  439. case keyDeleteWord:
  440. // Delete zero or more spaces and then one or more characters.
  441. t.eraseNPreviousChars(t.countToLeftWord())
  442. case keyDeleteLine:
  443. // Delete everything from the current cursor position to the
  444. // end of line.
  445. for i := t.pos; i < len(t.line); i++ {
  446. t.queue(space)
  447. t.advanceCursor(1)
  448. }
  449. t.line = t.line[:t.pos]
  450. t.moveCursorToPos(t.pos)
  451. case keyCtrlD:
  452. // Erase the character under the current position.
  453. // The EOF case when the line is empty is handled in
  454. // readLine().
  455. if t.pos < len(t.line) {
  456. t.pos++
  457. t.eraseNPreviousChars(1)
  458. }
  459. case keyCtrlU:
  460. t.eraseNPreviousChars(t.pos)
  461. case keyClearScreen:
  462. // Erases the screen and moves the cursor to the home position.
  463. t.queue([]rune("\x1b[2J\x1b[H"))
  464. t.queue(t.prompt)
  465. t.cursorX, t.cursorY = 0, 0
  466. t.advanceCursor(visualLength(t.prompt))
  467. t.setLine(t.line, t.pos)
  468. default:
  469. if t.AutoCompleteCallback != nil {
  470. prefix := string(t.line[:t.pos])
  471. suffix := string(t.line[t.pos:])
  472. t.lock.Unlock()
  473. newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
  474. t.lock.Lock()
  475. if completeOk {
  476. t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
  477. return
  478. }
  479. }
  480. if !isPrintable(key) {
  481. return
  482. }
  483. if len(t.line) == maxLineLength {
  484. return
  485. }
  486. if len(t.line) == cap(t.line) {
  487. newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
  488. copy(newLine, t.line)
  489. t.line = newLine
  490. }
  491. t.line = t.line[:len(t.line)+1]
  492. copy(t.line[t.pos+1:], t.line[t.pos:])
  493. t.line[t.pos] = key
  494. if t.echo {
  495. t.writeLine(t.line[t.pos:])
  496. }
  497. t.pos++
  498. t.moveCursorToPos(t.pos)
  499. }
  500. return
  501. }
  502. func (t *Terminal) writeLine(line []rune) {
  503. for len(line) != 0 {
  504. remainingOnLine := t.termWidth - t.cursorX
  505. todo := len(line)
  506. if todo > remainingOnLine {
  507. todo = remainingOnLine
  508. }
  509. t.queue(line[:todo])
  510. t.advanceCursor(visualLength(line[:todo]))
  511. line = line[todo:]
  512. }
  513. }
  514. func (t *Terminal) Write(buf []byte) (n int, err error) {
  515. t.lock.Lock()
  516. defer t.lock.Unlock()
  517. if t.cursorX == 0 && t.cursorY == 0 {
  518. // This is the easy case: there's nothing on the screen that we
  519. // have to move out of the way.
  520. return t.c.Write(buf)
  521. }
  522. // We have a prompt and possibly user input on the screen. We
  523. // have to clear it first.
  524. t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
  525. t.cursorX = 0
  526. t.clearLineToRight()
  527. for t.cursorY > 0 {
  528. t.move(1 /* up */, 0, 0, 0)
  529. t.cursorY--
  530. t.clearLineToRight()
  531. }
  532. if _, err = t.c.Write(t.outBuf); err != nil {
  533. return
  534. }
  535. t.outBuf = t.outBuf[:0]
  536. if n, err = t.c.Write(buf); err != nil {
  537. return
  538. }
  539. t.writeLine(t.prompt)
  540. if t.echo {
  541. t.writeLine(t.line)
  542. }
  543. t.moveCursorToPos(t.pos)
  544. if _, err = t.c.Write(t.outBuf); err != nil {
  545. return
  546. }
  547. t.outBuf = t.outBuf[:0]
  548. return
  549. }
  550. // ReadPassword temporarily changes the prompt and reads a password, without
  551. // echo, from the terminal.
  552. func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
  553. t.lock.Lock()
  554. defer t.lock.Unlock()
  555. oldPrompt := t.prompt
  556. t.prompt = []rune(prompt)
  557. t.echo = false
  558. line, err = t.readLine()
  559. t.prompt = oldPrompt
  560. t.echo = true
  561. return
  562. }
  563. // ReadLine returns a line of input from the terminal.
  564. func (t *Terminal) ReadLine() (line string, err error) {
  565. t.lock.Lock()
  566. defer t.lock.Unlock()
  567. return t.readLine()
  568. }
  569. func (t *Terminal) readLine() (line string, err error) {
  570. // t.lock must be held at this point
  571. if t.cursorX == 0 && t.cursorY == 0 {
  572. t.writeLine(t.prompt)
  573. t.c.Write(t.outBuf)
  574. t.outBuf = t.outBuf[:0]
  575. }
  576. for {
  577. rest := t.remainder
  578. lineOk := false
  579. for !lineOk {
  580. var key rune
  581. key, rest = bytesToKey(rest)
  582. if key == utf8.RuneError {
  583. break
  584. }
  585. if key == keyCtrlD {
  586. if len(t.line) == 0 {
  587. return "", io.EOF
  588. }
  589. }
  590. line, lineOk = t.handleKey(key)
  591. }
  592. if len(rest) > 0 {
  593. n := copy(t.inBuf[:], rest)
  594. t.remainder = t.inBuf[:n]
  595. } else {
  596. t.remainder = nil
  597. }
  598. t.c.Write(t.outBuf)
  599. t.outBuf = t.outBuf[:0]
  600. if lineOk {
  601. if t.echo {
  602. t.historyIndex = -1
  603. t.history.Add(line)
  604. }
  605. return
  606. }
  607. // t.remainder is a slice at the beginning of t.inBuf
  608. // containing a partial key sequence
  609. readBuf := t.inBuf[len(t.remainder):]
  610. var n int
  611. t.lock.Unlock()
  612. n, err = t.c.Read(readBuf)
  613. t.lock.Lock()
  614. if err != nil {
  615. return
  616. }
  617. t.remainder = t.inBuf[:n+len(t.remainder)]
  618. }
  619. panic("unreachable") // for Go 1.0.
  620. }
  621. // SetPrompt sets the prompt to be used when reading subsequent lines.
  622. func (t *Terminal) SetPrompt(prompt string) {
  623. t.lock.Lock()
  624. defer t.lock.Unlock()
  625. t.prompt = []rune(prompt)
  626. }
  627. func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
  628. // Move cursor to column zero at the start of the line.
  629. t.move(t.cursorY, 0, t.cursorX, 0)
  630. t.cursorX, t.cursorY = 0, 0
  631. t.clearLineToRight()
  632. for t.cursorY < numPrevLines {
  633. // Move down a line
  634. t.move(0, 1, 0, 0)
  635. t.cursorY++
  636. t.clearLineToRight()
  637. }
  638. // Move back to beginning.
  639. t.move(t.cursorY, 0, 0, 0)
  640. t.cursorX, t.cursorY = 0, 0
  641. t.queue(t.prompt)
  642. t.advanceCursor(visualLength(t.prompt))
  643. t.writeLine(t.line)
  644. t.moveCursorToPos(t.pos)
  645. }
  646. func (t *Terminal) SetSize(width, height int) error {
  647. t.lock.Lock()
  648. defer t.lock.Unlock()
  649. oldWidth := t.termWidth
  650. t.termWidth, t.termHeight = width, height
  651. switch {
  652. case width == oldWidth || len(t.line) == 0:
  653. // If the width didn't change then nothing else needs to be
  654. // done.
  655. return nil
  656. case width < oldWidth:
  657. // Some terminals (e.g. xterm) will truncate lines that were
  658. // too long when shinking. Others, (e.g. gnome-terminal) will
  659. // attempt to wrap them. For the former, repainting t.maxLine
  660. // works great, but that behaviour goes badly wrong in the case
  661. // of the latter because they have doubled every full line.
  662. // We assume that we are working on a terminal that wraps lines
  663. // and adjust the cursor position based on every previous line
  664. // wrapping and turning into two. This causes the prompt on
  665. // xterms to move upwards, which isn't great, but it avoids a
  666. // huge mess with gnome-terminal.
  667. t.cursorY *= 2
  668. t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
  669. case width > oldWidth:
  670. // If the terminal expands then our position calculations will
  671. // be wrong in the future because we think the cursor is
  672. // |t.pos| chars into the string, but there will be a gap at
  673. // the end of any wrapped line.
  674. //
  675. // But the position will actually be correct until we move, so
  676. // we can move back to the beginning and repaint everything.
  677. t.clearAndRepaintLinePlusNPrevious(t.maxLine)
  678. }
  679. _, err := t.c.Write(t.outBuf)
  680. t.outBuf = t.outBuf[:0]
  681. return err
  682. }
  683. // stRingBuffer is a ring buffer of strings.
  684. type stRingBuffer struct {
  685. // entries contains max elements.
  686. entries []string
  687. max int
  688. // head contains the index of the element most recently added to the ring.
  689. head int
  690. // size contains the number of elements in the ring.
  691. size int
  692. }
  693. func (s *stRingBuffer) Add(a string) {
  694. if s.entries == nil {
  695. const defaultNumEntries = 100
  696. s.entries = make([]string, defaultNumEntries)
  697. s.max = defaultNumEntries
  698. }
  699. s.head = (s.head + 1) % s.max
  700. s.entries[s.head] = a
  701. if s.size < s.max {
  702. s.size++
  703. }
  704. }
  705. // NthPreviousEntry returns the value passed to the nth previous call to Add.
  706. // If n is zero then the immediately prior value is returned, if one, then the
  707. // next most recent, and so on. If such an element doesn't exist then ok is
  708. // false.
  709. func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
  710. if n >= s.size {
  711. return "", false
  712. }
  713. index := s.head - n
  714. if index < 0 {
  715. index += s.max
  716. }
  717. return s.entries[index], true
  718. }