kilo

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

commit 40afadb33793d415717d0e7910863aba7242c148
parent fb4217ce51a604a0d05a852d9c5bd804cc359bf0
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sun,  9 Apr 2023 19:46:02 +0200

Add line numbing

Diffstat:
Mkilo.c | 29+++++++++++++++++++++++++++--
1 file changed, 27 insertions(+), 2 deletions(-)

diff --git a/kilo.c b/kilo.c @@ -7,6 +7,7 @@ #include <ctype.h> #include <errno.h> #include <fcntl.h> +#include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> @@ -30,6 +31,20 @@ #define CLAMP_LEFT(a, x) ((a) = RCLAMP_LEFT(a, x)) #define CLAMP_RIGHT(a, x) ((a) = RCLAMP_RIGHT(a, x)) +int numberOfDigits(int n) { + if (n < 0) n = (n == INT_MIN) ? INT_MAX : -n; + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; + if (n < 1000000000) return 9; + return 10; +} + /*** defines ***/ #define KILO_VERSION "0.0.1" @@ -112,6 +127,7 @@ struct editorConfig { int screenrows; int screencols; int numrows; + int row_digits; erow *row; int dirty; char *filename; @@ -564,9 +580,11 @@ void editorInsertRow(int at, char *s, size_t len) { E.row[at].render = NULL; E.row[at].hl = NULL; E.row[at].hl_open_comment = 0; + editorUpdateRow(&E.row[at]); E.numrows++; + E.row_digits = numberOfDigits(E.numrows); E.dirty++; } @@ -581,7 +599,9 @@ void editorDelRow(int at) { editorFreeRow(&E.row[at]); memmove(&E.row[at], &E.row[at + 1], sizeof(erow) * (E.numrows - at - 1)); for (int j = at; j < E.numrows - 1; j++) E.row[j].idx--; + E.numrows--; + E.row_digits = numberOfDigits(E.numrows); E.dirty++; } @@ -984,8 +1004,12 @@ void editorDrawRows(struct abuf *ab) { abAppend(ab, "~", 1); } } else { + char num_buf[E.row_digits + 1]; + int left = sprintf(num_buf, "%*d ", E.row_digits, filerow + 1); + abAppend(ab, num_buf, left); + int len = E.row[filerow].rsize - E.coloff; - CLAMP(len, 0, E.screencols); + CLAMP(len, 0, E.screencols - left); char *c = &E.row[filerow].render[E.coloff]; unsigned char *hl = &E.row[filerow].hl[E.coloff]; int current_color = -1; @@ -1073,7 +1097,7 @@ void editorRefreshScreen() { char buf[32]; snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, - (E.rx - E.coloff) + 1); + (E.rx - E.coloff) + E.row_digits + 2); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\x1b[?25h", 6); // show cursor @@ -1099,6 +1123,7 @@ void initEditor() { E.rowoff = 0; E.coloff = 0; E.numrows = 0; + E.row_digits = 1; E.row = NULL; E.dirty = 0; E.filename = NULL;