Skip to content

Commit

Permalink
add function to retrieve terminal size (cols/rows)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tieske committed Apr 29, 2024
1 parent db39d22 commit ec7c6ce
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/term.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
# include <string.h>
# include <errno.h>
# include <fcntl.h>
# include <sys/ioctl.h>
# include <unistd.h>
#endif

#ifdef _WIN32
Expand Down Expand Up @@ -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
*-------------------------------------------------------------------------*/
Expand All @@ -750,6 +796,7 @@ static luaL_Reg func[] = {
{ "setnonblock", lst_setnonblock },
{ "readkey", lst_readkey },
{ "keypressed", lst_keypressed },
{ "termsize", lst_termsize },
{ NULL, NULL }
};

Expand Down

0 comments on commit ec7c6ce

Please sign in to comment.