-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
141 lines (119 loc) · 3.25 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ncurses.h>
#include <sys/stat.h>
#include "gapbuffer.h"
#define KEY_ESCAPE 27
void usage(char* invocation) {
fprintf(stderr, "Usage: %s file\n", invocation);
exit(1);
}
void display_buffer(struct GapBuffer* buffer) {
erase();
// display the buffer contents
int row = 0;
int col = 0;
for (int i = 0; i < gb_charc(buffer); i++) {
char ch = gb_get(buffer, i);
if (ch == '\n') {
row++;
col = 0;
} else {
mvaddch(row, col, ch);
col++;
}
}
refresh();
}
int main(int argc, char** argv) {
if (argc < 2) {
usage(argv[0]);
}
char* path = argv[1];
struct GapBuffer buffer;
struct stat path_stat;
stat(path, &path_stat);
if (!S_ISREG(path_stat.st_mode)) {
gb_init(&buffer, 256);
} else {
gb_init(&buffer, path_stat.st_size + 256);
char* fileContents = malloc(sizeof(path_stat.st_size));
FILE* file = fopen(path, "r");
fread(fileContents, 1, path_stat.st_size, file);
fclose(file);
gb_insert_chars(&buffer, fileContents, path_stat.st_size);
}
initscr();
noecho();
keypad(stdscr, TRUE);
cbreak();
bool shouldExit = FALSE;
int index = 0;
int row = 0;
int col = 0;
int c;
while (!shouldExit) {
display_buffer(&buffer);
move(row, col);
gb_move_gap(&buffer, index);
switch (c = getch()) {
case KEY_ESCAPE: {
FILE* file = fopen(path, "w+");
gb_fprint(&buffer, file);
fclose(file);
shouldExit = TRUE;
} break;
case KEY_BACKSPACE: {
gb_delete_backward(&buffer, 1);
}
case KEY_LEFT: {
if (index > 0) {
if (col > 0) {
col--;
} else {
// move up a row
row--;
int i;
for (i = index - 2; i > -1; i--) {
if (gb_get(&buffer, i) == '\n') {
break;
}
}
col = index - (i + 2);
}
index--;
}
} break;
case KEY_RIGHT: {
if (index < gb_charc(&buffer)) {
if (gb_get(&buffer, index) == '\n') {
// move to start of next line
col = 0;
row++;
} else {
col++;
}
index++;
}
} break;
case KEY_UP: {
} break;
case KEY_DOWN: {
} break;
default: {
gb_insert(&buffer, (char) c);
if (c == '\n') {
row++;
col = 0;
} else {
col++;
}
index++;
}
}
}
endwin();
return 0;
}