2021-03-18 16:30:04 -04:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-03-18 19:15:19 -04:00
|
|
|
"bufio"
|
|
|
|
"fmt"
|
2021-03-18 16:30:04 -04:00
|
|
|
"golang.org/x/term"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2021-03-19 12:03:55 -04:00
|
|
|
func isAscii(char rune) bool {
|
|
|
|
ord := int(char)
|
|
|
|
|
|
|
|
return ord < 0x80
|
|
|
|
}
|
|
|
|
|
|
|
|
func isCtrl(char rune) bool {
|
|
|
|
if ! isAscii(char) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
ord:= int(char)
|
|
|
|
|
|
|
|
return ord == 0x7f || ord < 0x20
|
|
|
|
}
|
|
|
|
|
2021-03-19 12:46:43 -04:00
|
|
|
// Put the terminal in
|
|
|
|
func goRaw() *term.State {
|
|
|
|
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
|
2021-03-18 16:30:04 -04:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2021-03-19 12:46:43 -04:00
|
|
|
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()
|
2021-03-18 16:30:04 -04:00
|
|
|
defer term.Restore(int(os.Stdin.Fd()), oldState)
|
2021-03-18 19:15:19 -04:00
|
|
|
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
|
|
|
|
|
|
for {
|
|
|
|
char, _, err := reader.ReadRune()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2021-03-19 12:46:43 -04:00
|
|
|
// Ugliest syntax structure ever?
|
2021-03-18 19:15:19 -04:00
|
|
|
switch {
|
2021-03-19 08:45:33 -04:00
|
|
|
case char == 'q':
|
2021-03-19 12:46:43 -04:00
|
|
|
outLn("bye!")
|
2021-03-18 19:15:19 -04:00
|
|
|
return
|
2021-03-19 12:03:55 -04:00
|
|
|
case isCtrl(char):
|
2021-03-19 12:46:43 -04:00
|
|
|
outLn("%d", char)
|
2021-03-19 12:03:55 -04:00
|
|
|
default:
|
2021-03-19 12:46:43 -04:00
|
|
|
outLn("%d ('%c')", char, char)
|
2021-03-18 19:15:19 -04:00
|
|
|
}
|
|
|
|
}
|
2021-03-18 16:30:04 -04:00
|
|
|
}
|