在Go语言中进行光标键终端输入

huangapple go评论83阅读模式
英文:

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-gogocui,但我不知道如何确切地将它们用于此目的。

英文:

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,在这里你可以将终端设置为原始模式,并从完整的上下左右光标移动中受益。

terminal.go#NewTerminal()

// NewTerminal 在给定的ReadWriter上运行一个VT100终端。如果ReadWriter是
// 一个本地终端,那么该终端必须首先被设置为原始模式。
// prompt是一个在每个输入行开头写入的字符串(即
// "> ")。
func NewTerminal(c io.ReadWriter, prompt string) *Terminal 

请参阅terminal/terminal.goterminal/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()

huangapple
  • 本文由 发表于 2015年6月7日 10:58:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/30689640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定