1
0
Fork 0

Further cleanup main package

This commit is contained in:
Timothy Warren 2021-03-19 17:39:15 -04:00
parent eb474ddad2
commit 94426483c6
3 changed files with 29 additions and 13 deletions

10
gilo.go
View File

@ -1,9 +1,6 @@
package main package main
import ( import (
"bufio"
"os"
"timshome.page/gilo/internal/editor" "timshome.page/gilo/internal/editor"
"timshome.page/gilo/internal/terminal" "timshome.page/gilo/internal/terminal"
) )
@ -13,9 +10,8 @@ func main() {
oldState := terminal.RawOn() oldState := terminal.RawOn()
defer terminal.RawOff(oldState) defer terminal.RawOff(oldState)
reader := bufio.NewReader(os.Stdin) // The input loop
for editor.ProcessKeypress() {
for editor.ProcessKeypress(reader) { editor.RefreshScreen()
// loop!
} }
} }

View File

@ -2,12 +2,15 @@ package editor
import ( import (
"bufio" "bufio"
"os"
"timshome.page/gilo/internal/char" "timshome.page/gilo/internal/char"
"timshome.page/gilo/internal/terminal" "timshome.page/gilo/internal/terminal"
) )
func readKey(reader *bufio.Reader) (rune, int) { var reader = bufio.NewReader(os.Stdin)
func readKey() (rune, int) {
ch, size, err := reader.ReadRune() ch, size, err := reader.ReadRune()
if err != nil { if err != nil {
panic(err) panic(err)
@ -16,14 +19,24 @@ func readKey(reader *bufio.Reader) (rune, int) {
return ch, size return ch, size
} }
func ProcessKeypress(reader *bufio.Reader) bool { func RefreshScreen() {
ch, _ := readKey(reader) terminal.ANSICode(terminal.ClearScreen)
terminal.ANSICode(terminal.ResetCursor)
}
func ProcessKeypress() bool {
ch, _ := readKey()
// Clean up on exit
if ch == char.Ctrl('q') {
terminal.ANSICode(terminal.ClearScreen)
terminal.ANSICode(terminal.ResetCursor)
return false
}
// Ugliest syntax structure ever? // Ugliest syntax structure ever?
switch { switch {
case ch == char.Ctrl('q'):
terminal.OutLn("bye!")
return false
case char.IsCtrl(ch): case char.IsCtrl(ch):
terminal.OutLn("%d", ch) terminal.OutLn("%d", ch)
default: default:

View File

@ -7,6 +7,9 @@ import (
"golang.org/x/term" "golang.org/x/term"
) )
const ClearScreen = "2J"
const ResetCursor = "H"
// Is this a valid interactive terminal? // Is this a valid interactive terminal?
func check() { func check() {
if !term.IsTerminal(int(os.Stdin.Fd())) { if !term.IsTerminal(int(os.Stdin.Fd())) {
@ -34,6 +37,10 @@ func RawOff(oldState *term.State) {
} }
} }
func ANSICode (code string) {
fmt.Printf("\x1b[%s", code)
}
// 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...)