gilo/gilo.go

88 lines
1.4 KiB
Go
Raw Normal View History

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 {
2021-03-19 16:02:05 -04:00
if !isAscii(char) {
2021-03-19 12:03:55 -04:00
return false
}
2021-03-19 16:02:05 -04:00
ord := int(char)
2021-03-19 12:03:55 -04:00
return ord == 0x7f || ord < 0x20
}
2021-03-19 16:02:05 -04:00
// Return the input code of a Ctrl-key chord.
func ctrlKey(char rune) rune {
ord := int(char)
raw := ord & 0x1f
if !isCtrl(rune(raw)) {
return 0
}
return rune(raw)
}
// Put the terminal in raw mode
func rawOn() *term.State {
2021-03-19 12:46:43 -04:00
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
}
2021-03-19 16:02:05 -04:00
// Restore the terminal to canonical mode
func rawOff(oldState *term.State) {
err := term.Restore(int(os.Stdin.Fd()), oldState)
if err != nil {
panic(err)
}
}
2021-03-19 12:46:43 -04:00
// 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
2021-03-19 16:02:05 -04:00
oldState := rawOn()
defer rawOff(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 16:02:05 -04:00
case char == ctrlKey('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
}