Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Gurrium committed Dec 27, 2022
1 parent db1f78b commit 4d3e9b2
Showing 1 changed file with 42 additions and 12 deletions.
54 changes: 42 additions & 12 deletions kilo.c
Expand Up @@ -15,6 +15,13 @@

#define CTRL_KEY(k) ((k)&0x1f)

enum editorKey {
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN
};

/*** data ***/

struct editorConfig {
Expand Down Expand Up @@ -56,13 +63,36 @@ void enableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}

char editorReadKey() {
int editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) die("read");
}
return c;

if (c == '\x1b') {
char seq[3];

if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b';

if (seq[0] == '[') {
switch (seq[1]) {
case 'A':
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
}
}

return '\x1b';
} else {
return c;
}
}

int getCursorPosition(int *rows, int *cols) {
Expand Down Expand Up @@ -121,25 +151,25 @@ void abFree(struct abuf *ab) {

/*** input ***/

void editorMoveCursor(char key) {
void editorMoveCursor(int key) {
switch (key) {
case 'a':
case ARROW_LEFT:
E.cx--;
break;
case 'd':
case ARROW_RIGHT:
E.cx++;
break;
case 'w':
case ARROW_UP:
E.cy--;
break;
case 's':
case ARROW_DOWN:
E.cy++;
break;
}
}

void editorProcessKeyPress() {
char c = editorReadKey();
int c = editorReadKey();

switch (c) {
case CTRL_KEY('q'):
Expand All @@ -148,10 +178,10 @@ void editorProcessKeyPress() {

exit(0);
break;
case 'w':
case 's':
case 'a':
case 'd':
case ARROW_UP:
case ARROW_DOWN:
case ARROW_LEFT:
case ARROW_RIGHT:
editorMoveCursor(c);
break;
}
Expand Down

0 comments on commit 4d3e9b2

Please sign in to comment.