feat: Cursor movement (arrow keys for now).

This commit is contained in:
jmug
2026-10-26 12:12:06 -07:00
parent 9fe7f35932
commit e27f9c08de
+55 -4
View File
@@ -18,6 +18,7 @@
/*** data ***/
struct editorConfig {
int cx, cy;
int screenrows;
int screencols;
struct termios orig_termios;
@@ -70,6 +71,27 @@ char editorReadKey() {
die("read");
}
}
// Read arrow key escape sequences as single characters.
if (c == '\x1b') {
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1)
return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
if (seq[0] == '[') {
switch (seq[1]) {
case 'A': return 'w';
case 'B': return 's';
case 'C': return 'd';
case 'D': return 'a';
}
}
return '\x1b';
}
return c;
}
@@ -152,7 +174,7 @@ void editorDrawRows(struct abuf *ab) {
int welcomelen = snprintf(
welcome,
sizeof(welcome),
"Kil editor -- version %s",
"Kilo editor -- version %s",
KILO_VERSION
);
if (welcomelen > E.screencols)
@@ -183,13 +205,17 @@ void editorRefreshScreen() {
struct abuf ab = ABUF_INIT;
// Hide cursor.
abAppend(&ab, "\x1b[?25l", 6);
// Move cursor to top left.
// Move cursor to top left to begin drawing.
abAppend(&ab, "\x1b[H", 3);
editorDrawRows(&ab);
// Return cursor to top left after drawing.
abAppend(&ab, "\x1b[H", 3);
// Move cursor to its saved position.
char posbuf[32];
snprintf(posbuf, sizeof(posbuf), "\x1b[%d;%dH", E.cy+1, E.cx+1);
abAppend(&ab, posbuf, strlen(posbuf));
// Show cursor again.
abAppend(&ab, "\x1b[?25h", 6);
@@ -199,6 +225,23 @@ void editorRefreshScreen() {
/*** input ***/
void editorMoveCursor(char key) {
switch (key) {
case 'a':
E.cx--;
break;
case 'd':
E.cx++;
break;
case 'w':
E.cy--;
break;
case 's':
E.cy++;
break;
}
}
void editorProcessKeypress() {
char c = editorReadKey();
@@ -211,12 +254,20 @@ void editorProcessKeypress() {
exit(0);
break;
case 'w':
case 'a':
case 's':
case 'd':
editorMoveCursor(c);
break;
}
}
/*** init ***/
void initEditor() {
E.cx = 0;
E.cy = 0;
if (getWindowSize(&E.screenrows, &E.screencols) == -1) {
die("getWindowSize");
}