From 403acbb836688f57e184b57b77f073a51b0dc4eb Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Fri, 7 Apr 2023 12:33:17 +0100 Subject: util.human.io: Add term_width() method to discover the terminal width This is not standard POSIX, but apparently very widely supported. For reference: https://www.austingroupbugs.net/view.php?id=1053 --- util/human/io.lua | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'util/human/io.lua') diff --git a/util/human/io.lua b/util/human/io.lua index bfbabafb..8a162059 100644 --- a/util/human/io.lua +++ b/util/human/io.lua @@ -108,6 +108,17 @@ if utf8.len and utf8.offset then end end +local function term_width(default) + local stty = io.popen("stty -a"); + if not stty then return default; end + local result = stty:read("*a"); + if result then + result = result:match("%f[%w]columns[ =]*(%d+)"); + end + stty:close(); + return tonumber(result or default); +end + local function ellipsis(s, width) if len(s) <= width then return s; end if width == 1 then return "…"; end @@ -194,6 +205,7 @@ return { printf = printf; padleft = padleft; padright = padright; + term_width = term_width; ellipsis = ellipsis; table = new_table; }; -- cgit v1.2.3