Giter Club home page Giter Club logo

go-prompt's Introduction

go-prompt

Go Report Card Software License GoDoc tests

A library for building powerful interactive prompts inspired by python-prompt-toolkit, making it easier to build cross-platform command line tools using Go.

package main

import (
	"fmt"
	"github.com/c-bata/go-prompt"
)

func completer(d prompt.Document) []prompt.Suggest {
	s := []prompt.Suggest{
		{Text: "users", Description: "Store the username and age"},
		{Text: "articles", Description: "Store the article text posted by user"},
		{Text: "comments", Description: "Store the text commented to articles"},
	}
	return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
}

func main() {
	fmt.Println("Please select table.")
	t := prompt.Input("> ", completer)
	fmt.Println("You selected " + t)
}

Projects using go-prompt

Features

Powerful auto-completion

demo

(This is a GIF animation of kube-prompt.)

Flexible options

go-prompt provides many options. Please check option section of GoDoc for more details.

options

Keyboard Shortcuts

Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell). You can customize and expand these shortcuts.

keyboard shortcuts

Key Binding Description
Ctrl + A Go to the beginning of the line (Home)
Ctrl + E Go to the end of the line (End)
Ctrl + P Previous command (Up arrow)
Ctrl + N Next command (Down arrow)
Ctrl + F Forward one character
Ctrl + B Backward one character
Ctrl + D Delete character under the cursor
Ctrl + H Delete character before the cursor (Backspace)
Ctrl + W Cut the word before the cursor to the clipboard
Ctrl + K Cut the line after the cursor to the clipboard
Ctrl + U Cut the line before the cursor to the clipboard
Ctrl + L Clear the screen

History

You can use Up arrow and Down arrow to walk through the history of commands executed.

History

Multiple platform support

We have confirmed go-prompt works fine in the following terminals:

  • iTerm2 (macOS)
  • Terminal.app (macOS)
  • Command Prompt (Windows)
  • gnome-terminal (Ubuntu)

Links

Author

Masashi Shibata

License

This software is licensed under the MIT license, see LICENSE for more information.

go-prompt's People

Contributors

andy-js avatar aphistic avatar babarot avatar bcicen avatar brettbuddin avatar c-bata avatar calinou avatar chyroc avatar kalafut avatar mattn avatar monkeywithacupcake avatar odino avatar orisano avatar pgollangi avatar rhysd avatar stealthybox avatar uip9av6y avatar unasuke avatar vonc avatar zaynetro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-prompt's Issues

Add way to exit go-prompt

Either it's well hidden or there doesn't seem to be a way to exit go-prompt.
Tried Ctrl-C, Ctrl-X, Esc, exit, quit in kube-prompt …

Wrong behaviour with accent letters

Hi c-bata,

Thanks a lot for go-prompt, it helps me a lot. 👍

It might not be important for english people, but there is a problem with accent letters on go-prompt.
In fact, when I enter an word with an accent, like "voilà", in the echo program, the cursor go back to the 'à' letter after typing it.
As a result, go-prompt is not very usable for french people, for example.

Thanks for your help.

Escaped arrow keys written when traversed quickly on remote shell

Bug reports

When I run a program using go-prompt on a remote SSH shell, quick traversal with arrow keys causes escaped arrow key characters to be written.

Expected Behavior

Arrow keys to only move the curser, regardless of how fast they're repeated.

Current Behavior and Steps to Reproduce

go-prompt-escape-arrow

Key-response delay via SSH must be playing a part here.

Context

A simple hello-world prompt running on a SSH shell running bash.

  • Operating System: iTerm2/OSX via SSH into Ubuntu+bash
  • Terminal Emulator: (i.e. iTerm2)
  • tag of go-prompt or commit revision: de51277

Rendering issue: `?` is invisible while typing.

Bug reports

Expected Behavior

? have to be rendered properly.

Current Behavior and Steps to Reproduce

? is invisible while typing. You can see on a following GIF.
feb-15-2018 05-30-44

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: macOS 10.12.6
  • Terminal Emulator: iTerm2
  • tag of go-prompt or commit revision: 7c05c0763ad15c362f3636e02624e84b2a43c902

Search history

