refactor: Process keypresses in dedicated function, also clear the screen.
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user