+#define _GNU_SOURCE
+#include <string.h>
#include <assert.h>
#include "edit.h"
unsigned i = 0;
Rune r;
FILE* in = (!strcmp(path,"-") ? stdin : fopen(path, "rb"));
- while (RUNE_EOF != (r = fgetrune(in)))
- buf_ins(buf, i++, r);
- fclose(in);
+ buf->path = (in == stdin ? NULL : strdup(path));
+ if (in != NULL) {
+ while (RUNE_EOF != (r = fgetrune(in)))
+ buf_ins(buf, i++, r);
+ fclose(in);
+ }
+ /* Make sure it ends with a newline */
+ if (r != '\n')
+ buf_ins(buf, i, (Rune)'\n');
buf->insert_mode = false;
}
+void buf_save(Buf* buf) {
+ if (!buf->path) return;
+ unsigned end = buf_end(buf);
+ FILE* out = fopen(buf->path, "wb");
+ if (!out) return;
+ for (unsigned i = 0; i < end; i++)
+ fputrune(buf_get(buf, i), out);
+ fclose(out);
+}
+
void buf_resize(Buf* buf, size_t sz) {
/* allocate the new buffer and gap */
Buf copy = *buf;
/* Buffer management functions
*****************************************************************************/
typedef struct buf {
+ char* path;
bool insert_mode; /* tracks current mode */
size_t bufsize; /* size of the buffer in runes */
Rune* bufstart; /* start of the data buffer */
} Buf;
void buf_load(Buf* buf, char* path);
+void buf_save(Buf* buf);
void buf_init(Buf* buf);
void buf_clr(Buf* buf);
void buf_del(Buf* buf, unsigned pos);
--- /dev/null
+Testing edit and save
static void special_keys(Rune key);
static void control_keys(Rune key);
+static void vi_keys(Rune key);
void handle_key(Rune key) {
/* ignore invalid keys */
else if (Buffer.insert_mode)
buf_ins(&Buffer, CursorPos++, key);
else
- (void)0;
-
+ vi_keys(key);
}
static void special_keys(Rune key) {
switch (key) {
case KEY_ESCAPE: Buffer.insert_mode = false; break;
case KEY_BACKSPACE: buf_del(&Buffer, --CursorPos); break;
+ case KEY_CTRL_W: buf_save(&Buffer); break;
+ case KEY_CTRL_Q: exit(0); break;
default: buf_ins(&Buffer, CursorPos++, key); break;
}
}
+
+static void vi_keys(Rune key) {
+ (void)key;
+}