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

View File

@ -2,12 +2,15 @@ package editor
import (
"bufio"
"os"
"timshome.page/gilo/internal/char"
"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()
if err != nil {
panic(err)
@ -16,14 +19,24 @@ func readKey(reader *bufio.Reader) (rune, int) {
return ch, size
}
func ProcessKeypress(reader *bufio.Reader) bool {
ch, _ := readKey(reader)
func RefreshScreen() {
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?
switch {
case ch == char.Ctrl('q'):
terminal.OutLn("bye!")
return false
case char.IsCtrl(ch):
terminal.OutLn("%d", ch)
default:

View File

@ -7,6 +7,9 @@ import (
"golang.org/x/term"
)
const ClearScreen = "2J"
const ResetCursor = "H"
// Is this a valid interactive terminal?
func check() {
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
func OutLn(format string, a ...interface{}) {
formatted := fmt.Sprintf(format, a...)