Compare commits
3
Commits
908eb1ef1c
...
07882d8ba5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07882d8ba5 | ||
|
|
7dc05fce1d | ||
|
|
0a682b779e |
@@ -7,6 +7,10 @@
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/*** defines ***/
|
||||
|
||||
#define CTRL_KEY(k) ((k) & 0x1f)
|
||||
|
||||
/*** data ***/
|
||||
|
||||
struct termios orig_termios;
|
||||
@@ -14,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);
|
||||
}
|
||||
@@ -43,22 +52,61 @@ 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 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 ***/
|
||||
|
||||
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 == 'q')
|
||||
break;
|
||||
editorRefreshScreen();
|
||||
editorProcessKeypress();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user