diff --git a/go.mod b/go.mod index 45f3b12..570b588 100644 --- a/go.mod +++ b/go.mod @@ -6,5 +6,5 @@ require ( github.com/mattn/go-runewidth v0.0.3 github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a github.com/pkg/term v0.0.0-20180423043932-cda20d4ac917 - golang.org/x/sys v0.0.0-20180620133508-ad87a3a340fa // indirect + golang.org/x/sys v0.0.0-20180620133508-ad87a3a340fa ) diff --git a/option.go b/option.go index 9d843a7..abce19a 100644 --- a/option.go +++ b/option.go @@ -234,6 +234,14 @@ func OptionShowCompletionAtStart() Option { } } +// OptionBreakLineCallback to run a callback at every break line +func OptionBreakLineCallback(fn func(*Document)) Option { + return func(p *Prompt) error { + p.renderer.breakLineCallback = fn + return nil + } +} + // New returns a Prompt with powerful auto-completion. func New(executor Executor, completer Completer, opts ...Option) *Prompt { defaultWriter := NewStdoutWriter() diff --git a/render.go b/render.go index c3c89b4..90bdf9d 100644 --- a/render.go +++ b/render.go @@ -12,6 +12,7 @@ type Render struct { out ConsoleWriter prefix string livePrefixCallback func() (prefix string, useLivePrefix bool) + breakLineCallback func(*Document) title string row uint16 col uint16 @@ -235,6 +236,9 @@ func (r *Render) BreakLine(buffer *Buffer) { r.out.WriteStr(buffer.Document().Text + "\n") r.out.SetColor(DefaultColor, DefaultColor, false) debug.AssertNoError(r.out.Flush()) + if r.breakLineCallback != nil { + r.breakLineCallback(buffer.Document()) + } r.previousCursor = 0 } diff --git a/render_test.go b/render_test.go index a87aea3..98cb27c 100644 --- a/render_test.go +++ b/render_test.go @@ -2,6 +2,7 @@ package prompt import ( "reflect" + "syscall" "testing" ) @@ -65,3 +66,48 @@ func TestFormatCompletion(t *testing.T) { } } } + +func TestBreakLineCallback(t *testing.T) { + var i int + r := &Render{ + prefix: "> ", + out: &PosixWriter{ + fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests + }, + livePrefixCallback: func() (string, bool) { return "", false }, + prefixTextColor: Blue, + prefixBGColor: DefaultColor, + inputTextColor: DefaultColor, + inputBGColor: DefaultColor, + previewSuggestionTextColor: Green, + previewSuggestionBGColor: DefaultColor, + suggestionTextColor: White, + suggestionBGColor: Cyan, + selectedSuggestionTextColor: Black, + selectedSuggestionBGColor: Turquoise, + descriptionTextColor: Black, + descriptionBGColor: Turquoise, + selectedDescriptionTextColor: White, + selectedDescriptionBGColor: Cyan, + scrollbarThumbColor: DarkGray, + scrollbarBGColor: Cyan, + col: 1, + } + b := NewBuffer() + r.BreakLine(b) + + if i != 0 { + t.Errorf("i should initially be 0, before applying a break line callback") + } + + r.breakLineCallback = func(doc *Document) { + i++ + } + r.BreakLine(b) + r.BreakLine(b) + r.BreakLine(b) + + if i != 3 { + t.Errorf("BreakLine callback not called, i should be 3") + } +}