Move cursor with wasd keys

This commit is contained in:
Timothy Warren 2021-03-25 12:46:53 -04:00
parent ca81c5a8cf
commit ebf6b38a97
2 changed files with 32 additions and 1 deletions

View File

@ -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
}
@ -87,3 +94,16 @@ func (e *editor) drawRows(ab *buffer) {
}
}
}
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
}
}

View File

@ -1,3 +1,4 @@
// ANSI Terminal Escape Codes and helpers
package terminal
import "fmt"
@ -12,3 +13,13 @@ 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))
}