-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraw.c
More file actions
120 lines (115 loc) · 3.47 KB
/
raw.c
File metadata and controls
120 lines (115 loc) · 3.47 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include "headers.h"
void die(const char *s)
{
perror(s);
exit(1);
}
struct termios orig_termios;
void disableRawMode()
{
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
die("tcsetattr");
}
/**
* Enable row mode for the terminal
* The ECHO feature causes each key you type to be printed to the terminal, so you can see what you’re typing.
* Terminal attributes can be read into a termios struct by tcgetattr().
* After modifying them, you can then apply them to the terminal using tcsetattr().
* The TCSAFLUSH argument specifies when to apply the change: in this case, it waits for all pending output to be written to the terminal, and also discards any input that hasn’t been read.
* The c_lflag field is for “local flags”
*/
void enableRawMode()
{
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1)
die("tcgetattr");
atexit(disableRawMode);
struct termios raw = orig_termios;
raw.c_lflag &= ~(ICANON | ECHO);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr");
}
/**
* stdout and stdin are buffered we disable buffering on that
* After entering in raw mode we read characters one by one
* Up arrow keys and down arrow keys are represented by 3 byte escape codes
* starting with ascii number 27 i.e. ESC key
* This way we interpret arrow keys
* Tabs are usually handled by the term, but here we are simulating tabs for the sake of simplicity
* Backspace move the cursor one control character to the left
* @return
*/
int rawmode()
{
int fg_present;
char *inp = malloc(sizeof(char) * 100);
strcpy(inp, "a");
char c;
while (1)
{
fg_present = 0;
if (c == 'x')
exit(0);
setbuf(stdout, NULL);
enableRawMode();
// printf("Prompt>");
memset(inp, '\0', 100);
int pt = 0;
while (read(STDIN_FILENO, &c, 1) == 1)
{
if (iscntrl(c))
{
if (c == 10)
break;
else if (c == 27)
{
char buf[3];
buf[2] = 0;
if (read(STDIN_FILENO, buf, 2) == 2)
{ // length of escape code
printf("\rarrow key: %s", buf);
}
}
else if (c == 127)
{ // backspace
if (pt > 0)
{
if (inp[pt - 1] == 9)
{
for (int i = 0; i < 7; i++)
{
printf("\b");
}
}
inp[--pt] = '\0';
printf("\b \b");
}
}
else if (c == 9)
{ // TAB character
inp[pt++] = c;
for (int i = 0; i < 8; i++)
{ // TABS should be 8 spaces
printf(" ");
}
}
else if (c == 4)
{
exit(0);
}
else
{
printf("%d\n", c);
}
}
else
{
inp[pt++] = c;
printf("%c", c);
if (c == 'x')
exit(0);
}
}
disableRawMode();
}
return 1;
}