Maybe I have overlooked, it doesn’t seem to be that there is a search function of the history, like ctrl+r / ctrl+s in bash.

Add example of multi-line support

Can you add an example of how to achieve multi-line editing? Something similar to the way the mysql REPL handles long queries.

>>> select * from
... table
... then terminating char;

binding a key to os.Exit results in strange terminal output

Issue

I bound ControlC to a function that calls os.Exit - because that's what I want it to do

Expected Behavior

program to exit, drop back into bash, continue work

Current Behavior and Steps to Reproduce

my app exits nicely, but the bash session acts "strange" afterwards. There is no newline after hitting Enter (the prompt just repeats without one) and history does not appear with up/down arrow keys (though the commands that are there still work - just that the text is not written into the shell)

Note - these are not problems while using my application that imports go-prompt, they are problems that occur in my regular OS shell after I have quit my application via a ctrl-c keybinding that happens to call os.Exit.

If, instead, I call panic everything works fine afterwards - I just have to ignore the stacktrace.

Context

image

minimal reproducible example (use ctrl-c to observe behavior):

package main

import (
	"fmt"
	"os"

	prompt "github.com/c-bata/go-prompt"
)

func main() {
	p := prompt.New(
		dummyExecutor,
		completer,
		prompt.OptionPrefix(">>> "),
		prompt.OptionAddKeyBind(quit),
	)
	text := p.Input()
	fmt.Println("You've got text: ", text)
}

func dummyExecutor(in string) { return }

func completer(d prompt.Document) []prompt.Suggest {
	s := []prompt.Suggest{
		{Text: "dummy", Description: "I'm a dummy"},
	}
	return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
}

var quit = prompt.KeyBind{
	Key: prompt.ControlC,
	Fn: func(b *prompt.Buffer) {
		os.Exit(0) // log.Fatal doesn't work, but panic somehow avoids this issue...
	},
}
  • Operating System: OSX Sierra, go v1.10
  • tag of go-prompt or commit revision: de51277535db236123a9f8f97d03290f62c5f2a6

Catch a signal that window size is changed on Windows

I wrote that "windows support is almost perfect" in change log of v0.2.1 but I noticed a critical bug a while ago :(

Current implementation of go-prompt cannot catch signal for updating window size on Windows. So if you change a size of terminal emulator, the layout will be broken.

On Windows, ReadConsoleInput and WINDOW_BUFFER_SIZE_EVENT can be used for receiving window size change events.

Way to exit prompt?

Suggestions

Ability to exit the prompt using Ctrl+C or something else in the examples without having to kill the terminal window.
i.e. Ctrl+C, etc...

  • Operating System: Mac OS El Capitan
  • Terminal Emulator: iTerm2
  • tag of go-prompt or commit revision: latest head version

Is it possible to perform validation?

I used go-prompt successfully to implement input with completion, but in my application I also need to ask input and validate it. I was wondering if it is possible to use the go-prompt infrastructure to force a valid input (for example, input matching a regex).

Naturally, I am not talking about doing that in a loop (input -> validate -> ask again), but I would like to do that inline, as user type.

Library using go-prompt: moshpit

I've written moshpit, a command-line tool to perform datamoshing, using go-prompt:
tutorial

Thank you so much for your amazing tool, it made creating a helpful command line interface easy as pie!
If you want, please include my tool in your list of tools using go-prompt :)

Input example is leaving the console with colored text

Suggestions

When I run go run src/github.com/c-bata/go-prompt/_example/echo/main.go the console ends up with bold text in my iterm and my xterm terminals.


Bug reports

It seems like Render.Teardown is not resetting the default colors on exit. Please let me know if I am mistaken:

 // TearDown to clear title and erasing.                                                         |   -livePrefixCallback : func() string,
 func (r *Render) TearDown() {                                                                   |   -out : ConsoleWriter
     r.out.ClearTitle()                                                                          |   -prefix : string
     r.out.EraseDown()                                                                           |   -prefixBGColor : Color
     r.out.Flush()                                                                               |   -prefixTextColor : Color
 }                                                                                               |   -previewSuggestionBGColor : Color

Should this not also include r.out.SetColor(DefaultColor, DefaultColor, false)?

