kilo

Kilo: minimal text editor written in C
git clone git://git.dimitrijedobrota.com/kilo.git
Log | Files | Refs

commit 156653a2d53a2abe82c5383810000db0127243bb
parent 06dacdfa12189128fb57b9f611c2eff6e3d4169b
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sun,  9 Apr 2023 09:30:55 +0200

Add some utils for better readability

Diffstat:
Mkilo.c | 26+++++++++++++++++++-------
1 file changed, 19 insertions(+), 7 deletions(-)

diff --git a/kilo.c b/kilo.c @@ -16,6 +16,19 @@ #include <time.h> #include <unistd.h> +/*** utils ***/ + +#define MIN(x, y) ((x) < (y) ? (x) : (y)) +#define MAX(x, y) ((x) > (y) ? (x) : (y)) + +#define RCLAMP(a, x, y) (MAX((x), MIN((y), (a)))) +#define RCLAMP_LEFT(a, x) (MAX((a), (x))) +#define RCLAMP_RIGHT(a, x) (MIN((a), (x))) + +#define CLAMP(a, x, y) ((a) = RCLAMP(a, x, y)) +#define CLAMP_LEFT(a, x) ((a) = RCLAMP_LEFT(a, x)) +#define CLAMP_RIGHT(a, x) ((a) = RCLAMP_RIGHT(a, x)) + /*** defines ***/ #define KILO_VERSION "0.0.1" @@ -297,7 +310,7 @@ void editorMoveCursor(int key) { row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; int rowlen = row ? row->size : 0; - if (E.cx > rowlen) { E.cx = rowlen; } + CLAMP_RIGHT(E.cx, rowlen); } void editorProcessKeypress() { @@ -342,9 +355,9 @@ void editorProcessKeypress() { void editorScroll() { E.rx = 0; if (E.cy < E.numrows) { E.rx = editorRowCxToRx(&E.row[E.cy], E.cx); } - if (E.cy < E.rowoff) { E.rowoff = E.cy; } + CLAMP_RIGHT(E.rowoff, E.cy); if (E.cy >= E.rowoff + E.screenrows) { E.rowoff = E.cy - E.screenrows + 1; } - if (E.rx < E.coloff) { E.coloff = E.rx; } + CLAMP_RIGHT(E.coloff, E.rx); if (E.rx >= E.coloff + E.screencols) { E.coloff = E.rx - E.screencols + 1; } } @@ -369,8 +382,7 @@ void editorDrawRows(struct abuf *ab) { } } else { int len = E.row[filerow].rsize - E.coloff; - if (len < 0) len = 0; - if (len > E.screencols) len = E.screencols; + CLAMP(len, 0, E.screencols); abAppend(ab, E.row[filerow].render + E.coloff, len); } abAppend(ab, "\x1b[K", 3); // clear current row @@ -384,7 +396,7 @@ void editorDrawStatusBar(struct abuf *ab) { int len = snprintf(status, sizeof(status), "%.20s - %d lines", E.filename ? E.filename : "[No Name]", E.numrows); int rlen = snprintf(rstatus, sizeof(rstatus), "%d/%d", E.cy + 1, E.numrows); - if (len > E.screencols) len = E.screencols; + CLAMP_RIGHT(len, E.screencols); abAppend(ab, status, len); while (len < E.screencols) { if (E.screencols - len == rlen) { @@ -402,7 +414,7 @@ void editorDrawStatusBar(struct abuf *ab) { void editorDrawMessageBar(struct abuf *ab) { abAppend(ab, "\x1b[K", 3); int msglen = strlen(E.statusmsg); - if (msglen > E.screencols) msglen = E.screencols; + CLAMP_RIGHT(msglen, E.screencols); if (msglen && time(NULL) - E.statusmsg_time < 5) abAppend(ab, E.statusmsg, msglen); }