rpg-westreiche/tools/autowidth.lua
2026-10-25 16:09:59 +01:00

58 lines
1.4 KiB
Lua

-- Verteilt Tabellenspalten proportional zur Inhaltslänge (statt gleicher
-- Breiten aus der Markdown-Trennzeile). Für Tabellen mit langer
-- Beschreibungsspalte (typisch bei RPG-Tabellen) deutlich besser lesbar.
--
-- Die Breite einer Spalte = max. Zeichenlänge ihrer Zellen (Header + Rumpf),
-- normalisiert auf Anteile. Mindestbreite 12 %, um schmale Kennspalten
-- (z. B. "d6") nicht zu erdrücken.
local FLOOR = 0.08
local function strlen(s)
local ok, n = pcall(utf8.len, s)
if ok then return n end
return #s
end
local function celltext(blocks)
return pandoc.utils.stringify(blocks)
end
function Table(tbl)
local ncols = #tbl.colspecs
if ncols < 1 then return tbl end
local lens = {}
for i = 1, ncols do lens[i] = 1 end
local function measure(cells)
for i, cell in ipairs(cells) do
local l = strlen(celltext(cell.contents))
if l > lens[i] then lens[i] = l end
end
end
if tbl.head and tbl.head.rows then
for _, row in ipairs(tbl.head.rows) do measure(row.cells) end
end
for _, body in ipairs(tbl.bodies) do
for _, row in ipairs(body.body) do measure(row.cells) end
end
local total = 0
for i = 1, ncols do
lens[i] = math.sqrt(lens[i])
total = total + lens[i]
end
if total > 0 then
for i = 1, ncols do
local w = lens[i] / total
if w < FLOOR then w = FLOOR end
-- ColSpec ist positionsbasiert: [1]=align, [2]=width
tbl.colspecs[i][2] = w
end
end
return tbl
end