Expected Behavior

The console to be back to its previous text formatting after prompt.Input() finishes.

Current Behavior and Steps to Reproduce

  1. go get -u github.com/c-bata/go-prompt
  2. go run src/github.com/c-bata/go-prompt/_example/echo/main.go

What is the current behavior? Please provide detailed steps for reproducing the issue.

If you enter your own string, the program exits as expected - with previous console colors. However, if you accept the suggestions, the program exits with bold text.

asciicast

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: Mac OSX High Sierra
  • Terminal Emulator: iTerm2 and xquartx terminal
  • tag of go-prompt or commit revision: HEAD

this library doesn't support Windows?

When i run 'got get' for this library, I got message below

# github.com/pkg/term/termios
..\..\pkg\term\termios\pty.go:20: undefined: open_pty_master
..\..\pkg\term\termios\pty.go:25: undefined: Ptsname
..\..\pkg\term\termios\pty.go:30: undefined: grantpt
..\..\pkg\term\termios\pty.go:35: undefined: unlockpt

My environment
OS: Windows 10
version:
go version go1.8.3 windows/amd64

I want to try go-prompt.
Please help!

Prompt Rendering Issue With Autocomplete - Windows 10 x64 CMD + Powershell

Bug reports

Expected Behavior

The prompt to allocate additional space when at the end of the consoles buffer for the autocomplete box.

Current Behavior and Steps to Reproduce

When reaching the end of a console windows buffer, if the autocomplete feature is enabled the buffer is not scrolled up to allow for space for the autocomplete suggestions. The result is that while the prompt is rendered at the bottom of the window, the actual cursor position is at the top of where the autocomplete box would have been rendered. For some reason only the bottom line of the autocomplete box is rendered.

In the screenshot below you can see the prompt at the bottom of the window with the cursor out of place a few lines above.
image
As soon as I start typing part of the previous output is erased and the prompt is re-rendered correctly.
image

Note that this only happens when the prompt is at the bottom of the consoles buffer not just the console window. ie. When the scroll bar on the console is all the way to the bottom. When there is still empty buffer space (console window scroll bar is not at the bottom) the previous output scrolls up as expected and the autocomplete box is given enough room to render.

Context

  • Operating System: Windows 10 x64 Build 16299
  • Terminal Emulator: Windows Command Prompt, Powershell
  • tag of go-prompt or commit revision: master

"panic: inappropriate ioctl for device" when stdin is reused

Bug reports

When a program reads input from stdin (i.e, piped in before initializing the prompt), go-prompt attempts to reuse this same pipe to read user input interactively, resulting in a panic:

panic: inappropriate ioctl for device

goroutine 1 [running]:
github.com/c-bata/go-prompt.(*PosixParser).GetWinSize(0xc420102b90, 0x871ee0)
	/home/bradley/go/src/github.com/c-bata/go-prompt/input_posix.go:113 +0xdd

Expected Behavior

go-prompt should always open a fresh stdin descriptor when initialized

Current Behavior and Steps to Reproduce

Read from stdin before starting the prompt

Context

  • Operating System: Linux
  • Terminal Emulator: Terminator
  • tag of go-prompt or commit revision: aa7dc8b

prefix string will be disappear after press Ctrl+L inside tmux session.

Bug reports

Current Behavior and Steps to Reproduce

prefix-bug

  1. Run tmux session
  2. Run echo example
  3. Press Control + L

prefix string will be disappear. this bug doesn't reproduce without tmux.

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: macOS
  • Terminal Emulator: (i.e. iTerm2) iTerm2
  • tag of go-prompt or commit revision: 5e184cd

Add way to stop go-prompt

If you want 2 go-prompt in a single application you should have the ability to stop the first one to start the second one.

Example:

- ssh service to interact with a server
- login in different prompt to request the credentials if doesn't exist in a config file like a yaml

2 different executor and completer for 2 different tasks which are connected one each other.
Without credentials first run prompt login, if already credentials run prompt ssh, if in prompt ssh and you want to change credentials stop prompt ssh and run prompt login...

Rancher CLI for go-prompt

Rancher cli is currently using go-prompt to auto prompt its command. Could you add it to the list of your repo? :) Again thanks for this awesome library

