From 4c8239d83d4857a51795c195c609ff32fb9fad67 Mon Sep 17 00:00:00 2001 From: Scott Sullivan Date: Fri, 16 Oct 2020 13:24:46 -0400 Subject: [PATCH] introduce prompt.OptionCloseOnControlC() Allows one to optionally have ControlC act like ControlD -- func dialogConfirmProceed() (proceed bool) { var haveAnswer bool f := func(d prompt.Document) []prompt.Suggest { s := []prompt.Suggest{ {Text: "yes", Description: "I understand continue"}, {Text: "no", Description: "I would like to cancel"}, } return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true) } for !haveAnswer { fmt.Printf("Are you sure? ") answer := strings.ToLower(prompt.Input("> ", f, prompt.OptionShowCompletionAtStart(), prompt.OptionCloseOnControlC())) if answer == "yes" || answer == "no" || answer == "" { haveAnswer = true if answer == "yes" { proceed = true } } } return } --- option.go | 8 ++++++++ prompt.go | 11 ++++++++--- render.go | 1 + 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/option.go b/option.go index 9fbd6806..9f117eaf 100644 --- a/option.go +++ b/option.go @@ -250,6 +250,14 @@ func OptionShowCompletionAtStart() Option { } } +// OptionCloseOnControlC causes prompts to close on ControlC +func OptionCloseOnControlC() Option { + return func(p *Prompt) error { + p.renderer.closeOnControlC = true + return nil + } +} + // OptionBreakLineCallback to run a callback at every break line func OptionBreakLineCallback(fn func(*Document)) Option { return func(p *Prompt) error { diff --git a/prompt.go b/prompt.go index 173cd517..551411e1 100644 --- a/prompt.go +++ b/prompt.go @@ -129,9 +129,14 @@ func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) { p.history.Add(exec.input) } case ControlC: - p.renderer.BreakLine(p.buf) - p.buf = NewBuffer() - p.history.Clear() + if p.renderer.closeOnControlC && p.buf.Text() == "" { + shouldExit = true + return + } else { + p.renderer.BreakLine(p.buf) + p.buf = NewBuffer() + p.history.Clear() + } case Up, ControlP: if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1. if newBuf, changed := p.history.Older(p.buf); changed { diff --git a/render.go b/render.go index 299ac48b..e9a4a9ed 100644 --- a/render.go +++ b/render.go @@ -13,6 +13,7 @@ type Render struct { prefix string livePrefixCallback func() (prefix string, useLivePrefix bool) breakLineCallback func(*Document) + closeOnControlC bool title string row uint16 col uint16