safe-c-std/programs/edit.c
Raw file ยท Directory on GitHub
1// Build from the repo root: build.noindex/bin/clang -fsafe-c -isysroot $(xcrun --show-sdk-path) safe-c-std/programs/edit.c -o /tmp/edit
2/* A small text editor: edit FILE
3 Arrows, Home, End, Page Up, Page Down; ^S save, ^X quit, ^Z undo, ^Y redo, ^F find, ^G find again.
4 The file is one text. An edit replaces some bytes of it with others; undo does the opposite. */
5#include "../args.h"
6#include "../file.h"
7#include <sys/ioctl.h>
8#include <termios.h>
9#include <unistd.h>
10
11/* At 'at', 'removed' bytes became 'added' bytes; both are kept in history.bytes, one after the other. */
12struct change { size_t at, removed, added, bytes; };
13/* vec.h is included once per element type: this makes struct changes and changes_add, _at, _get, _set, _pop, _free. */
14#define VEC_NAME changes
15#define VEC_TYPE struct change
16#include "../vec.h"
17struct history {
18 struct changes changes;
19 struct text bytes;
20 size_t now; /* changes before this one are done, the others undone */
21 size_t saved;
22};
23struct editor {
24 struct text doc;
25 struct history history;
26 struct text screen, find, message;
27 size_t cursor, top, left;
28 int rows, columns, quitting, done;
29};
30
31/* The checker proves this frees everything e owns: leave a field out and it rejects the return. */
32static void editor_free(struct editor *_Empties e) {
33 text_free(&e->doc);
34 text_free(&e->history.bytes);
35 changes_free(&e->history.changes);
36 text_free(&e->screen);
37 text_free(&e->find);
38 text_free(&e->message);
39}
40
41enum key { KEY_END = -1, KEY_UP = 1000, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_HOME, KEY_LAST, KEY_PAGE_UP, KEY_PAGE_DOWN, KEY_DELETE, KEY_OTHER };
42#define CTRL_KEY(c) ((c) & 0x1f)
43
44/* ---- the terminal (the system calls are the program's only unsafe code) ---- */
45
46_Trusted __unsafe static int terminal_raw(struct termios *before) {
47 if (!isatty(0) || tcgetattr(0, before) != 0)
48 return 0;
49 struct termios raw = *before;
50 raw.c_iflag &= ~(tcflag_t)(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
51 raw.c_oflag &= ~(tcflag_t)OPOST;
52 raw.c_cflag |= CS8;
53 raw.c_lflag &= ~(tcflag_t)(ECHO | ICANON | IEXTEN | ISIG);
54 return tcsetattr(0, TCSAFLUSH, &raw) == 0;
55}
56_Trusted __unsafe static void terminal_restore(const struct termios *before) { tcsetattr(0, TCSAFLUSH, before); }
57_Trusted __unsafe static int terminal_size(int *rows, int *columns) {
58 struct winsize w = {0, 0, 0, 0};
59 if (ioctl(1, TIOCGWINSZ, &w) != 0 || w.ws_row < 3 || w.ws_col < 8)
60 return 0;
61 *rows = w.ws_row;
62 *columns = w.ws_col;
63 return 1;
64}
65
66static int read_key(void) {
67 int c = getc(stdin);
68 if (c != 27)
69 return c == EOF ? KEY_END : c;
70 if (getc(stdin) != '[')
71 return KEY_OTHER;
72 c = getc(stdin);
73 switch (c) {
74 case 'A': return KEY_UP;
75 case 'B': return KEY_DOWN;
76 case 'C': return KEY_RIGHT;
77 case 'D': return KEY_LEFT;
78 case 'H': return KEY_HOME;
79 case 'F': return KEY_LAST;
80 }
81 if (c < '0' || c > '9' || getc(stdin) != '~')
82 return KEY_OTHER;
83 switch (c) {
84 case '1': case '7': return KEY_HOME;
85 case '4': case '8': return KEY_LAST;
86 case '3': return KEY_DELETE;
87 case '5': return KEY_PAGE_UP;
88 case '6': return KEY_PAGE_DOWN;
89 }
90 return KEY_OTHER;
91}
92
93/* ---- changes ---- */
94
95/* Forgets what was undone, and keeps a change that is about to be made. */
96static int remember(struct history *h, size_t at, struct str removed, struct str added) {
97 struct change c = {at, removed.len, added.len, 0};
98 while (h->changes.len > h->now) {
99 struct change undone;
100 changes_pop(&h->changes, &undone);
101 h->bytes.len = undone.bytes;
102 if (h->saved > h->changes.len)
103 h->saved = (size_t)-1;
104 }
105 c.bytes = h->bytes.len;
106 if (!text_add(&h->bytes, removed.p, removed.len) || !text_add(&h->bytes, added.p, added.len) ||
107 !changes_add(&h->changes, c)) {
108 h->bytes.len = c.bytes;
109 return 0;
110 }
111 h->now++;
112 return 1;
113}
114
115static void replace(struct editor *e, size_t at, size_t n, struct str with) {
116 if (!remember(&e->history, at, str_part(text_str(&e->doc), at, n), with) ||
117 !text_splice(&e->doc, at, n, with)) {
118 text_set(&e->message, STR("out of memory"));
119 return;
120 }
121 e->cursor = at + with.len;
122}
123
124static void undo(struct editor *e) {
125 struct change c;
126 if (e->history.now == 0)
127 return;
128 changes_get(&e->history.changes, e->history.now - 1, &c);
129 struct str old = str_part(text_str(&e->history.bytes), c.bytes, c.removed);
130 if (!text_splice(&e->doc, c.at, c.added, old))
131 return;
132 e->history.now--;
133 e->cursor = c.at + c.removed;
134}
135
136static void redo(struct editor *e) {
137 struct change c;
138 if (!changes_get(&e->history.changes, e->history.now, &c))
139 return;
140 struct str new = str_part(text_str(&e->history.bytes), c.bytes + c.removed, c.added);
141 if (!text_splice(&e->doc, c.at, c.removed, new))
142 return;
143 e->history.now++;
144 e->cursor = c.at + c.added;
145}
146
147/* ---- lines ---- */
148
149static size_t line_start(struct str s, size_t at) {
150 while (at > 0 && at <= s.len && s.p[at - 1] != '\n')
151 at--;
152 return at;
153}
154static size_t line_end(struct str s, size_t at) {
155 return at + str_find(str_part(s, at, s.len), '\n');
156}
157/* The start of the line 'by' lines on from the one at is in. */
158static size_t line_move(struct str s, size_t at, int by) {
159 at = line_start(s, at);
160 for (; by < 0 && at > 0; by++)
161 at = line_start(s, at - 1);
162 for (; by > 0 && line_end(s, at) < s.len; by--)
163 at = line_end(s, at) + 1;
164 return at;
165}
166static void move_lines(struct editor *e, int by) {
167 struct str s = text_str(&e->doc);
168 size_t column = e->cursor - line_start(s, e->cursor);
169 size_t to = line_move(s, e->cursor, by), end = line_end(s, to);
170 e->cursor = to + column < end ? to + column : end;
171}
172
173/* ---- the screen ---- */
174
175static void draw_line(struct text *out, struct str line, size_t left, size_t columns) {
176 struct str s = str_part(line, left, columns);
177 for (size_t i = 0; i < s.len; i++) {
178 char c = s.p[i];
179 if ((unsigned char)c < 32 || c == 127)
180 c = '?';
181 text_add(out, &c, 1);
182 }
183 struct str clear = STR("\x1b[K\r\n");
184 text_add(out, clear.p, clear.len);
185}
186
187static void draw(struct editor *e) {
188 struct str doc = text_str(&e->doc);
189 size_t start = line_start(doc, e->cursor), column = e->cursor - start;
190 size_t wide = (size_t)e->columns;
191 if (start < e->top)
192 e->top = start;
193 while (line_move(doc, e->top, e->rows - 2) < start)
194 e->top = line_move(doc, e->top, 1);
195 if (column < e->left)
196 e->left = column;
197 if (column >= e->left + wide)
198 e->left = column - wide + 1;
199
200 text_set(&e->screen, STR("\x1b[?25l\x1b[H"));
201 int row = 0, cursor_row = 0;
202 for (size_t at = e->top; row < e->rows - 1; row++) {
203 if (at > doc.len) {
204 draw_line(&e->screen, STR("~"), 0, wide);
205 continue;
206 }
207 if (at == start)
208 cursor_row = row;
209 size_t end = line_end(doc, at);
210 draw_line(&e->screen, str_part(doc, at, end - at), e->left, wide);
211 at = end + 1;
212 }
213 /* The bottom row: the message, or the keys when there is none; on the right,
214 the cursor's line and column and how far through the file that line is. */
215 size_t line = 1, lines = 1;
216 for (size_t i = 0; i < doc.len; i++)
217 if (doc.p[i] == '\n')
218 lines++, line += i < e->cursor;
219 char where[64];
220 int w = snprintf(where, sizeof where, "Ln %zu, Col %zu %zu%%", line, column + 1, line * 100 / lines);
221 size_t right = w > 0 && (size_t)w < sizeof where && (size_t)w < wide ? (size_t)w : 0;
222 /* An if, not a ?: picking the message or the keys: through a ?: the checker
223 cannot tell that the text added is not part of e->screen itself. */
224 struct str bar = STR("\x1b[97;44m"), plain = STR("\x1b[m"); /* the bar: bright white on blue */
225 text_add(&e->screen, bar.p, bar.len);
226 struct str shown = STR("^S save ^X quit ^Z undo ^Y redo ^F find ^G again");
227 if (e->message.len > 0) {
228 struct str message = str_part(text_str(&e->message), 0, wide - right);
229 text_add(&e->screen, message.p, message.len);
230 shown = message;
231 } else {
232 shown = str_part(shown, 0, wide - right);
233 text_add(&e->screen, shown.p, shown.len);
234 }
235 for (size_t i = shown.len + right; i < wide; i++)
236 text_add(&e->screen, " ", 1);
237 text_add(&e->screen, where, right);
238 text_add(&e->screen, plain.p, plain.len);
239 char at[40];
240 int n = snprintf(at, sizeof at, "\x1b[K\x1b[%d;%zuH\x1b[?25h", cursor_row + 1, column - e->left + 1);
241 if (n > 0 && (size_t)n < sizeof at)
242 text_add(&e->screen, at, (size_t)n);
243 struct str all = text_str(&e->screen);
244 fwrite(all.p, 1, all.len, stdout);
245 fflush(stdout);
246}
247
248/* ---- commands ---- */
249
250/* Reads what to find on the bottom row: 1, or 0 if it was given up. */
251static int ask(struct editor *e) {
252 text_set(&e->find, STR(""));
253 for (;;) {
254 text_set(&e->message, STR("find: "));
255 struct str a = text_str(&e->find);
256 text_add(&e->message, a.p, a.len);
257 draw(e);
258 int k = read_key();
259 if (k == '\r' || k == '\n')
260 return e->find.len > 0;
261 if (k == KEY_END || k == KEY_OTHER || k == CTRL_KEY('c'))
262 return 0;
263 if ((k == 127 || k == CTRL_KEY('h')) && e->find.len > 0)
264 e->find.len--;
265 if (k >= 32 && k < 127) {
266 char c = (char)k;
267 text_add(&e->find, &c, 1);
268 }
269 }
270}
271
272static void find_next(struct editor *e) {
273 struct str doc = text_str(&e->doc), what = text_str(&e->find);
274 if (what.len == 0)
275 return;
276 for (size_t i = 1; i <= doc.len; i++) {
277 size_t at = (e->cursor + i) % (doc.len + 1);
278 if (str_eq(str_part(doc, at, what.len), what)) {
279 e->cursor = at;
280 return;
281 }
282 }
283 text_set(&e->message, STR("not found"));
284}
285
286static void press(struct editor *e, int k, const char *__null_terminated path) {
287 struct str doc = text_str(&e->doc);
288 int was_quitting = e->quitting;
289 e->quitting = 0;
290 text_set(&e->message, STR(""));
291 switch (k) {
292 case KEY_END: e->done = 1; break;
293 case KEY_UP: move_lines(e, -1); break;
294 case KEY_DOWN: move_lines(e, 1); break;
295 case KEY_PAGE_UP: move_lines(e, 2 - e->rows); break;
296 case KEY_PAGE_DOWN: move_lines(e, e->rows - 2); break;
297 case KEY_LEFT: e->cursor -= e->cursor > 0; break;
298 case KEY_RIGHT: e->cursor += e->cursor < doc.len; break;
299 case KEY_HOME: e->cursor = line_start(doc, e->cursor); break;
300 case KEY_LAST: e->cursor = line_end(doc, e->cursor); break;
301 case KEY_DELETE:
302 if (e->cursor < doc.len)
303 replace(e, e->cursor, 1, STR(""));
304 break;
305 case 127:
306 case CTRL_KEY('h'):
307 if (e->cursor > 0)
308 replace(e, e->cursor - 1, 1, STR(""));
309 break;
310 case CTRL_KEY('z'): undo(e); break;
311 case CTRL_KEY('y'): redo(e); break;
312 case CTRL_KEY('f'):
313 if (ask(e))
314 find_next(e);
315 break;
316 case CTRL_KEY('g'): find_next(e); break;
317 case CTRL_KEY('s'):
318 if (file_write(path, doc) == 0) {
319 e->history.saved = e->history.now;
320 text_set(&e->message, STR("saved"));
321 } else {
322 text_set(&e->message, STR("could not save"));
323 }
324 break;
325 case CTRL_KEY('x'): // not ^Q: VS Code's terminal takes ^Q and quits VS Code
326 if (e->history.saved == e->history.now || was_quitting) {
327 e->done = 1;
328 } else {
329 e->quitting = 1;
330 text_set(&e->message, STR("not saved; ^X again to quit"));
331 }
332 break;
333 case '\r':
334 case '\n': replace(e, e->cursor, 0, STR("\n")); break;
335 default:
336 if (k == '\t' || (k >= 32 && k < 256)) {
337 char c = (char)k;
338 struct str s = {&c, 1};
339 replace(e, e->cursor, 0, s);
340 }
341 }
342}
343
344int main(int argc, char *__null_terminated *__counted_by(argc) argv) {
345 if (argc != 2)
346 return fputs("usage: edit FILE\n", stderr), 1;
347 struct editor e = {.rows = 24, .columns = 80};
348 (void)file_read(argv[1], &e.doc); /* a new file starts empty */
349 struct termios before;
350 int raw = terminal_raw(&before);
351 while (!e.done) {
352 terminal_size(&e.rows, &e.columns);
353 draw(&e);
354 press(&e, read_key(), argv[1]);
355 }
356 fputs("\x1b[2J\x1b[H", stdout);
357 if (raw)
358 terminal_restore(&before);
359 editor_free(&e);
360 return 0;
361}
362