1if not modules then modules = { } end modules ['util-fmt'] = {
2 version = 1.001,
3 comment = "companion to luat-lib.mkiv",
4 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5 copyright = "PRAGMA ADE / ConTeXt Development Team",
6 license = "see context related readme files"
7}
8
9utilities = utilities or { }
10utilities.formatters = utilities.formatters or { }
11local formatters = utilities.formatters
12
13local concat, format = table.concat, string.format
14local tostring, type = tostring, type
15local strip = string.strip
16
17local lpegmatch = lpeg.match
18local stripper = lpeg.patterns.stripzeros
19
20function formatters.stripzeros(str)
21 return lpegmatch(stripper,str)
22end
23
24function formatters.formatcolumns(result,between)
25 if result and #result > 0 then
26 between = between or " "
27 local widths, numbers = { }, { }
28 local first = result[1]
29 local n = #first
30 for i=1,n do
31 widths[i] = 0
32 end
33 for i=1,#result do
34 local r = result[i]
35 for j=1,n do
36 local rj = r[j]
37 local tj = type(rj)
38
39
40
41
42
43
44
45 if tj == "number" then
46 numbers[j] = true
47 rj = tostring(rj)
48 elseif tj ~= "string" then
49 rj = tostring(rj)
50 r[j] = rj
51 end
52 local w = #rj
53 if w > widths[j] then
54 widths[j] = w
55 end
56 end
57 end
58 for i=1,n do
59 local w = widths[i]
60 if numbers[i] then
61 if w > 80 then
62 widths[i] = "%s" .. between
63 else
64 widths[i] = "%0" .. w .. "i" .. between
65 end
66 else
67 if w > 80 then
68 widths[i] = "%s" .. between
69 elseif w > 0 then
70 widths[i] = "%-" .. w .. "s" .. between
71 else
72 widths[i] = "%s"
73 end
74 end
75 end
76 local template = strip(concat(widths))
77 for i=1,#result do
78 local str = format(template,unpack(result[i]))
79 result[i] = strip(str)
80 end
81 end
82 return result
83end
84 |