From 257f90cff9f73efed81cd36b8e627bed74897112 Mon Sep 17 00:00:00 2001 From: Hadeed Ahmad Date: Mon, 11 Sep 2023 16:02:21 +0500 Subject: [PATCH] Fix rx_to_cx bug --- src/commands.c | 2 ++ src/erow.c | 18 +++++++----------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/commands.c b/src/commands.c index 570f7a6..56de385 100644 --- a/src/commands.c +++ b/src/commands.c @@ -82,6 +82,7 @@ void command_insert_char(char c) { input_process_key(ARROW_RIGHT); } +// TODO: Is this many simulated keypresses necessary? Is it bad? void command_delete_char(void) { if (E.current_buf->cy == E.current_buf->n_rows) input_process_key(ARROW_LEFT); @@ -94,6 +95,7 @@ void command_delete_char(void) { struct erow *prow = E.current_buf->rows[E.current_buf->cy - 1]; + input_process_key(HOME); input_process_key(ARROW_UP); cursor_move(E.current_buf, prow->n_chars, 0); diff --git a/src/erow.c b/src/erow.c index 9da9f7f..c47b3db 100644 --- a/src/erow.c +++ b/src/erow.c @@ -55,9 +55,8 @@ int erow_cx_to_rx(struct erow *erow, int cx) { cx = CLAMP(cx, 0, (int) erow->n_chars); int rx = 0; - - for (char *c = erow->chars; c < erow->chars + cx; c++) { - if (*c == '\t') + for (int c_cx = 0; c_cx < cx; c_cx++) { + if (erow->chars[c_cx] == '\t') rx += KILO_TAB_STOP - (rx % KILO_TAB_STOP); else rx++; @@ -70,20 +69,17 @@ int erow_rx_to_cx(struct erow *erow, int rx) { if (erow == NULL) return 0; - int cx = 0, c_rx = 0; - while ((size_t) cx < erow->n_chars) { + rx = CLAMP(rx, 0, (int) erow->n_rchars); + + int cx = 0; + for (int c_rx = 0; c_rx < rx; cx++) { if (erow->chars[cx] == '\t') c_rx += KILO_TAB_STOP - (c_rx % KILO_TAB_STOP); else c_rx++; - - cx++; - - if (c_rx >= rx) - return cx; } - return erow->n_chars; + return cx; } void erow_free(struct erow *erow) {