diff --git a/src/term.c b/src/term.c index 1413d56..fa4d1df 100644 --- a/src/term.c +++ b/src/term.c @@ -20,6 +20,8 @@ # include # include # include +# include +# include #endif #ifdef _WIN32 @@ -736,6 +738,50 @@ static int lst_keypressed(lua_State *L) { #endif } +/*------------------------------------------------------------------------- + * Retrieve terminal size + *-------------------------------------------------------------------------*/ + + +/*** +Get the size of the terminal window. +@function termsize +@treturn[1] int the number of columns +@treturn[1] int the number of rows +@treturn[2] nil +@treturn[2] string error message +*/ +static int lst_termsize(lua_State *L) { + int columns, rows; + +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbi; + if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { + lua_pushnil(L); + lua_pushstring(L, "Failed to get terminal size."); + return 2; + } + columns = csbi.srWindow.Right - csbi.srWindow.Left + 1; + rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; + +#else + struct winsize ws; + if (ioctl(1, TIOCGWINSZ, &ws) == -1) { + lua_pushnil(L); + lua_pushstring(L, "Failed to get terminal size."); + return 2; + } + columns = ws.ws_col; + rows = ws.ws_row; + +#endif + lua_pushinteger(L, columns); + lua_pushinteger(L, rows); + return 2; +} + + + /*------------------------------------------------------------------------- * Initializes module *-------------------------------------------------------------------------*/ @@ -750,6 +796,7 @@ static luaL_Reg func[] = { { "setnonblock", lst_setnonblock }, { "readkey", lst_readkey }, { "keypressed", lst_keypressed }, + { "termsize", lst_termsize }, { NULL, NULL } };