-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkilo.c
99 lines (70 loc) · 1.56 KB
/
kilo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**** header files ****/
#include <unistd.h> // used for read()
#include <termios.h> // used for tcgetattr() and tcsetattr()
#include <stdlib.h>
#include <errno.h>
#include <stdio.h> // for printf()
#include <ctype.h> // for iscntrl()
/**** defines - macros ****/
#define CTRL_KEY(k) ((k) & 0x1f)
/**** data ****/
struct termios orig_termios;
/**** terminal ****/
void die(const char *s)
{
perror(s);
exit(1);
}
void disableRawMode()
{
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
{
die("tcsetattr");
}
}
void enableRawMode()
{
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1)
{
die("tcgetattr");
}
atexit(disableRawMode);
struct termios raw = orig_termios;
raw.c_iflag &= ~(BRKINT | INPCK | ICRNL | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
{
die("tcsetattr");
}
}
/**** 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;
}
}
return 0;
}