Provide a way to retrieve history

I don't see a way to retrieve the history, only a way to set it at program startup.

I would like to persist history between sessions. I can implement persistence/restore if I can access the history. It would be great if go-prompt provided a way to save/load history from a file though.

go-prompt behaves unexpected way when the description string has newline "\n" character

Bug reports

Expected Behavior

Either the description should trim away the new line charecters or show ...

Current Behavior and Steps to Reproduce

In the prompt.Suggest struct and the member variable Description give a string with newline "\n"

Context

  • Operating System: Any
  • Terminal Emulator: (i.e. iTerm2) Any
  • tag of go-prompt or commit revision: V 0.2.1

How to bind ctrl+c to terminate current running command?

Hi, I've been using this lib building a dynamodb prompt, it's all good until I try to kill a query running too long.
Ctrl+c seems can't kill what is running in that executor function, so I looked up in the docs, but can't find any useful tips.

Can someone help me with this, thanks~~

Panic while debugging using VSCODE linux

Bug reports

When placing a breakpoint is my code, the program is panicking

Expected Behavior

Debugging go-prompt application should not make the program panicking

Current Behavior and Steps to Reproduce

Place a break point into some of provided examples, let say in completer function
When the breakpoint is reached, the debug console shows:

API server listening at: 127.0.0.1:24621
]2;sql-prompt�
panic: inappropriate ioctl for device
goroutine 1 [running]:
github.com/c-bata/go-prompt.(*PosixParser).GetWinSize(0xc4200220a0, 0x0)
	/home/simulot/go/src/github.com/c-bata/go-prompt/posix_input.go:113 +0x16e
github.com/c-bata/go-prompt.(*Prompt).setUp(0xc42008a060)
	/home/simulot/go/src/github.com/c-bata/go-prompt/prompt.go:264 +0x69
github.com/c-bata/go-prompt.(*Prompt).Run(0xc42008a060)
	/home/simulot/go/src/github.com/c-bata/go-prompt/prompt.go:49 +0x9e
main.main()
	/home/simulot/go/src/github.com/c-bata/go-prompt/_example/echo/main.go:30 +0x120
...

Context

  • Operating System:
    ubuntu mint 18.3
    go version go1.10.1 linux/amd64

  • Terminal Emulator: (i.e. iTerm2)
    vscode 1.23.1 integrated terminal

  • tag of go-prompt or commit revision:
    I have used go get command.

Text after cursor will be disappear when completing

Bug reports

Expected Behavior

A text after cursor should be displayed after completed text.

Current Behavior and Steps to Reproduce

bug

use was disappear when completing.

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: macOS
  • Terminal Emulator: iTerm2
  • version(tag) or commit revision: 92ad4ee

Supports scrollbar when there are too many matched suggestions

Now, we can only set a max suggestions count to limit the total suggestions. If it was set to 10 when there are 20 matches, only the first 10 items will be shown.

While python-prompt-toolkit can display the prompt popup with a scrollbar in the right side, so user can choose from all matched items by scroll up and down.

pic of python-prompt-toolkit:

Are there any methods to highlight the input?

Is there any methods to highlight the input?

I know prompt.OptionInputTextColor(prompt.Blue) can be used to highlight the input,
but it only has one color.
If i want to highlight the input(e.g. SQL) language,
is there any methods to achieve?

Bug with cyrillic

Hi! After changing the keyboard layout to Russian cursor stands still, moving along the line <-> does not work, instead I move the cursor to the right with the space key.

prompt

  • Operating System: Arch Linux
  • Terminal Emulator: bug seen in xterm, termite, terminator
  • tag of go-prompt or commit revision: df30f17

gRPC client using go-prompt

hi, I created a gRPC client, Evans.
thanks for go-prompt, it was able to realize more convenient user interface! 😄
could you add this tool to "Projects using go-prompt" in the README?

Completion on non space separated words

I would like to bring completion on a language where words (or lexical identifiers) of an expression are not separated by spaces. For instance, consider the following expression:

object.method(value)

where object can have several available methods.

I would like to be able to do

object.<tab><tab>

to get the list of method and select a method among this list.

Is it currently possible? And is there an example somewhere?
Thanks.

