Skip to content

Commit

Permalink
Speed up window drawing.
Browse files Browse the repository at this point in the history
We were repeatedly calling gb_linecol_to_pos for each cell, which is
linear in the number of lines. gb_linecol_to_pos could be optimized, but
for now just inline the work and do it incrementally.

Closes #54.
  • Loading branch information
isbadawi committed Jun 6, 2021
1 parent d5a4cd3 commit 2eceda3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
27 changes: 23 additions & 4 deletions draw.c
Original file line number Diff line number Diff line change
Expand Up @@ -313,17 +313,36 @@ static void window_draw_leaf(struct window *window, struct editor *editor) {
struct syntax syntax;
struct syntax_token token = {SYNTAX_TOKEN_NONE, 0, 0};
bool highlight = syntax_init(&syntax, window->buffer);

size_t line_pos = 0;
for (size_t i = 0; i < window->top; ++i) {
line_pos += gb->lines->buf[i] + 1;
}

for (size_t y = 0; y < rows; ++y) {
size_t line = y + window->top;
window_draw_line_number(window, line);

size_t cols = (size_t) max(0,
min((ssize_t) gb_utf8len_line(gb, line) - (ssize_t) window->left, (ssize_t) w));
if (y > 0) {
line_pos += gb->lines->buf[line - 1] + 1;
}

size_t tabs = 0;
size_t linelen = gb_utf8len_line(gb, line_pos);
size_t cols = (size_t)max(0,
min((ssize_t)linelen - (ssize_t)window->left, (ssize_t)w));

size_t pos = line_pos;
for (size_t i = 0; i < window->left; ++i) {
pos += gb_utf8len(gb, pos);
}

for (size_t x = 0; x < cols; ++x) {
size_t x_offset = tabs * (tabstop - 1) + numberwidth + x;
size_t col = x + window->left;
size_t pos = gb_linecol_to_pos(gb, line, col);

if (x > 0) {
pos += gb_utf8len(gb, pos);
}

tb_color fg = COLOR_WHITE;
tb_color bg = COLOR_DEFAULT;
Expand Down
3 changes: 1 addition & 2 deletions gap.c
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,7 @@ size_t gb_linecol_to_pos(struct gapbuf *gb, size_t line, size_t column) {
return offset;
}

size_t gb_utf8len_line(struct gapbuf *gb, size_t line) {
size_t pos = gb_linecol_to_pos(gb, line, 0);
size_t gb_utf8len_line(struct gapbuf *gb, size_t pos) {
size_t len = 0;
while (gb_getchar(gb, pos) != '\n') {
pos += gb_utf8len(gb, pos);
Expand Down
2 changes: 1 addition & 1 deletion gap.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ size_t gb_utf8next(struct gapbuf *gb, size_t pos);
// Returns the offset of the previous utf8 start byte before pos.
size_t gb_utf8prev(struct gapbuf *gb, size_t pos);
// Returns the number of the unicode codepoints for the given line.
size_t gb_utf8len_line(struct gapbuf *gb, size_t line);
size_t gb_utf8len_line(struct gapbuf *gb, size_t line_pos);

// Reads n characters starting at offset pos.
struct buf *gb_getstring(struct gapbuf *gb, size_t pos, size_t n);
Expand Down

0 comments on commit 2eceda3

Please sign in to comment.