From c4af9bda7cbc789f6d5ce1b32d75efdb222f68c6 Mon Sep 17 00:00:00 2001 From: Hadeed Ahmad Date: Sun, 24 Sep 2023 04:50:45 +0500 Subject: [PATCH] Make newline behavior consistent with vim Assume every line ends with a newline, including the last line --- hello.c | 5 +++++ src/buffer.c | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 hello.c diff --git a/hello.c b/hello.c new file mode 100644 index 0000000..b4af39a --- /dev/null +++ b/hello.c @@ -0,0 +1,5 @@ +#include + +int main() { + printf("hello world\n"); +} diff --git a/src/buffer.c b/src/buffer.c index 1943295..6b9fb66 100644 --- a/src/buffer.c +++ b/src/buffer.c @@ -62,6 +62,9 @@ ERRCODE buffer_read_file(struct buffer *buffer, const char *filename) { break; } + if (buffer->rows[buffer->n_rows - 1]->n_chars == 0) + buffer_delete_row(buffer, buffer->n_rows - 1); + END: if (file != NULL) fclose(file); @@ -186,7 +189,6 @@ static char *buffer_get_string(struct buffer *buffer, size_t *n_chars) { for (int i = 0; i < buffer->n_rows; i++) *n_chars += buffer->rows[i]->n_chars + 1; - *n_chars -= 1; char *write_buffer = malloc(*n_chars); for (int i = 0, j = 0; i < buffer->n_rows; i++) { @@ -194,8 +196,7 @@ static char *buffer_get_string(struct buffer *buffer, size_t *n_chars) { memcpy(write_buffer + j, row->chars, row->n_chars); j += row->n_chars; - if (i < buffer->n_rows - 1) - write_buffer[j++] = '\n'; + write_buffer[j++] = '\n'; } return write_buffer;