Files
build-your-own-editor/kilo.c
T

65 lines
1.2 KiB
C
Raw Normal View History

2026-10-09 17:29:18 -07:00
/*** includes ***/
2026-10-09 12:28:16 -07:00
#include <ctype.h>
2026-10-09 17:29:18 -07:00
#include <errno.h>
2026-10-09 12:28:16 -07:00
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
2026-10-09 17:29:18 -07:00
/*** data ***/
2026-10-09 12:28:16 -07:00
struct termios orig_termios;
2026-10-09 17:29:18 -07:00
/*** terminal ***/
void die(const char* s) {
perror(s);
exit(1);
}
2026-10-09 12:28:16 -07:00
void disableRawMode() {
2026-10-09 17:29:18 -07:00
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
die("tcsetattr");
2026-10-09 12:28:16 -07:00
}
void enableRawMode() {
2026-10-09 17:29:18 -07:00
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1)
die("tcgetattr");
2026-10-09 12:28:16 -07:00
atexit(disableRawMode);
struct termios raw = orig_termios;
2026-10-09 17:29:18 -07:00
2026-10-09 12:28:16 -07:00
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
2026-10-09 17:29:18 -07:00
// Sets timeouts for read()
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr");
2026-10-09 12:28:16 -07:00
}
2026-10-09 17:29:18 -07:00
/*** init ***/
2026-10-09 12:28:16 -07:00
int main() {
enableRawMode();
2026-10-09 17:29:18 -07:00
while(1) {
char c = '\0';
if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN)
die("read");
2026-10-09 12:28:16 -07:00
if (iscntrl(c)) {
printf("%d\r\n", c);
} else {
printf("%d ('%c')\r\n", c, c);
}
2026-10-09 17:29:18 -07:00
if (c == 'q')
break;
2026-10-09 12:28:16 -07:00
}
return 0;
}