1
0
Fork 0

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
}
@ -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
}
}

View File

@ -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))
}