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 ***/ /*** data ***/
struct editorConfig { struct editorConfig {
int cx, cy;
int screenrows; int screenrows;
int screencols; int screencols;
struct termios orig_termios; struct termios orig_termios;
@@ -70,6 +71,27 @@ char editorReadKey() {
die("read"); 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; return c;
} }
@@ -152,7 +174,7 @@ void editorDrawRows(struct abuf *ab) {
int welcomelen = snprintf( int welcomelen = snprintf(
welcome, welcome,
sizeof(welcome), sizeof(welcome),
"Kil editor -- version %s", "Kilo editor -- version %s",
KILO_VERSION KILO_VERSION
); );
if (welcomelen > E.screencols) if (welcomelen > E.screencols)
@@ -183,13 +205,17 @@ void editorRefreshScreen() {
struct abuf ab = ABUF_INIT; struct abuf ab = ABUF_INIT;
// Hide cursor. // Hide cursor.
abAppend(&ab, "\x1b[?25l", 6); abAppend(&ab, "\x1b[?25l", 6);
// Move cursor to top left. // Move cursor to top left to begin drawing.
abAppend(&ab, "\x1b[H", 3); abAppend(&ab, "\x1b[H", 3);
editorDrawRows(&ab); editorDrawRows(&ab);
// Return cursor to top left after drawing. // Move cursor to its saved position.
abAppend(&ab, "\x1b[H", 3); char posbuf[32];
snprintf(posbuf, sizeof(posbuf), "\x1b[%d;%dH", E.cy+1, E.cx+1);
abAppend(&ab, posbuf, strlen(posbuf));
// Show cursor again. // Show cursor again.
abAppend(&ab, "\x1b[?25h", 6); abAppend(&ab, "\x1b[?25h", 6);
@@ -199,6 +225,23 @@ void editorRefreshScreen() {
/*** input ***/ /*** 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() { void editorProcessKeypress() {
char c = editorReadKey(); char c = editorReadKey();
@@ -211,12 +254,20 @@ void editorProcessKeypress() {
exit(0); exit(0);
break; break;
case 'w':
case 'a':
case 's':
case 'd':
editorMoveCursor(c);
break;
} }
} }
/*** init ***/ /*** init ***/
void initEditor() { void initEditor() {
E.cx = 0;
E.cy = 0;
if (getWindowSize(&E.screenrows, &E.screencols) == -1) { if (getWindowSize(&E.screenrows, &E.screencols) == -1) {
die("getWindowSize"); die("getWindowSize");
} }