Skip to content

Commit

Permalink
pound: implement backspace
Browse files Browse the repository at this point in the history
  • Loading branch information
ivop committed Sep 10, 2024
1 parent 8033bce commit a29fa0b
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions apps/pound.c
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ void die(char *reason, bool clear) {
cpm_warmboot();
}

void __zfree_null(void) {
die("zfree NULL", true);
}

// -------------------- ROW OPERATIONS --------------------

// return false when out of memory
Expand Down Expand Up @@ -74,6 +78,18 @@ bool editorAppendRow(char *s, size_t len) {
return E.dirty = true;
}

void editorFreeRow(struct erow *row) {
zfree(row->chars);
}

void editorDelRow(int at) {
if (at < 0 || at >= E.numrows) return;
editorFreeRow(&E.row[at]);
memmove(&E.row[at], &E.row[at + 1], sizeof(struct erow) * (E.numrows - at - 1));
E.numrows--;
E.dirty = true;
}

bool editorRowInsertChar(struct erow *row, int at, uint8_t c) {
if (at < 0 || at > row->size) at = row->size;

Expand All @@ -88,6 +104,25 @@ bool editorRowInsertChar(struct erow *row, int at, uint8_t c) {
return E.dirty = true;
}

// return false when out of memory
//
bool editorRowAppendString(struct erow *row, char *s, size_t len) {
void *tmp = zrealloc(row->chars, row->size + len + 1);
if (!tmp) return false;
row->chars = tmp;
memcpy(&row->chars[row->size], s, len);
row->size += len;
row->chars[row->size] = '\0';
return E.dirty = true;
}

void editorRowDelChar(struct erow *row, int at) {
if (at < 0 || at >= row->size) return;
memmove(&row->chars[at], &row->chars[at + 1], row->size - at);
row->size--;
E.dirty = true;;
}

// -------------------- EDITOR OPERATIONS --------------------

void editorDrawStatusMsg(char *msg);
Expand All @@ -104,6 +139,27 @@ void editorInsertChar(uint8_t c) {
editorDrawStatusMsg(OUT_OF_MEMORY_STRING);
}

void editorDelChar(void) {
if (E.cy == E.numrows) return;
if (E.cx == 0 && E.cy == 0) return;

struct erow *row = &E.row[E.cy];
if (E.cx > 0) {
editorRowDelChar(row, E.cx - 1);
E.cx--;
} else {
E.cx = E.row[E.cy - 1].size;
if (!editorRowAppendString(&E.row[E.cy - 1], row->chars, row->size))
goto failed;
editorDelRow(E.cy);
E.cy--;
}
return;

failed:
editorDrawStatusMsg(OUT_OF_MEMORY_STRING);
}

// -------------------- FILE INPUT/OUTPUT --------------------

static inline uint8_t write_byte(FCB *fcb, uint8_t c, uint8_t *opos) {
Expand Down Expand Up @@ -414,6 +470,12 @@ void editorProcessKeypress(void) {
editorMoveCursor(c == CTRL('R') ? CTRL('E') : CTRL('X'));
}
break;

case 127:
case CTRL('H'):
editorDelChar();
break;

case CTRL('K'):
ctrlk = true;
break;
Expand Down

0 comments on commit a29fa0b

Please sign in to comment.