Skip to content

Commit

Permalink
Trigger ExitChecker on pressed keys (#162)
Browse files Browse the repository at this point in the history
* prompt.go handleKeyBinding can indicate one should Exit if an exit checker function is set

* Use new name exitChecker instead of old exitor

* ExitChecker API change: breakline bool

- breakline true means the executor has been called: check for exit
- breakline false means no executor, just a character typed: check for
exit
  • Loading branch information
VonC authored Feb 22, 2020
1 parent 0d09787 commit 39d1a73
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import (
type Executor func(string)

// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
// User input means: selecting/typing an entry, then <return>, and the executor is called.
// Then, if said entry content matches the ExitChecker function criteria, exit go-prompt (not the overall Go program)
type ExitChecker func(string) bool
// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
// - immediate exit (if breakline is false) without executor called
// - exit after typing <return> (meaning breakline is true), and the executor is called first, before exit.
// Exit means exit go-prompt (not the overall Go program)
type ExitChecker func(in string, breakline bool) bool

// Completer should return the suggest item from Document.
type Completer func(Document) []Suggest
Expand Down Expand Up @@ -85,7 +87,7 @@ func (p *Prompt) Run() {

p.renderer.Render(p.buf, p.completion)

if p.exitChecker != nil && p.exitChecker(e.input) {
if p.exitChecker != nil && p.exitChecker(e.input, true) {
p.skipTearDown = true
return
}
Expand Down Expand Up @@ -155,7 +157,7 @@ func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
p.buf.InsertText(string(b), false, true)
}

p.handleKeyBinding(key)
shouldExit = p.handleKeyBinding(key)
return
}

Expand Down Expand Up @@ -185,7 +187,8 @@ func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
}
}

func (p *Prompt) handleKeyBinding(key Key) {
func (p *Prompt) handleKeyBinding(key Key) bool {
shouldExit := false
for i := range commonKeyBindings {
kb := commonKeyBindings[i]
if kb.Key == key {
Expand All @@ -209,6 +212,10 @@ func (p *Prompt) handleKeyBinding(key Key) {
kb.Fn(p.buf)
}
}
if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
shouldExit = true
}
return shouldExit
}

func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
Expand Down

0 comments on commit 39d1a73

Please sign in to comment.