Files
CSPP-coursework/final/editor.c
T
FantasyPvP 214dfc66a5 bugfixes
2024-11-07 13:52:28 +00:00

112 lines
3.0 KiB
C

#include <stdbool.h>
#include <stdlib.h>
#include "dynstr.h"
#include <ncurses.h>
typedef struct {
uint32_t lines;
uint32_t screen_line;
uint32_t screen_col;
bool editmode;
String_t* buffer;
} Editor;
Editor new_editor() {
Editor e;
e.lines = 0;
e.screen_line = 0;
e.screen_col = 0;
e.editmode = false;
String_t lines = str_from_chars("");
int linenum = 0;
e.buffer = str_lines(&lines, &linenum);
e.lines = linenum;
str_dealloc(&lines);
addstr("");
return e;
}
Editor editor_from(char* input_string) {
Editor e;
e.lines = 0;
e.screen_line = 0;
e.screen_col = 0;
e.editmode = false;
int linenum = 0;
String_t lines = str_from_chars(input_string);
e.buffer = str_lines(&lines, &linenum);
e.lines = (size_t)linenum;
fprintf(stderr, "BUFFER: %s", to_chars(&e.buffer[2]));
str_dealloc(&lines);
// String_t s = str_from_chars(input_string);
// int linen = 0;
// String_t* lines = str_lines(&s, &linen);
// for (int i=0; i < linen; i++) {
// fprintf(stderr, "%s", to_chars(&lines[i]));
// }
// e.lines = (size_t)linen;
// e.buffer = lines;
// str_dealloc(&s);
addstr(input_string);
return e;
}
void move_cursor(Editor* self, int x, int y) {
fprintf(stderr, "lns %d, line %d, col %d, mode %d", self->lines, self->screen_line, self->screen_col, self->editmode);
fprintf(stderr, "line: %s", to_chars(&self->buffer[self->screen_line]));
if (y != 0
&& (int)(self->screen_line) + y >= 0
&& self->screen_line + y <= self->lines)
{
self->screen_line += y;
int line_width = str_len(&self->buffer[self->screen_line]);
if (self->screen_col > line_width) {
self->screen_col = line_width;
}
} else if ((int)(self->screen_col) + x < 0) {
fprintf(stderr, "going off left side");
if (self->screen_line - 1 >= 0) {
self->screen_line -= 1;
self->screen_col = str_len(&self->buffer[self->screen_line]);
}
} else if (self->screen_col + x > str_len(&self->buffer[self->screen_line])) {
if (self->screen_line + 1 <= self->lines) {
self->screen_col = 0;
self->screen_line += 1;
}
} else if (x != 0) {
self->screen_col += x;
}
fprintf(stderr, "lns %d, line %d, col %d, mode %d", self->lines, self->screen_line, self->screen_col, self->editmode);
move(self->screen_line, self->screen_col);
}
void delchar(Editor* self) {
str_remove(&self->buffer[self->screen_line], self->screen_col);
delch();
}
void addchar(Editor* self, char c) {
insch(c);
// insert the character into the string at the given index
if (self->screen_line == self->lines) {
// reallocate self->buffer to be 1 larger
self->lines++;
self->buffer = realloc(self->buffer, sizeof(String_t) * (self->lines + 1));
}
str_insert(&self->buffer[self->screen_line], self->screen_col, c);
move_cursor(self, 1, 0);
}
String_t* to_string(Editor* self) {
}