feature request: Allow binding of any key

Suggestions

It's very common on routing platforms like Cisco IOS or Juniper Junos that the ? will instantly return context sensitive help. To get a real question mark you do a CTRL-V. The existing key bindings seem to be only for modifiers + keys. It would be nice to be able to bind any key at the prompt.

Customize insertion point for completion suggestions

Thanks for this library! It's impressive how quickly it's possible to get a REPL-like program working with it. I ran into a problem with a program I'm working on. Possibly there is already a way to solve this that I just didn't find yet, but in case that's not true...

Suggestions

I'm working on a REPL-like program that evaluates expressions in an expression language which contains the usual arithmetic operators, functions, variables, etc. As part of this I want to support autocomplete for variable names and object attribute names.

I have some examples working already:

> obj = {foo = "foo", bar = "bar"}

> ob
(suggests "obj")

> obj.
(suggests "obj.foo", "obj.bar")

> obj.fo
(suggests "obj.foo")

> complex = [{foo = "foo", bar = "bar"}, {"foo" = "foo", "notbar" = "notbar"}]

> complex[0].
(suggests "complex[0].foo" and "complex[0].bar")

> complex[1].
(suggests "complex[1].foo" and "complex[1].notbar")

> obj.foo + obj.
(suggests "obj.foo" and "obj.bar")

I run into problems, though, if the user doesn't use whitespace around the operators:

> obj.foo+obj.
(suggests "obj.foo" and "obj.bar" as expected, but when a suggestion is accepted
the entire input is replaced with it)

From studying the code I think I see why it behaves in this way:

go-prompt/prompt.go

Lines 166 to 170 in f329ebd

w := p.buf.Document().GetWordBeforeCursor()
if w != "" {
p.buf.DeleteBeforeCursor(len([]rune(w)))
}
p.buf.InsertText(s.Text, false, true)

Although my program is using d.TextBeforeCursor() and using its own simple scanner to recognize the start of the complete-able expression, the insertion code seems to be fixed using .GetWordBeforeCursor(), which then sees obj.foo+obj. as a single word, because "words" are defined as being space-separated.

Ideally I'd like to somehow be able to give the completer a "hint" about which portion of the document each suggestion is intended to replace. My completion callback already knows a byte offset into the .GetWordBeforeCursor() result which it could potentially return.

Alternatively, I could potentially implement another callback (using similar logic) that could replace the built-in FindStartOfPreviousWord as an option, effectively repeating the scanning operation my completion callback is already doing to find the start of the current expression.

A new field on type Suggest to give that offset hint would be most convenient for my use-case, but I'm sure there are complexities here I don't know, and so I'd be grateful for any reasonable feature to meet this use-case, if you agree it's worth addressing.

At the moment I'm just working on a toy prototype, but if I can get good results with the prototype (which I have so far, this quirk aside!) then my work here may be adapted into a more practical application with similar needs.

Thanks!

dynamic / live prompt/prefix string.

hey @c-bata , awesome package..

I have logged a pull request and opening this issue to discuss a potential feature enhancement or suggestions for this change.

PR #21 introduces a new option 'prompt.OptionLivePrefix' that accepts a function (signature = func() string). This function would be called each time Render() is executed.

The goal here is to enable a "live" (or dynamic) prompt, as an alternative to the current static Prefix/prompt.

example with help

Do you have an example with help command?

So, for example, if I do

help
i would my shell to show all valid commands

help commandA
i would like to show help message for "commandA"

or

help commandA subcommandA
would show help command for commandA subcommandA (i think you get the point)

Is that possible, if so do you have some example code?

Race condition

I'm encountering a data race during my debug sessions with -race. I'm performing a simple prompt.New(...).Run() and then typing into the prompt to trigger this behavior.

Race Detection Trace

...
> patch:apply()
WARNING: DATA RACE
Write at 0x00c4200b8400 by goroutine 13:
  internal/race.WriteRange()
      /usr/local/Cellar/go/1.9/libexec/src/internal/race/race.go:49 +0x42
  syscall.Read()
      /usr/local/Cellar/go/1.9/libexec/src/syscall/syscall_unix.go:165 +0x9a
  buddin.us/lumen/vendor/github.com/c-bata/go-prompt.readBuffer()
      /Users/brettbuddin/Code/src/buddin.us/lumen/vendor/github.com/c-bata/go-prompt/prompt.go:262 +0x11d

