Cleanup main package

This commit is contained in:
Timothy Warren 2021-03-19 16:39:49 -04:00
parent 0b05522b05
commit 2f73596d35
2 changed files with 11 additions and 64 deletions

73
gilo.go
View File

@ -2,68 +2,15 @@ package main
import (
"bufio"
"fmt"
"golang.org/x/term"
"os"
"timshome.page/gilo/internal/rune"
"timshome.page/gilo/internal/terminal"
)
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
}
// 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)
}
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...)
fmt.Printf("%s\r\n", formatted)
}
func main() {
// Go to proper raw mode, but restore canonical mode at extit
oldState := rawOn()
defer rawOff(oldState)
// Go to proper raw mode, but restore canonical mode at exit
oldState := terminal.RawOn()
defer terminal.RawOff(oldState)
reader := bufio.NewReader(os.Stdin)
@ -75,13 +22,13 @@ func main() {
// Ugliest syntax structure ever?
switch {
case char == ctrlKey('q'):
outLn("bye!")
case char == rune.Ctrl('q'):
terminal.OutLn("bye!")
return
case isCtrl(char):
outLn("%d", char)
case rune.IsCtrl(char):
terminal.OutLn("%d", char)
default:
outLn("%d ('%c')", char, char)
terminal.OutLn("%d ('%c')", char, char)
}
}
}

2
go.mod
View File

@ -1,4 +1,4 @@
module timshomepage.net/gilo
module timshome.page/gilo
go 1.16