我正在创建一个Go应用程序以在终端中使用。以下代码要求用户向终端输入文本。
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)
}
}
}
问题在于,用户不能使用向左和向右箭头浏览刚输入的文本以对其进行修改。当他按下箭头时,控制台会打印
^[[D^[[C^[[A^[[B
标志。输出:
Please input something and use arrows to move along the text left and right
hello^[[D^[[C^[[A^[[B
如何使箭头键的行为更加人性化,并让人们使用左右箭头在刚输入的文本中导航?
我想,我应该注意termbox-go或gocui之类的库,但是我不知道如何精确地使用它们。
最佳答案
一个简单的示例是 carmark/pseudo-terminal-go
,您可以在其中放置terminal in raw mode并从上,下,左右,左右光标移动中受益。
从 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
参见terminal/terminal.go和
terminal/terminal_test.go
以及 MakeRaw()
关于go - Go中的光标键端子输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30689640/