Skip to content

Commit

Permalink
Adds possibility to detect pasting request to allow insert multipline…
Browse files Browse the repository at this point in the history
… request
  • Loading branch information
ksysoev committed Oct 29, 2023
1 parent 352b58f commit 67e670a
Showing 1 changed file with 33 additions and 12 deletions.
45 changes: 33 additions & 12 deletions pkg/cli/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}

Expand All @@ -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
}
Expand All @@ -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:
Expand Down Expand Up @@ -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 != '\\'
Expand All @@ -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
}

0 comments on commit 67e670a

Please sign in to comment.