Files
CSPP-coursework/final/editor.c
T
2024-11-08 10:36:07 +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 editor_from(String_t input_string) {
Editor e;
e.lines = 0;
e.screen_line = 0;
e.screen_col = 0;
e.editmode = false;
int linenum = 0;
e.buffer = str_lines(&input_string, &linenum);
e.lines = (size_t)linenum;
str_dealloc(&input_string);
for (size_t i = 0; i < e.lines; i++) {
// adding the line number
char line_no[5];
snprintf(line_no, 5, "%-5d", i + 1);
// adding the line of text to the buffer
addstr(line_no);
addch(' ');
addstr(to_chars(&e.buffer[i]));
addstr("\n");
}
return e;
}
Editor new_editor() {
return editor_from(str_new());
}
void move_cursor(Editor* self, int x, int y) {
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) {
if ((int)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;
}
move(self->screen_line, self->screen_col + 5);
}
void delchar(Editor* self) {
str_remove(&self->buffer[self->screen_line], self->screen_col);
delch();
}
void pressed_enter(Editor* self) {
move_cursor(self, 1, 0);
}
void addchar(Editor* self, char c) {
if (self->screen_line == self->lines) {
move(self->screen_line, 0);
char line_no[5];
snprintf(line_no, 5, "%-5d", self->screen_line + 1);
// adding the line of text to the buffer
addstr(line_no);
addch(' ');
move(self->screen_line, self->screen_col + 5);
fprintf(stderr, "buffer full\n");
// reallocate self->buffer to be 1 larger
self->lines++;
self->buffer = realloc(self->buffer, sizeof(String_t) * (self->lines + 1));
// allocate the memory space for the new line and add it to the buffer
self->buffer[self->screen_line] = str_new();
for (size_t i = 0; i < self->lines; i++) {
fprintf(stderr, "size: %d\n", (&self->buffer[i])->size);
}
fprintf(stderr, "ok!");
}
insch(c);
// insert the character into the string at the given index
str_insert(&self->buffer[self->screen_line], self->screen_col, c);
move_cursor(self, 1, 0);
}
String_t* to_string(Editor* self) {
}