Archived
1
Fork 0

Finish some of chapter 3

This commit is contained in:
Hadeed 2023-08-23 21:36:42 +05:00
parent 282af378f2
commit 8b20212ee2
2 changed files with 53 additions and 16 deletions

View file

@ -1,4 +1,4 @@
CCFLAGS := -Wall -Wextra -Wpedantic -Werror -std=c99 CCFLAGS := -Wall -Wextra -Wpedantic -Werror -std=c99 -D_DEFAULT_SOURCE
kilo: kilo.c kilo: kilo.c
$(CC) $(CCFLAGS) kilo.c -o kilo $(CC) $(CCFLAGS) kilo.c -o kilo

67
kilo.c
View file

@ -5,11 +5,18 @@
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
#define CTRL_KEY(key) ((key) & 0x1f)
struct termios orig_termios; struct termios orig_termios;
void editor_clear_screen() {
write(STDIN_FILENO, "\x1b[2J", 4);
write(STDIN_FILENO, "\x1b[H", 3);
}
void die(const char *s) { void die(const char *s) {
editor_clear_screen();
perror(s); perror(s);
exit(1); exit(1);
} }
@ -24,30 +31,60 @@ void enable_raw_mode() {
atexit(disable_raw_mode); atexit(disable_raw_mode);
struct termios raw = orig_termios; struct termios raw = orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); cfmakeraw(&raw);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr"); if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
} }
char editor_read_key() {
char c = '\0';
while (c == '\0')
read(STDIN_FILENO, &c, 1);
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();
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:
printf("%d\r\n", c);
break;
}
}
int main() { int main() {
if (!isatty(STDIN_FILENO)) {
printf("kilo only supports a terminal at standard in. Exiting.");
exit(1);
}
enable_raw_mode(); enable_raw_mode();
while (1) { while (1) {
char c = '\0'; editor_redraw_screen();
if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN) die("read"); editor_process_key();
if (iscntrl(c))
printf("%d\r\n", c);
else
printf("%d ('%c')\r\n", c, c);
if (c == 'q') break;
} }
return 0; return 0;