From 6b45b1d6b4dff4e805d42c096c4db4e6d7be141e Mon Sep 17 00:00:00 2001 From: Shane-XB-Qian Date: Wed, 12 Mar 2025 23:51:56 +0800 Subject: [PATCH] cli: adding support ctrl-n/p like general cli (#9136) Signed-off-by: shane.xb.qian --- readline/readline.go | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/readline/readline.go b/readline/readline.go index f7b694eb2..9252f3253 100644 --- a/readline/readline.go +++ b/readline/readline.go @@ -116,19 +116,9 @@ func (i *Instance) Readline() (string, error) { switch r { case KeyUp: - if i.History.Pos > 0 { - if i.History.Pos == i.History.Size() { - currentLineBuf = []rune(buf.String()) - } - buf.Replace([]rune(i.History.Prev())) - } + i.historyPrev(buf, ¤tLineBuf) case KeyDown: - if i.History.Pos < i.History.Size() { - buf.Replace([]rune(i.History.Next())) - if i.History.Pos == i.History.Size() { - buf.Replace(currentLineBuf) - } - } + i.historyNext(buf, ¤tLineBuf) case KeyLeft: buf.MoveLeft() case KeyRight: @@ -185,6 +175,10 @@ func (i *Instance) Readline() (string, error) { esc = true case CharInterrupt: return "", ErrInterrupt + case CharPrev: + i.historyPrev(buf, ¤tLineBuf) + case CharNext: + i.historyNext(buf, ¤tLineBuf) case CharLineStart: buf.MoveToStart() case CharLineEnd: @@ -246,6 +240,24 @@ func (i *Instance) HistoryDisable() { i.History.Enabled = false } +func (i *Instance) historyPrev(buf *Buffer, currentLineBuf *[]rune) { + if i.History.Pos > 0 { + if i.History.Pos == i.History.Size() { + *currentLineBuf = []rune(buf.String()) + } + buf.Replace([]rune(i.History.Prev())) + } +} + +func (i *Instance) historyNext(buf *Buffer, currentLineBuf *[]rune) { + if i.History.Pos < i.History.Size() { + buf.Replace([]rune(i.History.Next())) + if i.History.Pos == i.History.Size() { + buf.Replace(*currentLineBuf) + } + } +} + func NewTerminal() (*Terminal, error) { fd := os.Stdin.Fd() termios, err := SetRawMode(fd)