From cdd1fefb732833d2f4808e8eb014d394f8a18d07 Mon Sep 17 00:00:00 2001 From: gurrium Date: Wed, 21 Dec 2022 23:07:10 +0900 Subject: [PATCH] https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html#the-last-line --- kilo.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/kilo.c b/kilo.c index 776344d..a67b458 100644 --- a/kilo.c +++ b/kilo.c @@ -61,12 +61,31 @@ char editorReadKey() { return c; } +int getCursorPosition(int *rows, int *cols) { + char buf[32]; + unsigned int i = 0; + + if (write(STDIN_FILENO, "\x1b[6n", 4) != 4) return -1; + + while (i < sizeof(buf) - 1) { + if (read(STDIN_FILENO, &buf[i], 1) != 1) break; + if (buf[i] == 'R') break; + i++; + } + buf[i] = '\0'; + + if (buf[0] != '\x1b' || buf[1] != '[') return -1; + if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; + + return 0; +} + int getWindowSize(int *rows, int *cols) { struct winsize ws; - if (1 || ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1; - editorReadKey(); + return getCursorPosition(rows, cols); } else { *cols = ws.ws_col; *rows = ws.ws_row;