Previous read at 0x00c4200b8400 by main goroutine:
  runtime.slicebytetostring()
      /usr/local/Cellar/go/1.9/libexec/src/runtime/string.go:72 +0x0
  buddin.us/lumen/vendor/github.com/c-bata/go-prompt.(*Prompt).feed()
      /Users/brettbuddin/Code/src/buddin.us/lumen/vendor/github.com/c-bata/go-prompt/prompt.go:169 +0x1761
  buddin.us/lumen/vendor/github.com/c-bata/go-prompt.(*Prompt).Run()
      /Users/brettbuddin/Code/src/buddin.us/lumen/vendor/github.com/c-bata/go-prompt/prompt.go:70 +0x5e7
  buddin.us/lumen/lua.repl()
      /Users/brettbuddin/Coexit status 66

Points of Interest

  1. Write to buffer before sending a slice of it over a channel:
    if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
  2. Receive the slice from the channel and then operate on it:
    if shouldExit, e := p.feed(b); shouldExit {
  3. The []byte that's being shared between goroutines is being allocated here:
    buf := make([]byte, 1024)

I'm going to take a crack at fixing this and will open a PR soon-ish, but I just wanted to file an issue just in case anyone else isn't aware of it.

This library has really helped me out so far. Thanks for it. Cheers 🍻

Support for asynchronous output without clobbering prompt

Suppose I have code like:

package main

import "github.com/c-bata/go-prompt"
import "fmt"
import "time"

func main() {

    completer := func(d prompt.Document) []prompt.Suggest { return []prompt.Suggest{} }

    executor := func(in string) {
            go func(){
                time.Sleep(time.Second)
                fmt.Println("job done!")
            }()
        }

    p := prompt.New(
            executor,
            completer,
            prompt.OptionPrefix(">>> "))
    p.Run()
}

This works, but the "job done" message is appended on the prompt line, and the cursor is moved to the next line, like this:

t

What I really want is for the "job done" message to appear on a line of its own, followed by a fresh prompt line. So I think I need some asynchronous mechanism to make go-prompt momentarily hide its prompt and input buffer, let me write my own output lines, and then redisplay the prompt and input buffer on a fresh line.

But I can't find anything in the API that would let me do that. So unless I'm overlooking it, this is a feature request. :)

Problem with key bindings

I have some problems adding key bindings in go-prompt.
I took the 'echo' example, and tried to add a simple print for the 'Home', 'End' and 'PageUp' keys, but only the 'Home' key bind worked:

package main

import (
	"fmt"
	"github.com/c-bata/go-prompt"
)

func executor(in string) {
	fmt.Println("Your input: " + in)
}

func completer(in prompt.Document) []prompt.Suggest {
	s := []prompt.Suggest{
		{Text: "users", Description: "Store the username and age"},
		{Text: "articles", Description: "Store the article text posted by user"},
		{Text: "comments", Description: "Store the text commented to articles"},
		{Text: "groups", Description: "Combine users with specific rules"},
	}
	return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
}

func main() {
	p := prompt.New(
		executor,
		completer,
		prompt.OptionPrefix(">>> "),
		prompt.OptionTitle("sql-prompt"),
		prompt.OptionAddKeyBind(prompt.KeyBind{
			Key: prompt.Home,
			Fn: func(buf *prompt.Buffer) {
				fmt.Println("HOME")
			}}),
		prompt.OptionAddKeyBind(prompt.KeyBind{
			Key: prompt.End,
			Fn: func(buf *prompt.Buffer) {
				fmt.Println("END")
			}}),
		prompt.OptionAddKeyBind(prompt.KeyBind{
			Key: prompt.PageUp,
			Fn: func(buf *prompt.Buffer) {
				fmt.Println("Up")
			}}),
	)
	p.Run()
}

What's wrong with my code?

Thanks for your help.

PS: by the way, the default behaviour of the 'Home' key doesn't take into account the length of the Prefix (here, the ">>>").

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.