From 974fde4a702eae5ea9fa8ca483ae7fa0b5be0c8a Mon Sep 17 00:00:00 2001 From: jmug Date: Sat, 10 Oct 2026 16:42:34 -0700 Subject: [PATCH] feat: Fallback to ioctl get window size with cursor position. --- kilo.c | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/kilo.c b/kilo.c index 911b437..44cb46e 100644 --- a/kilo.c +++ b/kilo.c @@ -71,11 +71,41 @@ char editorReadKey() { return c; } +int getCursorPosition(int *rows, int *cols) { + if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) { + return -1; + } + + char buf[32]; + unsigned int i = 0; + // Leave space for null terminator. + 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 (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { - return -1; + // Fallback if ioctl can't query size: + // Move cursor to the bottom right, then query its position. + if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) { + return -1; + } + return getCursorPosition(rows, cols); } *rows = ws.ws_row;