history.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package prompt
  2. // History stores the texts that are entered.
  3. type History struct {
  4. histories []string
  5. tmp []string
  6. selected int
  7. }
  8. // Add to add text in history.
  9. func (h *History) Add(input string) {
  10. h.histories = append(h.histories, input)
  11. h.Clear()
  12. }
  13. // Clear to clear the history.
  14. func (h *History) Clear() {
  15. h.tmp = make([]string, len(h.histories))
  16. for i := range h.histories {
  17. h.tmp[i] = h.histories[i]
  18. }
  19. h.tmp = append(h.tmp, "")
  20. h.selected = len(h.tmp) - 1
  21. }
  22. // Older saves a buffer of current line and get a buffer of previous line by up-arrow.
  23. // The changes of line buffers are stored until new history is created.
  24. func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
  25. if len(h.tmp) == 1 || h.selected == 0 {
  26. return buf, false
  27. }
  28. h.tmp[h.selected] = buf.Text()
  29. h.selected--
  30. new = NewBuffer()
  31. new.InsertText(h.tmp[h.selected], false, true)
  32. return new, true
  33. }
  34. // Newer saves a buffer of current line and get a buffer of next line by up-arrow.
  35. // The changes of line buffers are stored until new history is created.
  36. func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
  37. if h.selected >= len(h.tmp)-1 {
  38. return buf, false
  39. }
  40. h.tmp[h.selected] = buf.Text()
  41. h.selected++
  42. new = NewBuffer()
  43. new.InsertText(h.tmp[h.selected], false, true)
  44. return new, true
  45. }
  46. // NewHistory returns new history object.
  47. func NewHistory() *History {
  48. return &History{
  49. histories: []string{},
  50. tmp: []string{""},
  51. selected: 0,
  52. }
  53. }