Go cursor key terminal input

I am creating a Go application for use in a terminal. The following code asks the user to enter text into the terminal.

package main import ( "bufio" "fmt" "os" ) func main() { for { fmt.Println("Please input something and use arrows to move along the text left and right") in := bufio.NewReader(os.Stdin) _, err := in.ReadString('\n') if err != nil { fmt.Println(err) } } } 

The problem is that the user cannot use the left and right arrows to follow the text just entered to change it. When he presses the arrows, the console prints the signs ^[[D^[[C^[[A^[[B

Exit:

 Please input something and use arrows to move along the text left and right hello^[[D^[[C^[[A^[[B 

How to make arrow keys more user-friendly and allow a person to navigate the text just entered using the left and right arrows?

I think I should pay attention to libraries such as termbox-go or gocui , but I don’t know how to use them for this purpose.

+7
terminal go
source share
1 answer

A simple example would be carmark/pseudo-terminal-go , where you can put the terminal in raw mode and capitalize on moving the cursor up, down, left, and right.

From terminal.go#NewTerminal()

 // NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is // a local terminal, that terminal must first have been put into raw mode. // prompt is a string that is written at the start of each input line (ie // "> "). func NewTerminal(c io.ReadWriter, prompt string) *Terminal 

See terminal / terminal.go and terminal/terminal_test.go , as well as MakeRaw()

+3
source share

All Articles