commit 6c865f04f3cce5ed4502fc32b8e2a044e6d33ec2
parent bb1400f138800794a5f2dc0e953e09098eecf2bc
Author: afify <hassan@afify.dev>
Date: Wed, 9 Mar 2022 16:29:30 +0300
[feat] add buffer before write
Diffstat:
M | nasmfm.c | | | 71 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------- |
1 file changed, 60 insertions(+), 11 deletions(-)
diff --git a/nasmfm.c b/nasmfm.c
@@ -6,18 +6,23 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include <termios.h>
#include <unistd.h>
/* macros */
#define CTRL_KEY(k) ((k)&0x1f)
-#define CLEAR_SCREEN write(STDOUT_FILENO, "\x1b[2J", 4);
-#define CURSOR_TOP_LEFT write(STDOUT_FILENO, "\x1b[H", 3);
+#define CLEAR_SCREEN abAppend(&ab, "\x1b[2J", 4);
+#define CURSOR_TOP_LEFT abAppend(&ab, "\x1b[H", 3);
+#define CURSOR_HIDE abAppend(&ab, "\x1b[?25l", 6);
+#define CURSOR_SHOW abAppend(&ab, "\x1b[?25h", 6);
+#define ABUF_INIT \
+ { \
+ NULL, 0 \
+ }
/* typedef */
/* function declarations */
-/* global variables */
-/* function implementations */
typedef struct {
int rows;
@@ -25,8 +30,31 @@ typedef struct {
struct termios orig_termios;
} Term;
+struct abuf {
+ char *b;
+ int len;
+};
+
+/* global variables */
Term term;
+/* function implementations */
+void
+abAppend(struct abuf *ab, const char *s, int len)
+{
+ char *new = realloc(ab->b, ab->len + len);
+ if (new == NULL)
+ return;
+ memcpy(&new[ab->len], s, len);
+ ab->b = new;
+ ab->len += len;
+}
+void
+abFree(struct abuf *ab)
+{
+ free(ab->b);
+}
+
void
die(const char *s)
{
@@ -61,14 +89,32 @@ enableRawMode()
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr");
}
+
void
-editorDrawRows()
+editorDrawRows(struct abuf *ab)
{
int y;
for (y = 0; y < term.rows; y++) {
- write(STDOUT_FILENO, "~", 1);
+ if (y == term.rows / 3) {
+ char welcome[80];
+ int welcomelen = snprintf(welcome, sizeof(welcome),
+ "Kilo editor -- version nasmfm");
+ if (welcomelen > term.cols)
+ welcomelen = term.cols;
+ int padding = (term.cols - welcomelen) / 2;
+ if (padding) {
+ abAppend(ab, "~", 1);
+ padding--;
+ }
+ while (padding--)
+ abAppend(ab, " ", 1);
+ abAppend(ab, welcome, welcomelen);
+ } else {
+ abAppend(ab, "~", 1);
+ }
+ abAppend(ab, "\x1b[K", 3);
if (y < term.rows - 1) {
- write(STDOUT_FILENO, "\r\n", 2);
+ abAppend(ab, "\r\n", 2);
}
}
}
@@ -76,10 +122,13 @@ editorDrawRows()
void
editorRefreshScreen()
{
- CLEAR_SCREEN
- CURSOR_TOP_LEFT
- editorDrawRows();
- CURSOR_TOP_LEFT
+ struct abuf ab = ABUF_INIT;
+ //abAppend(&ab, "\x1b[2J", 4);
+ abAppend(&ab, "\x1b[H", 3);
+ editorDrawRows(&ab);
+ abAppend(&ab, "\x1b[H", 3);
+ write(STDOUT_FILENO, ab.b, ab.len);
+ abFree(&ab);
}
char