Debian Codegraph @

texmf-dist/doc/latex/songs/songidx/songidx.lua

raw symbols SCIP
1 -- Copyright (C) 2018 Kevin W. Hamlen
2 --
3 -- This program is free software; you can redistribute it and/or
4 -- modify it under the terms of the GNU General Public License
5 -- as published by the Free Software Foundation; either version 2
6 -- of the License, or (at your option) any later version.
7 --
8 -- This program is distributed in the hope that it will be useful,
9 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
10 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 -- GNU General Public License for more details.
12 --
13 -- You should have received a copy of the GNU General Public License
14 -- along with this program; if not, write to the Free Software
15 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
16 -- MA 02110-1301, USA.
17 --
18 -- The latest version of this program can be obtained from
19 -- http://songs.sourceforge.net.
20
21
22 VERSION = "3.1"
23 BIBLEDEFAULT = "bible.can"
24
25 -- fileopen(<filename>)
26 -- Open <filename> for reading, returning a filestate table on success or
27 -- nil on failure.
28 function fileopen(fnam)
29 local handle
30 if fnam ~= "-" then
31 local msg,errno
32 handle,msg,errno = io.open(fnam, "r")
33 if not handle then
34 io.stderr:write("songidx: Unable to open ",fnam," for reading.\n",
35 "Error ",errno,": ",msg,"\n")
36 return nil
37 end
38 else
39 handle = io.stdin
40 fnam = "stdin"
41 end
42 return { f=handle, filename=fnam, lineno=0 }
43 end
44
45 -- filereadln(<fstate>)
46 -- Read a line of input, returning the string or nil if at file-end.
47 function filereadln(fs)
48 fs["lineno"] = fs["lineno"] + 1
49 local s = fs["f"]:read()
50 if not s then return nil end
51 return s
52 end
53
54 -- closeout(<handle>)
55 -- Close an output file <handle>.
56 function closeout(handle)
57 if handle == io.stdout then handle:flush()
58 else handle:close() end
59 end
60
61 -- errorout(<handle>)
62 -- Respond to a write failure to <handle>.
63 function errorout(handle)
64 closeout(handle)
65 io.stderr:write("songidx: Error writing to output file. Aborting.\n")
66 return 2
67 end
68
69 -- fileclose(<fstate>)
70 -- Close file table <fstate>.
71 function fileclose(fs)
72 if (fs["f"] ~= io.stdin) then fs["f"]:close() end
73 fs["f"] = nil
74 fs["filename"] = nil
75 fs["lineno"] = 0
76 end
77
78 -- numprefix(<string>)
79 -- Find the longest prefix of <string> that represents a number (according to
80 -- the current locale) and contains no whitespace. Return the number and the
81 -- suffix of <string> not parsed. If there is no such prefix, return false
82 -- and the original <string>.
83 function numprefix(s)
84 local _, len = unicode.utf8.find(s,"^%S*")
85 for i=len, 1, -1 do
86 local n = tonumber(s:sub(1,i))
87 if n then return n, s:sub(i+1) end
88 end
89 return false, s
90 end
91
92 -- cleantitle(<song>)
93 -- Remove macros and braces from <song>'s title, and convert it to uppercase.
94 -- Macro-spaces ("\ ") are converted to regular spaces (" "). Cache the
95 -- result to avoid re-cleaning during sorting.
96 function cleantitle(s)
97 if not s["clean"] then
98 local t = s["title"]:gsub("\\[^%a%s]","")
99 :gsub("\\(%s)","%1")
100 :gsub("\\%a+%s*","")
101 :gsub("{%s*","")
102 :gsub("}","")
103 s["clean"] = unicode.utf8.upper(t)
104 end
105 return s["clean"]
106 end
107
108 -- songcmp(<song1>,<song2>)
109 -- Return true if <song1> is less than <song2>, and false otherwise. The
110 -- ordering is first by title, then by index. This function is suitable for
111 -- use with table.sort().
112 function songcmp(s1,s2)
113 local t1 = cleantitle(s1)
114 local t2 = cleantitle(s2)
115
116 while true do
117 -- Find the next word or number in each string.
118 t1, t2 = unicode.utf8.match(t1,"%w.*"), unicode.utf8.match(t2,"%w.*")
119
120 -- If there is no next word/number in both, sort by index. If there is
121 -- no next word/number in one but not the other, sort the shorter string
122 -- before the longer one.
123 if not t1 then
124 if not t2 then break end
125 return true
126 elseif not t2 then return false end
127
128 -- If one is a number, sort the number before the word. If both are
129 -- numbers (and are not equal), then sort in numerical order.
130 local n1, n2
131 n1, t1 = numprefix(t1)
132 n2, t2 = numprefix(t2)
133 if n1 then
134 if not n2 or n1 < n2 then return true end
135 if n1 > n2 then return false end
136 elseif n2 then return false
137 else
138 -- Otherwise, both are words. Lexicographically compare the words
139 -- according to the current locale's collation conventions. If the
140 -- locale considers them "equal" (i.e., w1<w2 is false but w1<=w2 is true)
141 -- then continue the loop to consider the next pair of words.
142 local w1, w2 = unicode.utf8.match(t1,"^[%a'`]*"),
143 unicode.utf8.match(t2,"^[%a'`]*")
144 local diff = w1 < w2
145 if diff or not (w1 <= w2) then return diff end
146 t1, t2 = t1:sub(#w1+1), t2:sub(#w2+1)
147 end
148 end
149
150 -- If all corresponding words/numbers are equal, then sort alternate-form
151 -- entries (e.g., lyrics) after normal entries (e.g., titles)
152 local alt1, alt2 = s1["title"]:sub(1,1), s2["title"]:sub(1,1)
153 if alt1 == "*" and alt2 ~= "*" then return false end
154 if alt1 ~= "*" and alt2 == "*" then return true end
155
156 -- If everything is the same, sort by the right-hand sides of the index
157 -- entries (e.g., the song or page numbers).
158 return s1["idx"] < s2["idx"]
159 end
160
161 -- setstartchars(<array>)
162 -- Try to find canonical "start characters" for each block of songs in a
163 -- sorted <array> of songs. Since Lua doesn't currently have any means of
164 -- imparting a locale's alphabet, we adopt the following strategy: Extract
165 -- the first unicode character from each title in the sorted list of titles
166 -- until reaching one that the locale's collation algorithm says is "bigger"
167 -- than the last. Find the "smallest" first character in that set using
168 -- NON-UNICODE lexicographic sort. This tends to be the most canonical one,
169 -- since unicode tends to put canonical (e.g., no-accent) glyphs at lower
170 -- code points than non-canonical (e.g., accented) ones. (Unfortunately, if
171 -- none of the titles in the block start with the desired canonical glyph,
172 -- there's no way to guess it; we just use the best one available.)
173 function setstartchars(songs)
174 local start = 1
175 local best
176
177 for i=1, #songs do
178 local c = unicode.utf8.match(cleantitle(songs[i]),"%w")
179 if c then
180 c = unicode.utf8.upper(c)
181 if not best then
182 songs[start]["newblk"], start, best = "\\#", i, c
183 elseif best < c then
184 songs[start]["newblk"], start, best = best, i, c
185 elseif #c < #best then best = c
186 elseif #c == #best then
187 for j=1,#c do
188 if c:byte(j) < best:byte(j) then best = c; break
189 elseif c:byte(j) > best:byte(j) then break end
190 end
191 end
192 elseif best then
193 songs[start]["newblk"], start, best = best, i, nil
194 end
195 end
196
197 if start <= #songs then
198 if best then
199 songs[start]["newblk"] = best
200 else
201 songs[start]["newblk"] = "\\#"
202 end
203 end
204 end
205
206 wt_prefix = { A=true, THE=true }
207 wt_and = { AND=true }
208 wt_by = { BY=true }
209 wt_unknown = { UNKNOWN=true }
210
211 -- rotate(<title>)
212 -- If the first word of <title> is any word in wt_prefix, then shift that word
213 -- to the end of the string, preceded by a comma and a space. So for example,
214 -- if wt_prefix contains "The", then rotate("The title") returns "Title, The".
215 -- Words in wt_prefix are matched case-insensitively, and the new first word
216 -- becomes capitalized. If <title> begins with the marker character '*',
217 -- that character is ignored and left unchanged.
218 function rotate(s)
219 local t = unicode.utf8.upper(s)
220 local n = 0
221 if s:sub(1,1) == "*" then n = 1 end
222 for pre in pairs(wt_prefix) do
223 if t:sub(1+n,n+#pre) == pre and
224 unicode.utf8.find(t, "^%s+%S", n+#pre+1) then
225 local len = unicode.utf8.len(pre)
226 local x, y, z = unicode.utf8.match(unicode.utf8.sub(s,n+len+1),"^%s+(%W*)(%w?)(.*)$")
227 return s:sub(1,n) .. x .. unicode.utf8.upper(y) .. z:gsub("\\%s","%0\1"):match("^(.-)%s*$"):gsub("\1","") .. ",~" .. unicode.utf8.sub(s,1+n,n+len)
228 end
229 end
230 return s
231 end
232
233 -- matchany(<string>,<init>,<wordtable>)
234 -- If a word in <wordtable> case-insensitively matches to <string> starting
235 -- at index <init>, and if the match concludes with whitespace, then return
236 -- the index of the whitespace; otherwise return <init>.
237 function matchany(s,init,wt)
238 local t = s:sub(init)
239 local u = unicode.utf8.upper(t)
240 for w,_ in pairs(wt) do
241 if u:sub(1,#w) == w and
242 (#w == #u or unicode.utf8.find(u, "^%s", #w+1)) then
243 return init + #(unicode.utf8.sub(t,1,unicode.utf8.len(w)))
244 end
245 end
246 return init
247 end
248
249 -- issuffix(<string>,<init>)
250 -- Return true if the abbreviation "Jr" or a roman numeral (followed by
251 -- nothing, space, period, comma, or semicolon) appears at position <init>
252 -- within <string>. Return false otherwise.
253 function issuffix(s,i)
254 return unicode.utf8.find(s, "^Jr$", i) or
255 unicode.utf8.find(s, "^Jr[%s,;%.]", i) or
256 unicode.utf8.find(s, "^[IVX]+$", i) or
257 unicode.utf8.find(s, "^[IVX]+[%s,;%.]", i)
258 end
259
260 -- grabauthor(<string>)
261 -- Return a string of the form "Sirname, Restofname" denoting the full name
262 -- of the first author found in <string>; or return nil if no author name
263 -- can be found. Also return an index to the suffix of <string> that was
264 -- not parsed, and just the "Sirname" part as a stand-alone string.
265 --
266 -- Precondition: Caller must first sanitize <string> as follows:
267 -- <string>:gsub("[\1\2\3]","")
268 -- :gsub("\\\\","\\\1"):gsub("\\{","\\\2"):gsub("\\}","\\\3")
269 --
270 -- Postcondition: Caller must then unsanitize the returned <string> with:
271 -- <string>:gsub("\1","\\"):gsub("\2","{"):gsub("\3","}")
272 --
273 -- This is to allow grabauthor() to safely use Lua's %b pattern to find
274 -- balanced brace pairs without getting confused by escaped braces.
275 --
276 -- Heuristics:
277 -- * Names are separated by punctuation (other than hyphens, periods,
278 -- apostrophes, or backslashes) or by the word "and" (or whatever words
279 -- are in wt_and).
280 -- Special case: If a comma is followed by the abbreviation "Jr" or by a
281 -- roman numeral, then the comma does NOT end the author's name.
282 -- * If a name contains the word "by" (or anything in wt_by), then
283 -- everything before it is not considered part of the name. (Let's hope
284 -- nobody is named "By".)
285 -- * The author's last name is always the last capitalized word in the
286 -- name unless the last capitalized word is "Jr." or a roman numeral.
287 -- In that case the author's last name is the penultimate captialized
288 -- word.
289 -- * If an author appears to have only a first name, or if the last name
290 -- found according to the above heuristics is an abbreviation (ending in
291 -- a period), look ahead in <string> until we find someone with a last
292 -- name and use that one. This allows us to identify the first author in
293 -- a string like "Joe, Billy E., and Bob Smith" to be "Joe Smith".
294 -- * If the resultant name contains the word "unknown" (or any word in
295 -- wt_unknown), it's probably not a real name. Recursively attempt
296 -- to parse the next author.
297 function grabauthor(authline,i)
298 i = unicode.utf8.find(authline, "[^%s,;]", i)
299 if not i then return nil end
300 i = unicode.utf8.find(authline, "%S", matchany(authline,i,wt_and))
301 if not i then return nil end
302 i = unicode.utf8.find(authline, "%S", matchany(authline,i,wt_by))
303 if not i then return nil end
304 local skip = (matchany(authline,i,wt_unknown) > i)
305
306 -- Set "first" to the index of the start of the first name, "last" to the
307 -- index of the start of the sirname, "suffix" to the index of any suffix
308 -- like "Jr." or "III" (or nil if there is none), and i to the index of the
309 -- first character beyond the end of this author's name.
310 local first,last,suffix = i,nil,nil
311 while i <= #authline do
312 while true do
313 local j = select(2,authline:find("^\\%A", i)) or
314 select(2,authline:find("^\\%a+%s*", i)) or
315 select(2,authline:find("^%b{}", i))
316 if not j then break end
317 i = j + 1
318 end
319 if i > #authline then break
320 elseif authline:sub(i,i) == "," then
321 local j = unicode.utf8.find(authline, "%S", i+1)
322 if j and issuffix(authline,j) then i = i + 1
323 else break end
324 elseif authline:sub(i,i) == ";" then break
325 elseif unicode.utf8.find(authline, "^%s", i) then
326 i = unicode.utf8.find(authline, "%S", i)
327 if not i then i = #authline + 1; break end
328 if matchany(authline, i, wt_and) > i then break end
329 skip = skip or (matchany(authline, i, wt_unknown) > i)
330 local j = matchany(authline, i, wt_by)
331 if j > i then
332 j = unicode.utf8.find(authline, "%S", j)
333 if not j then last = i; break end -- last name of "By"?
334 i,first,last,suffix = j,j,nil,nil
335 elseif issuffix(authline,i) then
336 suffix = i
337 elseif unicode.utf8.find(authline:sub(i):gsub("\\%A",""):gsub("\\%a+%s*",""),"^[%s{}'`\"]*%u") then
338 last,suffix = i,nil
339 end
340 else
341 i = select(2, unicode.utf8.find(authline, ".", i)) + 1
342 end
343 end
344
345 -- If an "unknown" word appeared, skip this entry and parse the next.
346 if skip then return grabauthor(authline,i) end
347
348 -- Find the sirname.
349 local sirname, fullname
350 if last then
351 sirname = unicode.utf8.gsub(authline:sub(last,(suffix or i)-1),
352 "([^%s,;\\])[%s,;]+$", "%1")
353 end
354 if not sirname or unicode.utf8.find(sirname, "%a%.$") then
355 -- Here's where it gets tough. We either have a single-word name, or the
356 -- last name ends in a "." which means maybe it's just a middle initial or
357 -- other abbreviation. We could be dealing with a line like, "Billy,
358 -- Joe E., and Bob Smith", in which case we have to go searching for the
359 -- real last name. To handle this case, we will try a recursive call.
360 local _,_,r = grabauthor(authline,i)
361 if r or not sirname then
362 fullname = unicode.utf8.gsub(authline:sub(first,i-1),
363 "([^%s,;\\])[%s,;]+$", "%1")
364 if r then return (r .. ", " .. fullname), i, r
365 else return fullname, i, nil end
366 end
367 end
368
369 -- Add the first name.
370 fullname = sirname .. ", " ..
371 unicode.utf8.gsub(authline:sub(first,(last or suffix or i)-1),
372 "([^%s,;\\])[%s,;]+$", "%1")
373
374 -- Add the suffix, if any.
375 if suffix then
376 fullname = fullname .. " " ..
377 unicode.utf8.gsub(authline:sub(suffix,i-1), "([^%s,;\\])[%s,;]+$", "%1")
378 end
379
380 return fullname, i, sirname
381 end
382
383 -- genindex(<fstate>,<outname>)
384 -- Reads a title (if <authorindex>=false) or author (if <authorindex>=true)
385 -- index data file from file table <fstate> and generates a new file named
386 -- <outfile> containing a LaTeX title/author index.
387 -- Return Value: 0 on success, 1 on warnings, or 2 on failure
388 function genindex(fs,outname,authorindex)
389 local songs = {}
390 local seen = {}
391 local wt = { wt_sep, wt_after, wt_prefix, wt_ignore }
392 local typ = authorindex and "author" or "title"
393
394 io.stderr:write("songidx: Parsing ",typ," index data file ",fs["filename"],"...\n")
395
396 while true do
397 local buf = filereadln(fs)
398 if not buf then break end
399 if buf:sub(1,1) == "%" then
400 local j = buf:match("^()%%sep ") or
401 buf:match("^%%()after ") or
402 buf:match("^%%p()refix ") or
403 buf:match("^%%ig()nore ")
404 if j then
405 if not seen[j] then
406 for w in pairs(wt[j]) do wt[j][w] = nil end
407 seen[j] = true
408 end
409 wt[j][unicode.utf8.upper(buf:sub(buf:find(" ")+1))] = true
410 end
411 else
412 local snum = filereadln(fs)
413 if not snum then
414 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": incomplete song entry (orphan ",typ,")\n")
415 return 2
416 end
417 local link = filereadln(fs)
418 if not link then
419 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": incomplete song entry (missing hyperlink)\n")
420 return 2
421 end
422 if authorindex then
423 local i,a = 1
424 buf = buf:gsub("[\1\2\3]",""):gsub("\\\\","\\\1")
425 :gsub("\\{","\\\2"):gsub("\\}","\\\3")
426 while true do
427 a,i = grabauthor(buf, i)
428 if not a then break end
429 a = a:gsub("\1","\\"):gsub("\2","{"):gsub("\3","}")
430 table.insert(songs, {title=a, num=snum, linkname=link, idx=#songs})
431 end
432 else
433 buf = rotate(unicode.utf8.gsub(unicode.utf8.gsub(buf,"([^%s\\])%s+$","%1"),"^(%*?)%s+","%1"))
434 table.insert(songs, {title=buf, num=snum, linkname=link, idx=#songs})
435 end
436 end
437 end
438 fileclose(fs)
439
440 -- Sort the song table.
441 table.sort(songs, songcmp)
442 -- Find the index blocks.
443 setstartchars(songs)
444
445 -- Write the sorted data out to the output file.
446 io.stderr:write("songidx: Generating ",typ," index TeX file ",outname,"...\n")
447 local f,msg,errno
448 if outname == "-" then
449 f, outname = io.stdout, "stdout"
450 else
451 f,msg,errno = io.open(outname, "w")
452 if not f then
453 io.stderr:write("songidx: Unable to open ",outname," for writing.\n",
454 "Error ",errno,": ",msg,"\n")
455 return 2
456 end
457 end
458 for i=1, #songs do
459 if i>1 and songs[i]["title"] == songs[i-1]["title"] then
460 if not f:write("\\\\\\songlink{",songs[i]["linkname"],"}{",songs[i]["num"],"}") then return errorout(f) end
461 else
462 if songs[i]["newblk"] then
463 if i>1 then
464 if not f:write("}\n\\end{idxblock}\n") then return errorout(f) end
465 end
466 if not f:write("\\begin{idxblock}{",songs[i]["newblk"]) then return errorout(f) end
467 end
468 if songs[i]["title"]:find("^%*") then
469 if not f:write("}\n\\idxaltentry{",songs[i]["title"]:sub(2)) then return errorout(f) end
470 else
471 if not f:write("}\n\\idxentry{",songs[i]["title"]) then return errorout(f) end
472 end
473 if not f:write("}{\\songlink{",songs[i]["linkname"],"}{",songs[i]["num"],"}") then return errorout(f) end
474 end
475 end
476 if #songs > 0 then
477 if not f:write("}\n\\end{idxblock}\n") then return errorout(f) end
478 end
479
480 return 0
481 end
482
483 bible = {}
484 chapX = 0
485
486 -- readbible(<filename>)
487 -- Read bible data file <filename> into the bible table. Return nil on error
488 -- or true on success.
489 function readbible(filename)
490 local fs = fileopen(filename)
491 if not fs then return nil end
492 bible = {}
493
494 while true do
495 local buf = filereadln(fs)
496 if not buf then break end
497 if buf:sub(1,1) ~= "#" and buf:find("%S") then
498 local t, vbuf = { name = buf:match("^[^|]*"),
499 aliases = "|" .. unicode.utf8.upper(buf) .. "|" }
500 repeat
501 vbuf = filereadln(fs)
502 if not vbuf then
503 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": incomplete bible book entry (book title with no verses)\n")
504 fileclose(fs)
505 return nil
506 end
507 until vbuf:sub(1,1) ~= "#" and buf:find("%S")
508 if vbuf:find("[^%d%s]") then
509 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": verse count includes a non-digit\n")
510 fileclose(fs)
511 return nil
512 end
513 for n in vbuf:gmatch("%d+") do
514 local i = tonumber(n)
515 if not i then
516 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": invalid number ",n,"\n")
517 fileclose(fs)
518 return nil
519 end
520 i = math.floor(i)
521 if chapX < i+1 then chapX = i+1 end
522 table.insert(t, i)
523 end
524 table.insert(bible, t)
525 end
526 end
527
528 fileclose(fs)
529 return true
530 end
531
532 -- parseref(<string>,<init>,<book>,<chapter>)
533 -- Interpret the characters starting at index <init> of <string> as a
534 -- scripture reference, and return four values: (1) the index of the first
535 -- character after <init> not parsed, (2) the book number parsed, (3) the
536 -- chapter number parsed (or 1 if the book has only verses), and (4) the
537 -- verse number parsed. Arguments <book> and <chapter> are the PREVIOUS book
538 -- number and chapter parsed, or -1 if none. If book or chapter information
539 -- is missing from <string>, they will be drawn from <book> and <chapter>.
540 -- That way, successive calls can correctly parse a run-on string like
541 -- "Philippians 3:1,5; 4:3", infering that "5" refers to "Philippians 3" and
542 -- "4:3" refers to "Philippians". If the parser encounters an error in
543 -- processing the book name (e.g., a book name was specified but not
544 -- recognized), then #bible+1 is returned for the book. If no chapter or no
545 -- verse is provided (e.g., the reference is just "Philippians" or
546 -- "Philippians 3") then the chapter and/or verse are returned as -1.
547 function parseref(s,i,book,ch)
548 local v = -1
549 i = unicode.utf8.find(s,"%S",i)
550 if not i then return nil end
551 local j = unicode.utf8.find(s,"[%d:]*%s*[,;%-]",i) or
552 unicode.utf8.find(s,"[%d:]*%s*$",i)
553 local bookname = "|" .. unicode.utf8.upper(unicode.utf8.match(s:sub(i,j-1), "(.-)%s*$")) .. "|"
554 i = j
555 if bookname ~= "||" then
556 book, ch = #bible+1, -1
557 for b,t in pairs(bible) do
558 if t["aliases"]:find(bookname, 1, true) then book = b; break end
559 end
560 end
561 j = unicode.utf8.find(s,"%D",i) or (#s+1)
562 if s:sub(j,j) == ":" then
563 ch, i = (tonumber(s:sub(i,j-1)) or -1), j+1
564 j = unicode.utf8.find(s,"%D",i) or (#s+1)
565 end
566 if ch<=0 and book>0 and #bible[book] == 1 then
567 -- Special case: This book has only one chapter.
568 ch = 1
569 end
570 if ch <= 0 then
571 ch = tonumber(s:sub(i,j-1)) or -1
572 else
573 v = tonumber(s:sub(i,j-1)) or -1
574 end
575 i = unicode.utf8.find(s,"%S",j)
576 if not i then i = #s+1
577 elseif not s:find("^[,;%-]",i) then return nil end
578 return i, book, ch, v
579 end
580
581 -- vlt(<chapter1>,<verse1>,<chapter2>,<verse2>)
582 -- Return true if <chapter1>:<verse1> precedes <chapter2>:<verse2> and false
583 -- otherwise.
584 function vlt(ch1,v1,ch2,v2)
585 return ch1 < ch2 or (ch1 == ch2 and v1 < v2)
586 end
587
588 -- vinc(<book>,<chapter>,<verse>)
589 -- Return the chapter,verse pair of the verse immediately following
590 -- <chapter>:<verse> in <book>. If <chapter>:<verse> is the last verse in
591 -- <book>, the returned chapter will not exist in <book>.
592 function vinc(book,ch,v)
593 if v < bible[book][ch] then return ch, v+1 end
594 return ch+1, 1
595 end
596
597 -- vdec(<book>,<chapter>,<verse>)
598 -- Return the chapter,verse pair of the verse immediately preceding
599 -- <chapter>:<verse> in <book>. If <chapter> and <verse> are both 1,
600 -- then 0,nil will be returned.
601 function vdec(book,ch,v)
602 if v > 1 then return ch, v-1 end
603 return ch-1, bible[book][ch-1]
604 end
605
606 -- unpack_cv(<cv>)
607 -- Decompose a chapter-verse key (computed as cv*chapX+v) into the original
608 -- chapter and verse numbers.
609 function unpack_cv(cv)
610 local v = cv % chapX
611 return (cv-v)/chapX, v
612 end
613
614 -- eqdom(<table1>,<table2>)
615 -- Return true if two tables have identical domains; false otherwise.
616 function eqdom(t1,t2)
617 for k,_ in pairs(t1) do if not t2[k] then return false end end
618 for k,_ in pairs(t2) do if not t1[k] then return false end end
619 return true
620 end
621
622 -- insertref(<is_add>,<changeset>,<chapter>,<verse>,<song>,<link>,<key>)
623 -- Insert song <song>,<link>,<key> into the set of "adds" (if <is_add>=true)
624 -- or "drops" (if <is_add>=false) for verse <chapter>:<verse> in <changeset>.
625 -- A <changeset> is a table that maps cv's to {adds=<refset>, drops=<refset>}
626 -- tables, where cv's are chapter-verse pairs encoded as chapter*chapX+verse.
627 -- Each such entry denotes a verse where the set of songs that reference it
628 -- changes. The "adds" field lists the songs that refer to this verse but
629 -- not the previous one. The "drops" field lists the songs that refer to
630 -- this verse but not the next. This formulation allows us to efficiently
631 -- represent range-references (e.g., "Psalms 1:1-8") without creating a
632 -- separate table entry for each verse in the range.
633 -- Create a new entry for <chapter>:<verse> in <changeset> if it doesn't
634 -- already exist. Return the new <changeset>.
635 function insertref(is_add,set,ch,v,n,l,k)
636 if not set then set = {} end
637 local cv = ch*chapX+v
638 if not set[cv] then set[cv] = { adds={}, drops={} } end
639 set[cv][is_add and "adds" or "drops"][k] = { num=n, link=l }
640 return set
641 end
642
643 -- print_vrange(<file>,<book>,<ch1>,<v1>,<ch2>,<v2>,<lastchapter>)
644 -- Output LaTeX material to file <file> for verse range <ch1>:<v1>--<ch2>:<v2>
645 -- of book number <book>. Depending on <lastchapter>, the outputted material
646 -- might be the start of a new index entry or the continuation of a previous
647 -- entry. If <lastchapter> is positive, continue the previous entry and
648 -- print the chapter of <ch1>:<v1> only if it differs from <lastchapter>. If
649 -- <lastchapter> is negative, continue the previous entry and always print
650 -- the chapter number of <ch1>:<v1>.
651 function print_vrange(f,b,ch1,v1,ch2,v2,lch)
652 local r = f:write(lch == 0 and "\\idxentry{" or ",")
653
654 if v1 <= 0 then
655 if lch ~= 0 then r = r and f:write("\\thinspace ") end
656 r = r and f:write(ch1)
657 elseif 0 <= b and b < #bible and #bible[b] == 1 then
658 -- This book has only one chapter.
659 if lch ~= 0 then r = r and f:write("\\thinspace ") end
660 r = r and f:write(v1)
661 elseif lch <= 0 or lch ~= ch1 or ch1 ~= ch2 then
662 if lch ~= 0 then r = r and f:write(" ") end
663 r = r and f:write(ch1,":",v1)
664 else
665 if lch ~= 0 then r = r and f:write("\\thinspace ") end
666 r = r and f:write(v1)
667 end
668
669 if vlt(ch1,v1,ch2,v2) then
670 if v2 <= 0 then
671 r = r and f:write("--",ch2)
672 elseif ch1 ~= ch2 then
673 r = r and f:write("--",ch2,":",v2)
674 else
675 r = r and f:write("--",v2)
676 end
677 end
678
679 return r
680 end
681
682 -- print_reflist(<file>,<refset>)
683 -- Output the list of song references given by <refset> in sorted order
684 -- to file <file>.
685 function print_reflist(f,t)
686 local r = true
687 local s = {}
688 for k,_ in pairs(t) do table.insert(s,k) end
689 table.sort(s)
690
691 local first = true
692 for _,k in ipairs(s) do
693 if first then first = false else r = r and f:write("\\\\") end
694 r = r and f:write("\\songlink{",t[k]["link"],"}{",t[k]["num"],"}")
695 end
696 return r
697 end
698
699 function debug_print_reflist(r)
700 local first = true
701 io.stderr:write("{")
702 for k,_ in pairs(r) do
703 if first then first=false else io.stderr:write(",") end
704 io.stderr:write(k)
705 end
706 io.stderr:write("}")
707 end
708
709 function debug_print_changeset(x)
710 if not x then io.stderr:write("nil") else
711 for cv,r in pairs(x) do
712 local ch,v = unpack_cv(cv)
713 io.stderr:write("{",ch,":",v," --> adds=")
714 debug_print_reflist(r["adds"])
715 io.stderr:write(", drops=")
716 debug_print_reflist(r["drops"])
717 io.stderr:write("}")
718 end
719 end
720 end
721
722 -- genscriptureindex(<fstate>,<outname>,<biblename>)
723 -- Generate a LaTeX file named <outname> containing material suitable to
724 -- typeset the scripture index data found in input file <fstate>. Input
725 -- bible data from an ascii file named <biblename>. Return 0 on success,
726 -- 1 if there were warnings, and 2 if there was a fatal error.
727 function genscriptureindex(fs,outname,biblename)
728 local hadwarnings = 0
729 local idx = {}
730
731 io.stderr:write("songidx: Parsing scripture index data file ",fs["filename"],"...\n")
732
733 -- Read the bible data file into the bible array.
734 if not readbible(biblename) then return 2 end
735
736 -- Walk through the input file and construct a <changeset> for each book
737 -- of the bible. Each changeset represents the set of verses in that book
738 -- referred to by songs in the song book.
739 local key = 0
740 while true do
741 local ref = filereadln(fs)
742 if not ref then break end
743 local n = filereadln(fs)
744 if not n then
745 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": incomplete song entry (orphan reference line)\n")
746 fileclose(fs)
747 return 2
748 end
749 local l = filereadln(fs)
750 if not l then
751 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": incomplete song entry (missing hyperlink)\n")
752 fileclose(fs)
753 return 2
754 end
755 key = key + 1
756
757 local i = 1
758 local book, ch1, v1, ch2, v2 = -1, -1, -1, -1, -1
759 while i <= #ref do
760 i,book,ch1,v1 = parseref(ref,i,book,ch1)
761 ch2,v2 = ch1,v1
762 if not i then
763 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Malformed scripture reference for song ",n,". Ignoring it.\n")
764 hadwarnings = 1
765 break
766 end
767 if book < 1 then
768 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," doesn't include a book name. Ignoring it.\n")
769 hadwarnings = 1
770 break
771 end
772 if book > #bible then
773 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," references unknown book. Ignoring it.\n")
774 hadwarnings = 1
775 break
776 end
777 if ch1 < 1 then ch1 = 1 end
778 if ch1 > #bible[book] then
779 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," refers to ",bible[book]["name"]," ",ch1,", which doesn't exist. Ignoring it.\n")
780 hadwarnings = 1
781 break
782 end
783 if v1 < 1 then v1 = 1 end
784 if v1 > bible[book][ch1] then
785 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," refers to ",bible[book]["name"]," ",ch1,":",v1,", which doesn't exist. Ignoring it.\n")
786 hadwarnings = 1
787 break
788 end
789
790 if ref:sub(i,i) == "-" then
791 -- If the reference ends in a "-", it starts an explicit range.
792 -- Parse the next reference to find the range's end.
793 i = unicode.utf8.find(ref, "[^%s%-]", i)
794 if not i then
795 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," has range with no limit. Ignoring it.\n")
796 hadwarnings = 1
797 break
798 end
799 local book2
800 i,book2,ch2,v2 = parseref(ref,i,book,ch1)
801 if not i then
802 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Malformed scripture reference for song ",n,". Ignoring it.\n")
803 hadwarnings = 1
804 break
805 end
806 if book2 ~= book then
807 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," appears to span books! Ignoring it.\n")
808 hadwarnings = 1
809 break
810 end
811 end
812 if ch2 < 1 then ch2 = #bible[book] end
813 if ch2 > #bible[book] then
814 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," refers implicitly to ",bible[book]["name"]," ",ch2,", which doesn't exist. Ignoring it.\n")
815 hadwarnings = 1
816 break
817 end
818 if v2 < 1 then v2 = bible[book][ch2]
819 elseif v2 > bible[book][ch2] then
820 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," refers implicitly to chapter ",ch2," of ",bible[book]["name"],", which doesn't exist. Ignoring it.\n")
821 hadwarnings = 1
822 break
823 end
824 if vlt(ch2,v2,ch1,v1) then
825 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": WARNING: Scripture reference for song ",n," contains backwards range ",bible[book]["name"]," ",ch1,":",v1,"-",ch2,":",v2,". Ignoring it.\n")
826 hadwarnings = 1
827 break
828 end
829 if i < #ref then i = i + 1 end
830
831 idx[book] = insertref(true, idx[book], ch1, v1, n, l, key)
832 idx[book] = insertref(false, idx[book], ch2, v2, n, l, key)
833 end
834 end
835 fileclose(fs)
836
837 -- Now create the index .sbx file.
838 io.stderr:write("songidx: Generating scripture index TeX file ",outname,"...\n")
839 local f,msg,errno
840 if outname == "-" then
841 f, outname = io.stdout, "stdout"
842 else
843 f,msg,errno = io.open(outname, "w")
844 if not f then
845 io.stderr:write("songidx: Unable to open ",outname," for writing.\n",
846 "Error ",errno,": ",msg,"\n")
847 return 2
848 end
849 end
850
851 -- For each book of the bible the has songs that reference it, go through its
852 -- <changeset> and generate a sequence of index entries. Wherever possible,
853 -- compact adjacent entries that have identical <refset>'s so that we never
854 -- have two consecutive index entries with identical right-hand sides.
855 for b=1,#bible do
856 local x = idx[b]
857 if x then
858 -- io.stderr:write("idx[",b,"] = ")
859 -- debug_print_changeset(x)
860 local s, t = {}, {}
861 for cv,_ in pairs(x) do table.insert(s,cv) end
862 table.sort(s)
863 local lch = 0 -- 0=none, -1=force printing of chapter
864 local cv1 = s[1]
865 local ch1,v1 = unpack_cv(cv1)
866 if not f:write("\\begin{idxblock}{",bible[b]["name"],"}\n") then return errorout(f) end
867 for i,cv in ipairs(s) do
868 local this = x[cv]
869 local ch,v = unpack_cv(cv)
870 local ncv,nxt,nch,nv = s[i+1]
871 if ncv then
872 nxt,nch,nv = x[ncv], unpack_cv(ncv)
873 end
874 for k,r in pairs(this["adds"]) do t[k] = r end
875 local skip = false
876 if ncv and eqdom(this["drops"], nxt["adds"]) then
877 -- Set of drops here equals set of adds next time. There's at least
878 -- a chance that we can combine this item and the next one into a
879 -- single index entry.
880 local ch2, v2 = vinc(b,ch,v)
881 if not vlt(ch2,v2, nch,nv) then
882 -- If the next item is adjacent to this one, do nothing. Just let
883 -- the range in progress be extended. We'll output a single entry
884 -- for all of these adjacent verses when we reach the end.
885 skip = true
886 elseif eqdom(t, this["drops"]) then
887 -- Otherwise, if the next item is not adjacent but all refs are
888 -- dropped here, then print a partial entry to be continued with a
889 -- comma next time.
890 if not print_vrange(f,b,ch1,v1,ch,v,lch) then return errorout(f) end
891 lch = (ch1 == ch) and ch or -1
892 ch1, v1 = nch, nv
893 skip = true
894 end
895 end
896 if not skip then
897 if next(this["drops"]) then
898 -- Some songs get dropped here, and either the next item is not
899 -- adjacent to this one, or it's adjacent and the set of adds is not
900 -- the same. In either case, that means the set of refs changes at
901 -- this point, so we need to output a full entry (or finish the one
902 -- in progress).
903 if not (print_vrange(f,b,ch1,v1,ch,v,lch) and
904 f:write("}{") and
905 print_reflist(f,t) and
906 f:write("}\n")) then return errorout(f) end
907 for k,_ in pairs(this["drops"]) do t[k] = nil end
908 lch = 0
909 if not next(t) and ncv then
910 ch1, v1 = nch, nv
911 else
912 ch1, v1 = vinc(b,ch,v)
913 end
914 end
915 if next(t) and ncv and next(nxt["adds"]) and vlt(ch1,v1,nch,nv) then
916 -- There are verses between this item and the next which have refs,
917 -- but the refs change at the beginning of the next item. Make an
918 -- entry for the intermediate block of verses.
919 local ch2, v2 = vdec(b,nch,nv)
920 if not (print_vrange(f,b,ch1,v1,ch2,v2,lch) and
921 f:write("}{") and
922 print_reflist(f,t) and
923 f:write("}\n")) then return errorout(f) end
924 lch, ch1, v1 = 0, nch, nv
925 end
926 end
927 end
928 if not f:write("\\end{idxblock}\n") then return errorout(f) end
929 end
930 end
931
932 closeout(f)
933 return hadwarnings
934 end
935
936 -- Main program entry point
937 function main()
938 local fs, biblename, inname, outname, locale
939
940 local i = 1
941 while arg[i] do
942 if arg[i] == "-v" or arg[i] == "--version" then
943 io.write("songidx ", VERSION, "\n",
944 "Copyright (C) 2018 Kevin W. Hamlen\n",
945 "License GPLv2: GNU GPL version 2 or later",
946 " <http://gnu.org/licenses/gpl.html>\n",
947 "This is free software: you are free to change and redistribute it.\n",
948 "There is NO WARRANTY, to the extent permitted by law.\n")
949 return 0
950 elseif arg[i] == "-h" or arg[i] == "--help" then
951 io.write("Syntax: ",arg[-1]," ",arg[0]," [options] input.sxd [output.sbx]\n",
952 "Available options:\n",
953 " -b FILE Set the bible format when generating a scripture index\n",
954 " --bible FILE (default: ", BIBLEDEFAULT, ")\n",
955 "\n",
956 " -l LOCALE Override the default system locale (affecting how non-\n",
957 " --locale LOCALE English characters are sorted). See your system help\n",
958 " for valid LOCALEs.\n",
959 "\n",
960 " -h Display this help file and stop.\n",
961 " --help\n",
962 "\n",
963 " -v Print version information and stop.\n",
964 " --version\n",
965 "\n",
966 "If omitted, [output.sbx] defaults to the input filename but with the file\n",
967 "extension renamed to '.sbx'. To read or write to stdin or stdout, use '-'\n",
968 "in place of input.sxd or output.sbx.\n",
969 "\n",
970 "See http://songs.sourceforge.net for support.\n")
971 return 0
972 elseif arg[i] == "-b" or arg[i] == "--bible" then
973 if biblename then
974 io.stderr:write("songidx: multiple bible files specified\n")
975 return 2
976 end
977 i = i + 1
978 if arg[i] then
979 biblename = arg[i]
980 else
981 io.stderr:write("songidx: ",arg[i-1]," option requires an argument\n")
982 return 2
983 end
984 elseif arg[i] == "-l" or arg[i] == "--locale" then
985 if locale then
986 io.stderr:write("songidx: multiple locales specified\n")
987 return 2
988 end
989 i = i + 1
990 if arg[i] then
991 locale = arg[i]
992 else
993 io.stderr:write("songidx: ",arg[i-1]," requires an argument\n")
994 return 2
995 end
996 elseif arg[i] == "-o" or arg[i] == "--output" then
997 if outname then
998 io.stderr:write("songidx: multiple output files specified\n")
999 return 2
1000 end
1001 i = i + 1
1002 if arg[i] then
1003 outname = arg[i]
1004 else
1005 io.stderr:write("songidx: ",arg[i-1]," option requires an argument\n")
1006 return 2
1007 end
1008 elseif arg[i]:sub(1,1) == "-" and arg[i] ~= "-" then
1009 io.stderr:write("songidx: unknown option ",arg[i],"\n")
1010 return 2
1011 elseif not inname then inname = arg[i]
1012 elseif not outname then outname = arg[i]
1013 else
1014 io.stderr:write("songidx: too many command line arguments\n")
1015 return 2
1016 end
1017 i = i + 1
1018 end
1019
1020 if not locale then
1021 os.setlocale("")
1022 elseif not os.setlocale(locale) then
1023 io.stderr:write("songidx: invalid locale: ",locale,"\n")
1024 return 2
1025 end
1026
1027 if not inname then
1028 io.stderr:write("songidx: no input file specified\n")
1029 return 2
1030 end
1031 if not outname then
1032 if inname == "-" then
1033 outname = "-"
1034 else
1035 local n
1036 outname,n = inname:gsub("%.[^%./\\]*$", ".sbx")
1037 if n == 0 then outname = inname .. ".sbx" end
1038 end
1039 end
1040 if not biblename then biblename = BIBLEDEFAULT end
1041
1042 fs = fileopen(inname)
1043 if not fs then return 2 end
1044
1045 local retval = 2
1046 local buf = filereadln(fs)
1047 if not buf then
1048 io.stderr:write("songidx:",fs["filename"],": file is empty\n")
1049 fileclose(fs)
1050 elseif buf == "TITLE INDEX DATA FILE" then
1051 retval = genindex(fs,outname,false)
1052 elseif buf == "SCRIPTURE INDEX DATA FILE" then
1053 retval = genscriptureindex(fs,outname,biblename)
1054 elseif buf == "AUTHOR INDEX DATA FILE" then
1055 retval = genindex(fs,outname,true)
1056 else
1057 io.stderr:write("songidx:",fs["filename"],":",fs["lineno"],": file has unrecognized format\n")
1058 fileclose(fs)
1059 end
1060
1061 if retval == 0 then
1062 io.stderr:write("songidx: Done!\n")
1063 elseif retval == 1 then
1064 io.stderr:write("songidx: COMPLETED WITH ERRORS. SEE ABOVE.\n")
1065 else
1066 io.stderr:write("songidx: FAILED. SEE ERROR MESSAGES ABOVE.\n")
1067 end
1068
1069 return retval
1070 end
1071
1072 os.exit(main())
1073