Debian Codegraph @

texmf-dist/tex/lualatex/odsfile/odsfile.lua

raw
1 -- Package odsfile. Author Michal Hoftich <[email protected]>
2 -- This package is subject of LPPL license, version 1.3c
3 -- module(...,package.seeall)
4
5 local M = {}
6 local zip = require "zip"
7 local xmlparser = require ("luaxml-mod-xml")
8 local handler = require("luaxml-mod-handler")
9
10 local namedRanges = {}
11
12 local function load(filename)
13 -- add support for -reader command line option
14 -- we must open the file and close it immediatelly
15 local f = io.open(filename, "r")
16 f:close()
17 local p = {
18 file = zip.open(filename),
19 content_file_name = "content.xml",
20 loadContent = function(self,filename)
21 local treehandler = handler.simpleTreeHandler()
22 -- treehandler.options.noReduce = {["table:table-cell"]=true, ["text:p"]=true}
23 local filename = filename or self.content_file_name
24 local xmlfile = self.file:open(filename)
25 local text = xmlfile:read("*a")
26 local xml = xmlparser.xmlParser(treehandler)
27 xml:parse(text)
28 return treehandler
29 end
30 }
31 return p
32 end
33
34 local function loadNameRanges(root, tblname)
35 local tblname = tblname or ""
36 local t = {}
37 local ranges = root.root["office:document-content"]["office:body"]["office:spreadsheet"]["table:named-expressions"]
38 if not ranges then return {} end
39 ranges = ranges["table:named-range"] or {}
40 if #ranges == 0 then
41 ranges = {ranges}
42 end
43 for _,r in ipairs(ranges) do
44 local a = r["_attr"] or {}
45 local range = a["table:cell-range-address"] or ""
46 local name = a["table:name"]
47 if name and range:match("^$?"..tblname) then
48 range = range:gsub("^[^%.]*",""):gsub("[%$%.]","")
49 print("named range", name, range)
50 t[name] = range
51 end
52 end
53 return t
54 end
55
56
57
58
59 local function getTable0(x,table_name)
60 local tables = x.root["office:document-content"]["office:body"]["office:spreadsheet"]["table:table"]
61 namedRanges = loadNameRanges(x, table_name)
62 if #tables > 1 then
63 if type(tables) == "table" and table_name ~= nil then
64 for k,v in pairs(tables) do
65 if(v["_attr"]["table:name"]==table_name) then
66 return v, k
67 end
68 end
69 elseif type(tables) == "table" and table_name == nil then
70 return tables[1], 1
71 else
72 return tables
73 end
74 else
75 return tables
76 end
77 end
78
79
80 local function getTable(x,table_name)
81 local t = getTable0(x,table_name)
82 local t2 = {}
83
84 for key, val in pairs(t) do
85 if key == "table:table-row" then
86 local rows = {}
87 if #val == 0 then val = {val} end
88
89 for i = 1, #val do
90 local r = val[i]
91 local rattr = r["_attr"] or {}
92 local rowRep = rattr["table:number-rows-repeated"] or 1
93
94 row = {}
95 row["_attr"] = r["_attr"]
96 local cc = r["table:table-cell"] or {}
97 if #cc == 0 then
98 cc = {cc}
99 end
100
101 local columns = {}
102 --for j = 1, #cc do
103 -- local c = cc[j]
104 for _, c in ipairs(cc) do
105 c["_attr"] = c["_attr"] or {}
106 local colRep = c["_attr"]["table:number-columns-repeated"] or 1
107 for k = 1, colRep, 1 do
108 table.insert(columns, c)
109 end
110 end
111 row["table:table-cell"] = columns
112
113 for j = 1, rowRep, 1 do
114 table.insert(rows, row)
115 end
116 end
117
118 t2[key] = rows
119 else
120 t2[key] = val
121 end
122 end
123
124 return t2
125 end
126
127 local function getColumnCount(tbl)
128 local tbl = tbl or {}
129 local columns = tbl["table:table-column"] or {}
130 local x = 0
131 for _, c in pairs(columns) do
132 local rep = c["table:number-columns-repeated"] or 1
133 x = x + rep
134 end
135 return x
136 end
137
138
139 local function table_slice (values,i1,i2)
140 -- Function from http://snippets.luacode.org/snippets/Table_Slice_116
141 local res = {}
142 local n = #values
143 -- default values for range
144 i1 = i1 or 1
145 i2 = i2 or n
146 if i2 < 0 then
147 i2 = n + i2 + 1
148 elseif i2 > n then
149 i2 = n
150 end
151 if i1 < 1 or i1 > n then
152 return {}
153 end
154 local k = 1
155 for i = i1,i2 do
156 res[k] = values[i]
157 k = k + 1
158 end
159 return res
160 end
161
162 local function tableValues(tbl,x1,y1,x2,y2)
163 local t= {}
164 local x1 = x1 or 1
165 local x2 = x2 or getColumnCount(tbl)
166 if type(tbl["table:table-row"])=="table" then
167 local rows = table_slice(tbl["table:table-row"],y1,y2)
168 for k,v in pairs(rows) do
169 -- In every sheet, there are two rows with no data at the bottom, we need to strip them
170 if(v["_attr"] and v["_attr"]["table:number-rows-repeated"] and tonumber(v["_attr"]["table:number-rows-repeated"])>10000) then break end
171 local j = {}
172 if #v["table:table-cell"] > 1 then
173 local r = table_slice(v["table:table-cell"],x1,x2)
174 for p,n in pairs(r) do
175 local attr = n["_attr"]
176 local cellValue = n["text:p"] or ""
177 table.insert(j,{value=cellValue,attr=attr})
178 end
179 else
180 local p = {value=v["table:table-cell"]["text:p"],attr=v["table:table-cell"]["_attr"]}
181 table.insert(j,p)
182 end
183 table.insert(t,j)
184 end
185 end
186 return t
187 end
188
189 local function join(tbl1, tbl2)
190 for _, x in ipairs(tbl2) do
191 tbl1[#tbl1+1] = x
192 end
193 return tbl1
194 end
195
196 local function getRange(range)
197 if range == nil then return {{nil,nil,nil,nil}} end
198 local range = namedRanges[range] or range
199 local r = range:lower()
200 local function getNumber(s)
201 if s == "" or s == nil then return nil end
202 local f,ex = 0,0
203 for i in string.gmatch(s:reverse(),"(.)") do
204 f = f + (i:byte()-96) * 26 ^ ex
205 ex = ex + 1
206 end
207 return f
208 end
209 local ranges = {}
210 for x1,y1,x2,y2 in r:gmatch("(%a*)(%d*):*(%a*)(%d*)") do
211 ranges[#ranges+1] = {getNumber(x1),tonumber(y1),getNumber(x2),tonumber(y2)}
212 --print(string.format("%s, %s, %s, %s",getNumber(x1),y1,getNumber(x2),y2))
213 end
214 return ranges
215 end
216
217
218 local function interp(s, tab)
219 return (s:gsub('(-%b{})',
220 function(w)
221 s = w:sub(3, -2)
222 s = tonumber(s) or s
223 return tab[s] or w
224 end)
225 )
226 end
227
228 local function escape(s)
229 if latexescape=="true" then
230 return string.gsub(s, "([%\\]?)([#%%%$&_%{%}%\\|])", function(a,b)
231 if a=="" then
232 if b == "\\" then
233 return "\\textbackslash{}"
234 elseif b == "|" then
235 return "\\textbar{}"
236 else
237 return "\\"..b
238 end
239 elseif a=="\\" and b=="\\" then
240 return "\\textbackslash\\textbackslash{}"
241 end
242 end)
243 else
244 return s
245 end
246 end
247
248 local function get_link(val)
249 local k = val["text:a"][1]
250 local href = val["text:a"]["_attr"]["xlink:href"]
251 return "\\odslink{"..href.."}{".. escape(k).."}"
252 end
253
254
255 local function get_cell(val, delim)
256 local val = val or ""
257 local typ = type(val)
258 if typ == "string" then
259 return escape(val)
260 elseif typ == "table" then
261 if val["text:a"] then
262 return get_link(val)
263 elseif val["text:span"] then
264 return get_cell(val["text:span"], delim)
265 elseif val["text:s"] then
266 -- return get_cell(val["text:s"], delim)
267 return escape(table.concat(val, " "))
268 else
269 local t = {}
270 for _,v in ipairs(val) do
271 local c = get_cell(v, delim)
272 table.insert(t, c)
273 end
274 return table.concat(t,delim)
275 end
276 end
277 end
278
279 -- Interface for adding new rows to the spreadsheet
280
281 local function newRow()
282 local p = {
283 pos = 0,
284 cells = {},
285 -- Generic function for inserting cell
286 addCell = function(self,val, attr,pos)
287 local attr = attr or {}
288 if pos then
289 table.insert(self.cells,pos,{["text:p"] = val, ["_attr"] = attr})
290 self.pos = pos
291 else
292 self.pos = self.pos + 1
293 table.insert(self.cells,self.pos,{["text:p"] = val, ["_attr"] = attr})
294 end
295 end,
296 addString = function(self,s,attr,pos)
297 local attr = attr or {}
298 attr["office:value-type"] = "string"
299 self:addCell(s,attr,pos)
300 end,
301 addFloat = function(self,i,attr,pos)
302 local attr = attr or {}
303 local s = tonumber(i) or 0
304 s = tostring(s)
305 attr["office:value-type"] = "float"
306 attr["office:value"] = s
307 self:addCell(s,attr,pos)
308 end,
309 findLastRow = function(self,sheet)
310 for i= #sheet["table:table-row"],1,-1 do
311 if sheet["table:table-row"][i]["_attr"]["table:number-rows-repeated"] then
312 return i
313 end
314 end
315 return #sheet["table:table-row"]+1
316 end,
317 insert = function(self, sheet, pos)
318 local t = {_attr = {}}
319 local pos = pos or self:findLastRow(sheet)
320 print("pos je: ",pos)
321 if sheet["table:table-column"]["_attr"] and sheet["table:table-column"]["_attr"]["table:number-columns-repeated"] then
322 table_columns = sheet["table:table-column"]["_attr"]["table:number-columns-repeated"]
323 else
324 table_columns = #sheet["table:table-column"]
325 end
326 for i=1, table_columns do
327 table.insert(t,self.cells[i] or {_attr={}})
328 end
329 t = {["table:table-cell"]=t, _attr = {}}
330 table.insert(sheet["table:table-row"],pos,t)
331 end
332 }
333 return p
334 end
335
336
337 -- function for updateing the archive. Depends on external zip utility
338 local function updateZip(zipfile, updatefile)
339 local command = string.format("zip %s %s",zipfile, updatefile)
340 print ("Updating an ods file.\n" ..command .."\n Return code: ", os.execute(command))
341 end
342
343 local function save(filename, content)
344 local f = io.open(filename, "w")
345 f:write(content)
346 f:close()
347 end
348
349 M.load= load
350 M.getTable= getTable
351 M.getTable0= getTable0
352 M.getColumnCount= getColumnCount
353 M.loadNameRanges= loadNameRanges
354 M.tableValues= tableValues
355 M.join = join
356 M.getRange= getRange
357 M.table_slice = table_slice
358 M.interp= interp
359 M.get_link =get_link
360 M.escape= escape
361 M.get_cell= get_cell
362 M.newRow= newRow
363 -- for updateing the archive. Depends on external zip utility
364 M.updateZip= updateZip
365 M.save = save
366
367 return M