From 94426483c66b01b95c64f345c753376bc2db2db1 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 19 Mar 2021 17:39:15 -0400 Subject: [PATCH] Further cleanup main package --- gilo.go | 10 +++------- internal/editor/editor.go | 25 +++++++++++++++++++------ internal/terminal/terminal.go | 7 +++++++ 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/gilo.go b/gilo.go index 1a10b38..e5a0a83 100644 --- a/gilo.go +++ b/gilo.go @@ -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() } } diff --git a/internal/editor/editor.go b/internal/editor/editor.go index 4563a9c..b7c10cb 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -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: diff --git a/internal/terminal/terminal.go b/internal/terminal/terminal.go index 5c6a817..fa9f735 100644 --- a/internal/terminal/terminal.go +++ b/internal/terminal/terminal.go @@ -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...)