From ebf6b38a97a4d2396de0c73bd0bbb6b1831167fe Mon Sep 17 00:00:00 2001 From: Timothy J Warren Date: Thu, 25 Mar 2021 12:46:53 -0400 Subject: [PATCH] Move cursor with wasd keys --- editor/editor.go | 22 +++++++++++++++++++++- terminal/ansi.go | 11 +++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/editor/editor.go b/editor/editor.go index 3289f67..4d229c7 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -36,8 +36,8 @@ func (e *editor) RefreshScreen() { ab.append(terminal.ResetCursor) e.drawRows(ab) + ab.append(terminal.MoveCursor(e.cursor.x, e.cursor.y)) - ab.append(terminal.ResetCursor) ab.append(terminal.ShowCursor) terminal.Write(ab.toString()) @@ -53,6 +53,13 @@ func (e *editor) ProcessKeypress() bool { return false } + switch ch { + case 'w', 'a', 's', 'd': + e.moveCursor(ch) + default: + // Do nothing! + } + return true } @@ -86,4 +93,17 @@ func (e *editor) drawRows(ab *buffer) { ab.append("\r\n") } } +} + +func (e *editor) moveCursor (key rune) { + switch key { + case 'a': + e.cursor.x -= 1 + case 'd': + e.cursor.x += 1 + case 'w': + e.cursor.y -= 1 + case 's': + e.cursor.y += 1 + } } \ No newline at end of file diff --git a/terminal/ansi.go b/terminal/ansi.go index 0a87565..17c76eb 100644 --- a/terminal/ansi.go +++ b/terminal/ansi.go @@ -1,3 +1,4 @@ +// ANSI Terminal Escape Codes and helpers package terminal import "fmt" @@ -11,4 +12,14 @@ const ResetCursor = "\x1b[H" func Code (s string) string { return fmt.Sprintf("\x1b[%s", s) +} + + +// Move the terminal cursor to the 0-based coordinate +func MoveCursor(x int, y int) string { + // Allow 0-based indexing, the terminal code is 1-based + x += 1 + y += 1 + + return Code(fmt.Sprintf("%d;%dH", y, x)) } \ No newline at end of file