From bc7277bd012a28750ddeac83624567f23743d05d Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Thu, 6 Apr 2023 14:51:52 +0100 Subject: util.human.io: Support for dynamic "proportional" columns Instead of a percentage, this allows you to specify e.g. `width="[N]p"`, where a width="2p" will be twice the width of a width="1p" column. Compatibility with the old %-based widths is preserved, and percentages adding up to more than 100 are handled more gracefully. --- util/human/io.lua | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'util') diff --git a/util/human/io.lua b/util/human/io.lua index c050b335..e5b22d50 100644 --- a/util/human/io.lua +++ b/util/human/io.lua @@ -124,7 +124,7 @@ local function new_table(col_specs, max_width) -- Calculate width of fixed-size columns for i = 1, #col_specs do local width = col_specs[i].width or "0"; - if not(type(width) == "string" and width:sub(-1) == "%") then + if not (type(width) == "string" and width:match("[p%%]$")) then local title = col_specs[i].title; width = math.max(tonumber(width), title and (#title+1) or 0); widths[i] = width; @@ -134,11 +134,21 @@ local function new_table(col_specs, max_width) end end end - -- Calculate width of %-based columns + + -- Calculate width of proportional columns + local total_proportional_width = 0; + for i = 1, #col_specs do + if not widths[i] then + local width_spec = col_specs[i].width:match("(%d+)[p%%]"); + total_proportional_width = total_proportional_width + tonumber(width_spec); + end + end + for i = 1, #col_specs do if not widths[i] then - local pc_width = tonumber((col_specs[i].width:gsub("%%$", ""))); - widths[i] = math.floor(free_width*(pc_width/100)); + local width_spec = col_specs[i].width:match("(%d+)[p%%]"); + local rel_width = tonumber(width_spec); + widths[i] = math.floor(free_width*(rel_width/total_proportional_width)); end end -- cgit v1.2.3