diff --git a/kilo.c b/kilo.c index 9f3bb12..7333c64 100644 --- a/kilo.c +++ b/kilo.c @@ -18,6 +18,11 @@ struct termios orig_termios; /*** terminal ***/ 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); exit(1); } @@ -47,22 +52,51 @@ void enableRawMode() { 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 editorRefreshScreen() { + // Clear the whole screen. + write(STDOUT_FILENO, "\x1b[2J", 4); + // Move cursor to top left. + 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 ***/ int main() { enableRawMode(); while(1) { - char c = '\0'; - if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN) - die("read"); - if (iscntrl(c)) { - printf("%d\r\n", c); - } else { - printf("%d ('%c')\r\n", c, c); - } - if (c == CTRL_KEY('q')) - break; + editorRefreshScreen(); + editorProcessKeypress(); } return 0; }