diff --git a/pkg/cli/editor.go b/pkg/cli/editor.go index 608745d..18cf7c9 100644 --- a/pkg/cli/editor.go +++ b/pkg/cli/editor.go @@ -23,8 +23,7 @@ func NewEditor(history *History) *Editor { } func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer string) (string, error) { - historyIndex := 0 - + ed.History.ResetPosition() fmt.Print(ed.content.ReplaceText(initBuffer)) for e := range keyStream { @@ -61,25 +60,19 @@ func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer str case keyboard.KeyArrowRight: fmt.Print(ed.content.MovePositionRight()) case keyboard.KeyArrowUp: - historyIndex++ - req := ed.History.GetRequst(historyIndex) + req := ed.History.PrevRequst() if req == "" { fmt.Print(Bell) - historyIndex-- - continue } fmt.Print(ed.content.ReplaceText(req)) case keyboard.KeyArrowDown: - historyIndex-- - req := ed.History.GetRequst(historyIndex) + req := ed.History.NextRequst() if req == "" { fmt.Print(Bell) - historyIndex++ - continue } diff --git a/pkg/cli/history.go b/pkg/cli/history.go index fa0f2f4..e6f5597 100644 --- a/pkg/cli/history.go +++ b/pkg/cli/history.go @@ -15,6 +15,7 @@ type History struct { fileName string requests []string limit uint + pos int } func NewHistory(fileName string, limit uint) *History { @@ -22,6 +23,7 @@ func NewHistory(fileName string, limit uint) *History { fileName: fileName, limit: limit, requests: make([]string, 0), + pos: 0, } _ = h.loadFromFile() @@ -57,6 +59,8 @@ func (h *History) loadFromFile() error { h.requests = append(h.requests, line) } + h.pos = len(h.requests) - 1 + return nil } @@ -106,16 +110,35 @@ func (h *History) AddRequest(request string) { } h.requests = append(h.requests, request) + h.pos = len(h.requests) - 1 } -func (h *History) GetRequst(pos int) string { - if pos <= 0 { +func (h *History) PrevRequst() string { + if h.pos <= 0 { return "" } - if pos > len(h.requests) { + req := h.requests[h.pos] + h.pos-- + + return req +} + +func (h *History) NextRequst() string { + if h.pos >= len(h.requests)-1 { return "" } - return h.requests[len(h.requests)-pos] + h.pos++ + req := h.requests[h.pos] + + return req +} + +func (h *History) ResetPosition() { + if len(h.requests) == 0 { + return + } + + h.pos = len(h.requests) - 1 }