Quit with Ctrl-Q

This commit is contained in:
Timothy Warren 2021-03-19 16:02:05 -04:00
parent 27271a61b3
commit c37af9a6aa

30
gilo.go
View File

@ -23,8 +23,20 @@ func isCtrl(char rune) bool {
return ord == 0x7f || ord < 0x20 return ord == 0x7f || ord < 0x20
} }
// Put the terminal in // Return the input code of a Ctrl-key chord.
func goRaw() *term.State { 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 {
oldState, err := term.MakeRaw(int(os.Stdin.Fd())) oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil { if err != nil {
panic(err) panic(err)
@ -33,6 +45,14 @@ func goRaw() *term.State {
return oldState return oldState
} }
// Restore the terminal to canonical mode
func rawOff(oldState *term.State) {
err := term.Restore(int(os.Stdin.Fd()), oldState)
if err != nil {
panic(err)
}
}
// Print a formatted string to stdout, with CRLF line endings for proper terminal formatting // Print a formatted string to stdout, with CRLF line endings for proper terminal formatting
func outLn(format string, a ...interface{}) { func outLn(format string, a ...interface{}) {
formatted := fmt.Sprintf(format, a...) formatted := fmt.Sprintf(format, a...)
@ -42,8 +62,8 @@ func outLn(format string, a ...interface{}) {
func main() { func main() {
// Go to proper raw mode, but restore canonical mode at extit // Go to proper raw mode, but restore canonical mode at extit
oldState := goRaw() oldState := rawOn()
defer term.Restore(int(os.Stdin.Fd()), oldState) defer rawOff(oldState)
reader := bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin)
@ -55,7 +75,7 @@ func main() {
// Ugliest syntax structure ever? // Ugliest syntax structure ever?
switch { switch {
case char == 'q': case char == ctrlKey('q'):
outLn("bye!") outLn("bye!")
return return
case isCtrl(char): case isCtrl(char):