From e27f9c08defad233cc2bcc9dfeb3932930508e70 Mon Sep 17 00:00:00 2001 From: jmug Date: Mon, 26 Oct 2026 12:12:06 -0700 Subject: [PATCH] feat: Cursor movement (arrow keys for now). --- kilo.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/kilo.c b/kilo.c index 4ecd316..62c34da 100644 --- a/kilo.c +++ b/kilo.c @@ -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"); }