Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor key terminal input in Go

Tags:

terminal

go

I am creating a Go application for usage in a terminal. The following code asks a user to input text to 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 a user cannot use left and right arrows to go along the just inputted text in order to modify it. When he presses arrows, the console prints ^[[D^[[C^[[A^[[B signs.

The output:

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

How to make arrow keys behave more user-friendly and let a human navigate along the just inputted text, using left and right arrows?

I guess, I should pay attention to libraries like termbox-go or gocui but how to use them exactly for this purpose, I do not know.

like image 926
Maxim Yefremov Avatar asked Jun 07 '15 02:06

Maxim Yefremov


1 Answers

A simpler example would be carmark/pseudo-terminal-go, where you can put a terminal in raw mode and benefit from the full up-down-left-right cursor moves.

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 (i.e.
// "> ").
func NewTerminal(c io.ReadWriter, prompt string) *Terminal 

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

like image 62
VonC Avatar answered Oct 21 '22 05:10

VonC