From 4d3e9b2652cef1fa60e3f9fc1737ccca2eba9ee0 Mon Sep 17 00:00:00 2001 From: gurrium Date: Tue, 27 Dec 2022 19:52:52 +0900 Subject: [PATCH] next: https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html#prevent-moving-the-cursor-off-screen --- kilo.c | 54 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/kilo.c b/kilo.c index 9fa005d..b0b0f12 100644 --- a/kilo.c +++ b/kilo.c @@ -15,6 +15,13 @@ #define CTRL_KEY(k) ((k)&0x1f) +enum editorKey { + ARROW_LEFT = 1000, + ARROW_RIGHT, + ARROW_UP, + ARROW_DOWN +}; + /*** data ***/ struct editorConfig { @@ -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) { @@ -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'): @@ -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; }