英文:
Cursor key terminal input in Go
问题
我正在为终端创建一个Go应用程序。以下代码要求用户在终端输入文本。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
for {
fmt.Println("请输入一些内容,并使用箭头键在文本中左右移动")
in := bufio.NewReader(os.Stdin)
_, err := in.ReadString('\n')
if err != nil {
fmt.Println(err)
}
}
}
问题是用户无法使用左右箭头键沿着刚输入的文本移动以进行修改。当用户按下箭头键时,控制台会打印出^[[D^[[C^[[A^[[B
这样的符号。
输出结果:
请输入一些内容,并使用箭头键在文本中左右移动
hello^[[D^[[C^[[A^[[B
如何使箭头键更加用户友好,并允许用户使用左右箭头键在刚输入的文本中导航?
我猜想,我应该注意一些库,比如termbox-go或gocui,但我不知道如何确切地将它们用于此目的。
英文:
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.
答案1
得分: 3
一个更简单的例子是carmark/pseudo-terminal-go
,在这里你可以将终端设置为原始模式,并从完整的上下左右光标移动中受益。
// NewTerminal 在给定的ReadWriter上运行一个VT100终端。如果ReadWriter是
// 一个本地终端,那么该终端必须首先被设置为原始模式。
// prompt是一个在每个输入行开头写入的字符串(即
// "> ")。
func NewTerminal(c io.ReadWriter, prompt string) *Terminal
请参阅terminal/terminal.go和terminal/terminal_test.go
,以及MakeRaw()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论