Archived
1
Fork 0
This repository has been archived on 2024-10-07. You can view files and clone it, but cannot push or open issues or pull requests.
kilo/kilo.c

92 lines
1.7 KiB
C
Raw Normal View History

2023-08-22 21:32:16 +00:00
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
2023-08-23 16:36:42 +00:00
#define CTRL_KEY(key) ((key) & 0x1f)
2023-08-22 21:32:16 +00:00
struct termios orig_termios;
2023-08-23 16:36:42 +00:00
void editor_clear_screen() {
write(STDIN_FILENO, "\x1b[2J", 4);
write(STDIN_FILENO, "\x1b[H", 3);
}
2023-08-22 21:32:16 +00:00
void die(const char *s) {
2023-08-23 16:36:42 +00:00
editor_clear_screen();
2023-08-22 21:32:16 +00:00
perror(s);
exit(1);
}
void disable_raw_mode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
die("tcsetattr");
}
void enable_raw_mode() {
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) die("tcgetattr");
atexit(disable_raw_mode);
struct termios raw = orig_termios;
2023-08-23 16:36:42 +00:00
cfmakeraw(&raw);
2023-08-22 21:32:16 +00:00
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}
2023-08-23 16:36:42 +00:00
char editor_read_key() {
char c = '\0';
2023-08-22 21:32:16 +00:00
2023-08-23 16:36:42 +00:00
while (c == '\0')
read(STDIN_FILENO, &c, 1);
2023-08-22 21:32:16 +00:00
2023-08-23 16:36:42 +00:00
return c;
}
void editor_draw_rows() {
int rows = 24;
for (int y = 0; y < rows - 1; y++)
write(STDIN_FILENO, "~\r\n", 3);
write(STDIN_FILENO, "~", 1);
}
void editor_redraw_screen() {
editor_clear_screen();
editor_draw_rows();
2023-08-22 21:32:16 +00:00
2023-08-23 16:36:42 +00:00
write(STDIN_FILENO, "\x1b[H", 3);
}
void editor_process_key() {
char c;
read(STDIN_FILENO, &c, 1);
switch (c) {
case CTRL_KEY('Q'):
editor_clear_screen();
exit(0);
break;
default:
2023-08-22 21:32:16 +00:00
printf("%d\r\n", c);
2023-08-23 16:36:42 +00:00
break;
}
}
2023-08-22 21:32:16 +00:00
2023-08-23 16:36:42 +00:00
int main() {
if (!isatty(STDIN_FILENO)) {
printf("kilo only supports a terminal at standard in. Exiting.");
exit(1);
}
enable_raw_mode();
while (1) {
editor_redraw_screen();
editor_process_key();
2023-08-22 21:32:16 +00:00
}
return 0;
}