Quit with Ctrl-Q
This commit is contained in:
parent
27271a61b3
commit
c37af9a6aa
34
gilo.go
34
gilo.go
@ -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):
|
||||
|
Loading…
Reference in New Issue
Block a user