From 67e670a967333db6fb39006929fbef7bca8a6fb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=A1=D1=8B=D1=81?= =?UTF-8?q?=D0=BE=D0=B5=D0=B2?= Date: Sun, 29 Oct 2023 14:11:17 +0800 Subject: [PATCH] Adds possibility to detect pasting request to allow insert multipline request --- pkg/cli/editor.go | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/pkg/cli/editor.go b/pkg/cli/editor.go index 9ed4ab9..14ee195 100644 --- a/pkg/cli/editor.go +++ b/pkg/cli/editor.go @@ -3,25 +3,32 @@ package cli import ( "fmt" "io" + "time" "github.com/eiannone/keyboard" ) +const ( + PastingTimingThresholdInMicrosec = 250 +) + type Editor struct { - History *History - content *Content - output io.Writer - buffer []rune - pos int + History *History + content *Content + output io.Writer + prevPressedTime time.Time + buffer []rune + pos int } func NewEditor(output io.Writer, history *History) *Editor { return &Editor{ - History: history, - content: NewContent(), - buffer: make([]rune, 0), - pos: 0, - output: output, + History: history, + content: NewContent(), + buffer: make([]rune, 0), + pos: 0, + output: output, + prevPressedTime: time.Now(), } } @@ -30,6 +37,8 @@ func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer str fmt.Fprint(ed.output, ed.content.ReplaceText(initBuffer)) for e := range keyStream { + isPasting := ed.isPasting() + if e.Err != nil { return "", e.Err } @@ -47,7 +56,7 @@ func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer str case keyboard.KeySpace: fmt.Fprint(ed.output, ed.content.InsertSymbol(' ')) case keyboard.KeyEnter: - if isDone := ed.newLineOrDone(); isDone { + if isDone := ed.newLineOrDone(isPasting); isDone { return ed.done() } case keyboard.KeyBackspace, keyboard.KeyDelete, MacOSDeleteKey: @@ -108,7 +117,7 @@ func (ed *Editor) nextFromHistory() { fmt.Fprint(ed.output, ed.content.ReplaceText(req)) } -func (ed *Editor) newLineOrDone() (isDone bool) { +func (ed *Editor) newLineOrDone(isPasting bool) (isDone bool) { prev := ed.content.PrevSymbol() isDone = prev != '\\' @@ -119,5 +128,17 @@ func (ed *Editor) newLineOrDone() (isDone bool) { return isDone } + if isPasting { + fmt.Fprint(ed.output, ed.content.InsertSymbol('\n')) + return false + } + return isDone } + +func (ed *Editor) isPasting() bool { + elapsed := time.Since(ed.prevPressedTime) + ed.prevPressedTime = time.Now() + + return elapsed.Microseconds() < PastingTimingThresholdInMicrosec +}