Compare commits

...
3 Commits
Author SHA1 Message Date
jmug 07882d8ba5 feat: Row drawing boilerplate. 2026-10-09 18:03:51 -07:00
jmug 7dc05fce1d refactor: Process keypresses in dedicated function, also clear the screen. 2026-10-09 17:58:32 -07:00
jmug 0a682b779e feat: Exit with ctrl-q. 2026-10-09 17:36:48 -07:00
+58 -10
View File
@@ -7,6 +7,10 @@
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
/*** defines ***/
#define CTRL_KEY(k) ((k) & 0x1f)
/*** data ***/ /*** data ***/
struct termios orig_termios; struct termios orig_termios;
@@ -14,6 +18,11 @@ struct termios orig_termios;
/*** terminal ***/ /*** terminal ***/
void die(const char* s) { void die(const char* s) {
// Clear the whole screen.
write(STDOUT_FILENO, "\x1b[2J", 4);
// Move cursor to top left.
write(STDOUT_FILENO, "\x1b[H", 3);
perror(s); perror(s);
exit(1); exit(1);
} }
@@ -43,22 +52,61 @@ void enableRawMode() {
die("tcsetattr"); die("tcsetattr");
} }
char editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) {
die("read");
}
}
return c;
}
/*** output ***/
void editorDrawRows() {
for (int y = 0; y < 24; y++) {
write(STDOUT_FILENO, "~\r\n", 3);
}
}
void editorRefreshScreen() {
// Clear the whole screen.
write(STDOUT_FILENO, "\x1b[2J", 4);
// Move cursor to top left.
write(STDOUT_FILENO, "\x1b[H", 3);
editorDrawRows();
write(STDOUT_FILENO, "\x1b[H", 3);
}
/*** input ***/
void editorProcessKeypress() {
char c = editorReadKey();
switch (c) {
case CTRL_KEY('q'):
// Clear the whole screen.
write(STDOUT_FILENO, "\x1b[2J", 4);
// Move cursor to top left.
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
}
}
/*** init ***/ /*** init ***/
int main() { int main() {
enableRawMode(); enableRawMode();
while(1) { while(1) {
char c = '\0'; editorRefreshScreen();
if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN) editorProcessKeypress();
die("read");
if (iscntrl(c)) {
printf("%d\r\n", c);
} else {
printf("%d ('%c')\r\n", c, c);
}
if (c == 'q')
break;
} }
return 0; return 0;
} }