From ad1f1974503f12010266fe26a683530c753495cb Mon Sep 17 00:00:00 2001 From: jmug Date: Sun, 8 Nov 2026 10:52:00 -0800 Subject: [PATCH] feat: Vertical and horizontal scroll. --- kilo.c | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/kilo.c b/kilo.c index 285c6fe..a6ecaa1 100644 --- a/kilo.c +++ b/kilo.c @@ -41,6 +41,7 @@ typedef struct erow { struct editorConfig { int cx, cy; + int rowoff, coloff; int screenrows; int screencols; int numrows; @@ -253,9 +254,25 @@ void abFree(struct abuf *ab) { /*** output ***/ +void editorScroll() { + // Scrolled up passed the top. + if (E.cy < E.rowoff) + E.rowoff = E.cy; + // Scrolled down passed then bottom. + if (E.cy >= E.rowoff + E.screenrows) + E.rowoff = E.cy - E.screenrows + 1; + // Scrolled passed the left. + if (E.cx < E.coloff) + E.coloff = E.cx; + // Scrolled passed the right. + if (E.cx >= E.coloff + E.screencols) + E.coloff = E.cx - E.screencols + 1; +} + void editorDrawRows(struct abuf *ab) { for (int y = 0; y < E.screenrows; y++) { - if (y >= E.numrows) { + int filerow = y + E.rowoff; + if (filerow >= E.numrows) { // We spilled over the file content. if (E.numrows == 0 && y == E.screenrows / 3) { char welcome[80]; @@ -279,10 +296,10 @@ void editorDrawRows(struct abuf *ab) { abAppend(ab, "~", 1); } } else { - int len = E.row[y].size; - if (len > E.screencols) - len = E.screencols; - abAppend(ab, E.row[y].chars, len); + int len = E.row[filerow].size - E.coloff; + if (len < 0) + len = 0; + abAppend(ab, &E.row[filerow].chars[E.coloff], len); } // Erase the line content to the right of the cursor. @@ -296,6 +313,8 @@ void editorDrawRows(struct abuf *ab) { } void editorRefreshScreen() { + editorScroll(); + struct abuf ab = ABUF_INIT; // Hide cursor. abAppend(&ab, "\x1b[?25l", 6); @@ -306,7 +325,10 @@ void editorRefreshScreen() { // Move cursor to its saved position. char posbuf[32]; - snprintf(posbuf, sizeof(posbuf), "\x1b[%d;%dH", E.cy+1, E.cx+1); + snprintf(posbuf, sizeof(posbuf), "\x1b[%d;%dH", + (E.cy - E.rowoff) + 1, + (E.cx - E.coloff) + 1 + ); abAppend(&ab, posbuf, strlen(posbuf)); @@ -327,9 +349,7 @@ void editorMoveCursor(int key) { } break; case ARROW_RIGHT: - if (E.cx != E.screencols - 1) { - E.cx++; - } + E.cx++; break; case ARROW_UP: if (E.cy != 0) { @@ -337,7 +357,7 @@ void editorMoveCursor(int key) { } break; case ARROW_DOWN: - if (E.cy != E.screenrows - 1) { + if (E.cy < E.numrows) { E.cy++; } break; @@ -386,6 +406,8 @@ void editorProcessKeypress() { void initEditor() { E.cx = 0; E.cy = 0; + E.rowoff = 0; + E.coloff = 0; E.row = NULL; E.numrows = 0; if (getWindowSize(&E.screenrows, &E.screencols) == -1) {