Add terminal output helper

This commit is contained in:
Timothy Warren 2021-03-19 12:46:43 -04:00
parent 1161119269
commit 27271a61b3

35
gilo.go
View File

@ -23,20 +23,26 @@ func isCtrl(char rune) bool {
return ord == 0x7f || ord < 0x20 return ord == 0x7f || ord < 0x20
} }
func goRaw() (*term.State, error) { // Put the terminal in
state, err := term.MakeRaw(int(os.Stdin.Fd())) func goRaw() *term.State {
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
return state, err
}
func main() {
// Go to proper raw mode
oldState, err := goRaw()
if err != nil { if err != nil {
panic(err) panic(err)
} }
// Restore canonical mode at exit return oldState
}
// Print a formatted string to stdout, with CRLF line endings for proper terminal formatting
func outLn(format string, a ...interface{}) {
formatted := fmt.Sprintf(format, a...)
fmt.Printf("%s\r\n", formatted)
}
func main() {
// Go to proper raw mode, but restore canonical mode at extit
oldState := goRaw()
defer term.Restore(int(os.Stdin.Fd()), oldState) defer term.Restore(int(os.Stdin.Fd()), oldState)
reader := bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin)
@ -47,16 +53,15 @@ func main() {
panic(err) panic(err)
} }
// Ugliest syntax structure ever?
switch { switch {
case char == 'q': case char == 'q':
fmt.Println("bye!\r") outLn("bye!")
return return
case isCtrl(char): case isCtrl(char):
fmt.Printf("%d\n", char) outLn("%d", char)
default: default:
fmt.Printf("%d ('%c')\n", char, char) outLn("%d ('%c')", char, char)
} }
_ = os.Stdout.Sync()
} }
} }