1
0
Fork 0

Quit with Ctrl-Q

This commit is contained in:
Timothy Warren 2021-03-19 16:02:05 -04:00
parent 27271a61b3
commit c37af9a6aa
1 changed files with 27 additions and 7 deletions

34
gilo.go
View File

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