Debian Codegraph @

texk/texlive/linked_scripts/light-latex-make/llmk.lua

raw symbols SCIP
1 #!/usr/bin/env texlua
2
3 --
4 -- This is file `llmk.lua'.
5 --
6 -- Copyright 2018-2023 Takuto Asakura (wtsnjp)
7 -- GitHub: https://github.com/wtsnjp
8 -- Twitter: @wtsnjp
9 --
10 -- This sofware is released under the MIT License.
11 --
12
13 local llmk = {} -- the module table
14
15 ----------------------------------------
16
17 do -- The "core" submodule
18 local M = {}
19
20 -- option flags (default)
21 M.debug = {
22 config = false,
23 parser = false,
24 run = false,
25 fdb = false,
26 programs = false,
27 }
28 M.verbosity_level = 1
29 M.silent = false
30 M.dry_run = false
31
32 llmk.core = M
33 end
34
35 ----------------------------------------
36
37 do -- The "const" submodule
38 local M = {}
39
40 -- program information
41 M.prog_name = 'llmk'
42 M.version = '1.2.0'
43 M.copyright = 'Copyright 2018-2023'
44 M.author = 'Takuto Asakura (wtsnjp)'
45 M.llmk_toml = 'llmk.toml'
46
47 -- exit codes
48 M.exit_ok = 0
49 M.exit_error = 1
50 M.exit_failure = 2
51 M.exit_parser = 3
52 M.exit_type = 4
53
54 -- config item specification
55 M.top_level_spec = {
56 -- <program> = {<type>, <default value>}
57 bibtex = {'string', 'bibtex'},
58 clean_files = {'[string]', {
59 '%B.aux', '%B.bbl', '%B.bcf', '%B-blx.bib', '%B.blg', '%B.fls',
60 '%B.idx', '%B.ilg', '%B.ind', '%B.lof', '%B.log', '%B.lot', '%B.nav',
61 '%B.out', '%B.run.xml', '%B.snm', '%B.toc', '%B.vrb',
62 }},
63 clobber_files = {'[string]', {'%B.dvi', '%B.pdf', '%B.ps', '%B.synctex.gz'}},
64 dvipdf = {'string', 'dvipdfmx'},
65 dvips = {'string', 'dvips'},
66 extra_clean_files = {'[string]', {}},
67 latex = {'string', 'lualatex'},
68 llmk_version = {'string', nil},
69 makeindex = {'string', 'makeindex'},
70 makeglossaries = {'string', 'makeglossaries'},
71 max_repeat = {'integer', 5},
72 output_directory = {'string', nil},
73 ps2pdf = {'string', 'ps2pdf'},
74 sequence = {'[string]', {'latex', 'bibtex', 'makeindex', 'makeglossaries', 'dvipdf'}},
75 source = {'*[string]', nil},
76 }
77
78 M.program_spec = {
79 -- <item> = {<type>, {<specifiers allowed>, <default value>}}
80 args = {'*[string]', {true, {'%T'}}},
81 aux_file = {'string', {true, nil}},
82 aux_empty_size = {'integer', {false, nil}},
83 command = {'string', {false, ''}}, -- '' default because it must be string
84 generated_target = {'boolean', {false, false}},
85 opts = {'*[string]', {true, nil}},
86 postprocess = {'string', {false, nil}},
87 target = {'string', {true, '%S'}},
88 }
89
90 M.default_programs = {
91 bibtex = {
92 target = '%B.bib',
93 args = {'%B'}, -- "%B.bib" will result in an error
94 postprocess = 'latex',
95 },
96 dvipdf = {
97 target = '%B.dvi',
98 generated_target = true,
99 },
100 dvips = {
101 target = '%B.dvi',
102 generated_target = true,
103 },
104 latex = {
105 opts = {
106 '-interaction=nonstopmode',
107 '-file-line-error',
108 '-synctex=1',
109 '-output-directory="%o"',
110 },
111 aux_file = '%B.aux',
112 aux_empty_size = 9, -- "\\relax \n" is empty
113 },
114 makeindex = {
115 target = '%B.idx',
116 generated_target = true,
117 postprocess = 'latex',
118 },
119 makeglossaries = {
120 target = '%B.glo',
121 generated_target = true,
122 postprocess = 'latex',
123 opts = {'-d "%o"'},
124 args = {'%b.glo'}, -- "%B.glo" will result in an error
125 },
126 ps2pdf = {
127 target = '%B.ps',
128 generated_target = true,
129 },
130 }
131
132 llmk.const = M
133 end
134
135 ----------------------------------------
136
137 do -- The "util" submodule
138 local M = {}
139
140 local function log(label, msg, ...)
141 local prefix = llmk.const.prog_name .. ' ' .. label .. ': '
142 io.stderr:write(prefix .. msg:format(...) .. '\n')
143 end
144
145 function M.err_print(err_type, msg, ...)
146 if err_type == 'error' then
147 -- error must be reported
148 elseif err_type == 'info' then
149 if llmk.core.verbosity_level < 2 then return end
150 elseif err_type == 'warning' then
151 if llmk.core.verbosity_level < 1 then return end
152 end
153 log(err_type, msg, ...)
154 end
155
156 function M.dbg_print(dbg_type, msg, ...)
157 if llmk.core.debug[dbg_type] then
158 log('debug-' .. dbg_type, msg, ...)
159 end
160 end
161
162 function M.dbg_print_table(dbg_type, table)
163 if not llmk.core.debug[dbg_type] then return end
164
165 local function helper(tab, ind)
166 local function pp(msg, ...)
167 M.dbg_print(dbg_type, string.rep(' ', ind) .. msg, ...)
168 end
169 for k, v in pairs(tab) do
170 if type(v) == 'table' then
171 pp(k .. ':')
172 helper(v, ind + 2)
173 elseif type(v) == 'string' then
174 pp(k .. ': "%s"', v)
175 else -- number, boolean, etc.
176 pp(k .. ': %s', tostring(v))
177 end
178 end
179 end
180
181 helper(table, 2)
182 end
183
184 function M.get_status(raw)
185 if os.type == 'windows' then
186 return raw
187 else
188 return raw / 256
189 end
190 end
191
192 -- Replace config param to filename
193 function M.replace_specifiers(str, source, target, output_directory)
194 local tmp = '/' .. source
195 local basename_match = tmp:match('^.*/(.*)%..*$')
196
197 str = str:gsub('%%S', source)
198 str = str:gsub('%%T', target)
199
200 local sub_basename = source
201 if basename_match then
202 sub_basename = basename_match
203 end
204
205 local sub_output_directory = '.'
206 local sub_output_directory_basename = sub_basename
207 if output_directory then
208 sub_output_directory = output_directory
209 sub_output_directory_basename = output_directory .. '/' .. sub_basename
210 end
211
212 str = str:gsub('%%b', sub_basename)
213 str = str:gsub('%%o', sub_output_directory)
214 str = str:gsub('%%B', sub_output_directory_basename)
215
216 return str
217 end
218
219 llmk.util = M
220 end
221
222 ----------------------------------------
223
224 do -- The "checker" submodule
225 local M = {}
226
227 local function checked_value(k, v, expected)
228 local function error_if_wrong_type(val, t)
229 if type(val) ~= t then
230 llmk.util.err_print('error',
231 '[Type Error] Key "%s" must have value of type %s', k, expected)
232 os.exit(llmk.const.exit_type)
233 end
234 end
235
236 if expected == 'integer' then
237 error_if_wrong_type(v, 'number')
238 elseif expected == 'boolean' then
239 error_if_wrong_type(v, 'boolean')
240 elseif expected == 'string' then
241 error_if_wrong_type(v, 'string')
242 elseif expected == '[string]' then
243 error_if_wrong_type(v, 'table')
244
245 if v[1] ~= nil then -- it is not an empty array
246 error_if_wrong_type(v[1], 'string')
247 end
248 elseif expected == '*[string]' then
249 if type(v) == 'string' then
250 v = {v}
251 else
252 error_if_wrong_type(v, 'table')
253
254 if v[1] ~= nil then -- it is not an empty array
255 error_if_wrong_type(v[1], 'string')
256 end
257 end
258 end
259
260 return v
261 end
262
263 local function type_check(tab)
264 local new_top = {}
265
266 for k, v in pairs(tab) do
267 if k == 'programs' then
268 if type(v) ~= 'table' then
269 llmk.util.err_print('error', '[Type Error] Key "programs" must be a table')
270 os.exit(llmk.const.exit_type)
271 end
272
273 local new_prog = {}
274 for p_name, p_val in pairs(v) do
275 if type(p_val) ~= 'table' then
276 llmk.util.err_print('error',
277 '[Type Error] Key "programs.%s" must be a table', p_name)
278 os.exit(llmk.const.exit_type)
279 else
280 new_prog[p_name] = {}
281 for ik, iv in pairs(p_val) do
282 if not llmk.const.program_spec[ik] then
283 llmk.util.err_print('warning',
284 'Program key "%s" is unknown; ignoring it', ik)
285 else
286 expected = llmk.const.program_spec[ik][1]
287 new_prog[p_name][ik] = checked_value(ik, iv, expected)
288 end
289 end
290 end
291 end
292 new_top[k] = new_prog
293 else
294 if not llmk.const.top_level_spec[k] then
295 llmk.util.err_print('warning',
296 'Top-level key "%s" is unknown; ignoring it', k)
297 else
298 expected = llmk.const.top_level_spec[k][1]
299 new_top[k] = checked_value(k, v, expected)
300 end
301 end
302 end
303
304 return new_top
305 end
306
307 local function version_check(given_version)
308 if not given_version then -- nothing to do
309 return
310 end
311
312 -- parse the given version to the llmk_version key
313 local given_major, given_minor = given_version:match('^(%d+)%.(%d+)')
314 if not given_major or not given_minor then
315 llmk.util.err_print('warning', 'In valid llmk_version: ' .. given_version)
316 return
317 else
318 given_major, given_minor = tonumber(given_major), tonumber(given_minor)
319 end
320
321 -- the version of this program
322 local major, minor = llmk.const.version:match('^(%d+)%.(%d+)')
323 major, minor = tonumber(major), tonumber(minor)
324
325 -- warn if this program is older than the given version
326 if major < given_major or (major == given_major and minor < given_minor) then
327 llmk.util.err_print('warning',
328 'This program (v%d.%d) is older than the specified llmk_version (v%d.%d)',
329 major, minor, given_major, given_minor)
330 end
331
332 -- warn if the given mojor version is older than this program
333 if given_major < major then
334 llmk.util.err_print('warning',
335 'The specified llmk_version (v%d.%d) is older than this program (v%d.%d)',
336 given_major, given_minor, major, minor)
337 end
338
339 -- Note: no breaking change has been made (yet)
340 end
341
342 function M.check(tab)
343 local new_tab = type_check(tab)
344 version_check(new_tab.llmk_version)
345 return new_tab
346 end
347
348 llmk.checker = M
349 end
350
351 ----------------------------------------
352
353 do -- The "config" submodule
354 local M = {}
355
356 local function init_config()
357 local config = {}
358
359 for k, v in pairs(llmk.const.top_level_spec) do
360 config[k] = v[2]
361 end
362
363 config.programs = llmk.const.default_programs
364 return config
365 end
366
367 -- copy command name from top level
368 local function fetch_from_top_level(config, name)
369 if config.programs[name] then
370 if not config.programs[name].command and config[name] then
371 config.programs[name].command = config[name]
372 end
373 end
374 return config
375 end
376
377 local function update_config(config, tab)
378 -- merge the table from TOML
379 local function merge_table(tab1, tab2)
380 for k, v in pairs(tab2) do
381 if k == 'programs' then
382 local programs1 = tab1[k]
383 local programs2 = tab2[k]
384
385 for i_k, i_v in pairs(programs2) do
386 if type(programs1[i_k]) == 'table' then
387 for ii_k, ii_v in pairs(programs2[i_k]) do
388 programs1[i_k][ii_k] = ii_v
389 end
390 else
391 programs1[i_k] = i_v
392 end
393 end
394 else
395 tab1[k] = v
396 end
397 end
398 return tab1
399 end
400 local config = merge_table(config, tab)
401
402 -- set essential program names from top-level
403 local prg_names = {'latex', 'bibtex', 'makeindex', 'makeglossaries', 'dvipdf', 'dvips', 'ps2pdf'}
404 for _, name in pairs(prg_names) do
405 config = fetch_from_top_level(config, name)
406 end
407
408 -- show config table (for debug)
409 llmk.util.dbg_print('config', 'The final config table is as follows:')
410 llmk.util.dbg_print_table('config', config)
411
412 return config
413 end
414
415 function M.fetch_from_latex_source(fn)
416 local tab
417 local config = init_config()
418
419 -- get TOML field and parse it
420 local toml, line = llmk.parser.get_toml(fn)
421 if toml == '' then
422 llmk.util.err_print('warning',
423 'Neither TOML field nor magic comment is found in "%s"; ' ..
424 'using default config', fn)
425 end
426 tab = llmk.parser.parse_toml(toml, {fn, line})
427
428 -- check input and merge it to the config
429 tab = llmk.checker.check(tab)
430 config = update_config(config, tab)
431
432 return config
433 end
434
435 function M.fetch_from_llmk_toml()
436 local tab
437 local config = init_config()
438
439 local f = io.open(llmk.const.llmk_toml)
440 if f ~= nil then
441 local toml = f:read('*all')
442 tab = llmk.parser.parse_toml(toml, {llmk.const.llmk_toml, 1})
443 f:close()
444 else
445 llmk.util.err_print('error', 'No target specified and no %s found',
446 llmk.const.llmk_toml)
447 os.exit(llmk.const.exit_error)
448 end
449
450 -- check input and merge it to the config
451 tab = llmk.checker.check(tab)
452 config = update_config(config, tab)
453
454 return config
455 end
456
457 llmk.config = M
458 end
459
460 ----------------------------------------
461
462 do -- The "parser" submodule
463 --[[
464 This TOML parser is modified version of toml.lua
465 - Copyright 2017 Jonathan Stoler
466 - Licensed under MIT
467 https://github.com/jonstoler/lua-toml/blob/master/LICENSE
468 ]]
469 local M = {}
470
471 function M.parse_toml(toml, file_info)
472 -- basic local variables
473 local ws = '[\009\032]'
474 local nl = '[\10\13\10]'
475
476 local buffer = ''
477 local cursor = 1
478
479 local line = 0
480
481 local res = {}
482 local obj = res
483
484 -- basic local functions
485 local function parser_err(msg)
486 local function get_toml_str(nol)
487 local pattern = string.format('([^%s]*)%s', nl:sub(2, -2), nl)
488 local l = 0
489 for cur_line in toml:gmatch(pattern) do
490 if l == nol then
491 return cur_line
492 end
493 l = l + 1
494 end
495 end
496
497 llmk.util.err_print('error', '[Parse Error] %s', msg)
498 llmk.util.err_print('error', '--> %s:%d: %s',
499 file_info[1], file_info[2] + line, get_toml_str(line))
500 os.exit(llmk.const.exit_parser)
501 end
502
503 local function char(n)
504 n = n or 0
505 return toml:sub(cursor + n, cursor + n)
506 end
507
508 local function step(n)
509 n = n or 1
510 for i = 0, n-1 do
511 if char(i):match(nl) then
512 line = line + 1
513 end
514 end
515 cursor = cursor + n
516 end
517
518 local function skip_ws()
519 while(char():match(ws)) do
520 step()
521 end
522 end
523
524 local function trim(str)
525 return str:gsub('^%s*(.-)%s*$', '%1')
526 end
527
528 local function bounds()
529 return cursor <= toml:len()
530 end
531
532 -- parse functions for each type
533 local function parse_string()
534 -- TODO: multiline
535 local del = char() -- ' or "
536 local str = ''
537 -- all available escape characters
538 local escape = {
539 b = "\b",
540 t = "\t",
541 n = "\n",
542 f = "\f",
543 r = "\r",
544 ['"'] = '"',
545 ["\\"] = "\\",
546 }
547 -- utf function from http://stackoverflow.com/a/26071044
548 -- converts \uXXX into actual unicode
549 local function utf(char)
550 local bytemarkers = {{0x7ff, 192}, {0xffff, 224}, {0x1fffff, 240}}
551 if char < 128 then return string.char(char) end
552 local charbytes = {}
553 for bytes, vals in pairs(bytemarkers) do
554 if char <= vals[1] then
555 for b = bytes + 1, 2, -1 do
556 local mod = char % 64
557 char = (char - mod) / 64
558 charbytes[b] = string.char(128 + mod)
559 end
560 charbytes[1] = string.char(vals[2] + char)
561 break
562 end
563 end
564 return table.concat(charbytes)
565 end
566
567 -- skip the quotes
568 step()
569
570 while(bounds()) do
571 -- end of string
572 if char() == del then
573 step()
574 break
575 end
576
577 if char():match(nl) then
578 parser_err('Single-line string cannot contain line break')
579 end
580
581 if del == '"' and char() == '\\' then -- process escape characters
582 if escape[char(1)] then
583 -- normal escape
584 str = str .. escape[char(1)]
585 step(2) -- go past backslash and the character
586 elseif char(1) == 'u' then
587 -- utf-16
588 step()
589 local uni = char(1) .. char(2) .. char(3) .. char(4)
590 step(5)
591 uni = tonumber(uni, 16)
592 if (uni >= 0 and uni <= 0xd7ff) and not (uni >= 0xe000 and uni <= 0x10ffff) then
593 str = str .. utf(uni)
594 else
595 parser_err('Unicode escape is not a Unicode scalar')
596 end
597 elseif char(1) == 'U' then
598 -- utf-32
599 step()
600 local uni = char(1) .. char(2) .. char(3) .. char(4) ..
601 char(5) .. char(6) .. char(7) .. char(8)
602 step(9)
603 uni = tonumber(uni, 16)
604 if (uni >= 0 and uni <= 0xd7ff) and not (uni >= 0xe000 and uni <= 0x10ffff) then
605 str = str .. utf(uni)
606 else
607 parser_err('Unicode escape is not a Unicode scalar')
608 end
609 else
610 parser_err('Invalid escape')
611 end
612 else -- literal string; leave as it is
613 str = str .. char()
614 step()
615 end
616 end
617
618 return str
619 end
620
621 local function parse_number()
622 -- TODO: exp, date
623 local num = ''
624
625 while(bounds()) do
626 if char():match('[%+%-%.eE_0-9]') then
627 if char() ~= '_' then
628 num = num .. char()
629 end
630 elseif char():match(nl) then
631 break
632 elseif char():match(ws) or char() == '#' then
633 break
634 else
635 parser_err('Invalid number')
636 end
637 step()
638 end
639
640 return tonumber(num)
641 end
642
643 local get_value
644
645 local function parse_array()
646 step()
647 skip_ws()
648
649 local a_type
650 local array = {}
651
652 while(bounds()) do
653 if char() == ']' then
654 break
655 elseif char():match(nl) then
656 step()
657 skip_ws()
658 elseif char() == '#' then
659 while(bounds() and not char():match(nl)) do
660 step()
661 end
662 else
663 local v = get_value()
664 if not v then break end
665
666 if a_type == nil then
667 a_type = type(v)
668 elseif a_type ~= type(v) then
669 parser_err('Mixed types in array')
670 end
671
672 array = array or {}
673 table.insert(array, v)
674
675 if char() == ',' then
676 step()
677 end
678 skip_ws()
679 end
680 end
681 step()
682
683 return array
684 end
685
686 local function parse_boolean()
687 local bool
688
689 if toml:sub(cursor, cursor + 3) == 'true' then
690 step(4)
691 bool = true
692 elseif toml:sub(cursor, cursor + 4) == 'false' then
693 step(5)
694 bool = false
695 else
696 parser_err('Invalid primitive')
697 end
698
699 skip_ws()
700 if char() == '#' then
701 while(not char():match(nl)) do
702 step()
703 end
704 end
705
706 return bool
707 end
708
709 -- judge the type and get the value
710 get_value = function()
711 if (char() == '"' or char() == "'") then
712 return parse_string()
713 elseif char():match('[%+%-0-9]') then
714 return parse_number()
715 elseif char() == '[' then
716 return parse_array()
717 -- TODO: array of table, inline table
718 else
719 return parse_boolean()
720 end
721 end
722
723 -- main loop of parser
724 while(cursor <= toml:len()) do
725 -- ignore comments and whitespace
726 if char() == '#' then
727 while(not char():match(nl)) do
728 step()
729 end
730 end
731
732 if char() == '=' then
733 step()
734 skip_ws()
735
736 -- prepare the key
737 local key = trim(buffer)
738 buffer = ''
739
740 if key == '' then
741 parser_err('Empty key name')
742 elseif obj[key] then
743 -- duplicate keys are not allowed
744 parser_err('Cannot redefine key "' .. key .. '"')
745 end
746
747 local value = get_value()
748 if value ~= nil then
749 obj[key] = value
750 --dbg_print('parser', 'Entry "' .. key .. ' = ' .. value .. '"')
751 end
752
753 -- skip whitespace and comments
754 skip_ws()
755 if char() == '#' then
756 while(bounds() and not char():match(nl)) do
757 step()
758 end
759 end
760
761 -- if garbage remains on this line, raise an error
762 if not char():match(nl) and cursor < toml:len() then
763 parser_err('Invalid primitive')
764 end
765
766 elseif char() == '[' then
767 buffer = ''
768 step()
769 local table_array = false
770
771 if char() == '[' then
772 table_array = true
773 step()
774 end
775
776 obj = res
777
778 local function process_key(is_last)
779 is_last = is_last or false
780 buffer = trim(buffer)
781
782 if buffer == '' then
783 parser_err('Empty table name')
784 end
785
786 if is_last and obj[buffer] and not table_array and #obj[buffer] > 0 then
787 parser_err('Cannot redefine tabel')
788 end
789
790 if table_array then
791 if obj[buffer] then
792 obj = obj[buffer]
793 if is_last then
794 table.insert(obj, {})
795 end
796 obj = obj[#obj]
797 else
798 obj[buffer] = {}
799 obj = obj[buffer]
800 if is_last then
801 table.insert(obj, {})
802 obj = obj[1]
803 end
804 end
805 else
806 obj[buffer] = obj[buffer] or {}
807 obj = obj[buffer]
808 end
809 end
810
811 while(bounds()) do
812 if char() == ']' then
813 if table_array then
814 if char(1) ~= ']' then
815 parser_err('Mismatching brackets')
816 else
817 step()
818 end
819 end
820 step()
821
822 process_key(true)
823 buffer = ''
824 break
825 --elseif char() == '"' or char() == "'" then
826 -- TODO: quoted keys
827 elseif char() == '.' then
828 step()
829 process_key()
830 buffer = ''
831 else
832 buffer = buffer .. char()
833 step()
834 end
835 end
836
837 buffer = ''
838 --elseif (char() == '"' or char() == "'") then
839 -- TODO: quoted keys
840 end
841
842 -- put the char to the buffer and proceed
843 buffer = buffer .. (char():match(nl) and '' or char())
844 step()
845 end
846
847 return res
848 end
849
850 function M.get_toml(fn)
851 local toml = ''
852 local toml_field = false
853 local toml_source = fn
854
855 local f = io.open(toml_source)
856
857 llmk.util.dbg_print('config', 'Looking for config in the file "%s"', toml_source)
858
859 local ts_tmp
860 local ts_latex
861 local ts_bibtex
862
863 local first_line = true
864 local shebang
865
866 local line = 0
867 local start_pos = -1
868
869 for l in f:lines() do
870 line = line + 1
871
872 -- 1. llmk-style TOML field
873 if string.match(l, '^%s*%%%s*%+%+%++%s*$') then
874 -- NOTE: only topmost field is valid
875 if not toml_field then
876 toml_field = true
877 start_pos = line + 1
878 else
879 llmk.util.dbg_print('config', 'TOML field found')
880 break
881 end
882 else
883 if toml_field then
884 local match = string.match(l, '^%s*%%%s*(.-)%s*$')
885 if match == nil then
886 llmk.util.err_print('error', 'Encounter invalid line in TOML field')
887 os.exit(llmk.const.exit_error)
888 else
889 toml = toml .. match .. '\n'
890 end
891 end
892 end
893
894 -- 2. TeXShop directives
895 ts_tmp = string.match(l, '^%s*%%%s*!%s*TEX%s+program%s*=%s*(.-)%s*$') or
896 string.match(l, '^%s*%%%s*!%s*TeX%s+program%s*=%s*(.-)%s*$') or
897 string.match(l, '^%s*%%%s*!%s*TEX%s+TS%-program%s*=%s*(.-)%s*$')
898 if ts_tmp then
899 ts_latex = ts_latex or ts_tmp
900 end
901
902 ts_tmp = string.match(l, '^%s*%%%s*!%s*BIB%s+program%s*=%s*(.-)%s*$') or
903 string.match(l, '^%s*%%%s*!%s*BIB%s+TS%-program%s*=%s*(.-)%s*$')
904 if ts_tmp then
905 ts_bibtex = ts_bibtex or ts_tmp
906 end
907
908 -- 3. shebang
909 if first_line then
910 first_line = false
911 shebang = string.match(l, '^%s*%%#!%s*(.-)%s*$')
912 end
913 end
914
915 f:close()
916
917 -- convert magic or shebang to TOML
918 if toml == '' and (ts_latex or ts_bibtex) then
919 llmk.util.dbg_print('config', 'TeXShop directives found')
920 if ts_latex then
921 toml = toml .. 'latex = "' .. ts_latex .. '"\n'
922 end
923 if ts_bibtex then
924 toml = toml .. 'bibtex = "' .. ts_bibtex .. '"\n'
925 end
926 elseif toml == '' and shebang then
927 llmk.util.dbg_print('config', 'Shebang found')
928 toml = 'latex = "' .. shebang .. '"\n'
929 end
930
931 return toml, start_pos
932 end
933
934 llmk.parser = M
935 end
936
937 ----------------------------------------
938
939 do -- The "runner" submodule
940 local M = {}
941
942 -- dependencies
943 local lfs = require 'lfs'
944 local md5 = require 'md5'
945
946 -- module local variable
947 local start_time = os.time()
948
949 local function table_copy(org)
950 local copy
951 if type(org) == 'table' then
952 copy = {}
953 for org_key, org_value in next, org, nil do
954 copy[table_copy(org_key)] = table_copy(org_value)
955 end
956 setmetatable(copy, table_copy(getmetatable(org)))
957 else -- number, string, boolean, etc.
958 copy = org
959 end
960 return copy
961 end
962
963 local function setup_programs(fn, config)
964 --[[Setup the programs table for each sequence.
965
966 Collecting tables of only related programs, which appears in the
967 `config.sequence` or `prog.postprocess`, and replace all specifiers.
968
969 Args:
970 fn (str): the input FILE name
971
972 Returns:
973 table of program tables
974 ]]
975 local prognames = {}
976 local new_programs = {}
977 local programs = config.programs
978
979 -- collect related programs
980 local function add_progname(name)
981 -- is the program known?
982 if not programs[name] then
983 llmk.util.err_print('error', 'Unknown program "%s" is in the sequence', name)
984 os.exit(llmk.const.exit_error)
985 end
986
987 -- if not new, no addition
988 for _, c in pairs(prognames) do
989 if c == name then
990 return
991 end
992 end
993
994 -- if new, add it!
995 prognames[#prognames + 1] = name
996 end
997
998 for _, name in pairs(config.sequence) do
999 -- add the program name
1000 add_progname(name)
1001
1002 -- add postprocess program if any
1003 local postprocess = programs[name].postprocess
1004 if postprocess then
1005 add_progname(postprocess)
1006 end
1007 end
1008
1009 -- setup the programs
1010 for _, name in ipairs(prognames) do
1011 local prog = table_copy(programs[name])
1012
1013 -- setup the `prog.target`
1014 local cur_target
1015
1016 if prog.target == nil then
1017 -- the default value of `prog.target` is `fn`
1018 cur_target = fn
1019 else
1020 -- here, %T should be replaced by `fn`
1021 cur_target = llmk.util.replace_specifiers(prog.target, fn, fn, config.output_directory)
1022 end
1023
1024 prog.target = cur_target
1025
1026 -- initialize other items
1027 for k, v in pairs(llmk.const.program_spec) do
1028 if k ~= 'target' then -- target is a special case: already treated
1029 if prog[k] == nil then
1030 if type(v[2][2]) == 'table' then
1031 prog[k] = table_copy(v[2][2])
1032 else
1033 prog[k] = v[2][2]
1034 end
1035 end
1036
1037 if v[2][1] then -- need to replace specifiers
1038 if type(prog[k]) == 'table' then
1039 for ik, iv in ipairs(prog[k]) do
1040 if type(prog[k][ik]) == 'string' then
1041 prog[k][ik] = llmk.util.replace_specifiers(iv, fn, cur_target, config.output_directory)
1042 end
1043 end
1044 elseif type(prog[k]) == 'string' then
1045 prog[k] = llmk.util.replace_specifiers(prog[k], fn, cur_target, config.output_directory)
1046 end
1047 end
1048 end
1049 end
1050
1051 -- register the program
1052 new_programs[name] = prog
1053 end
1054
1055 return new_programs
1056 end
1057
1058 local function file_mtime(path)
1059 return lfs.attributes(path, 'modification')
1060 end
1061
1062 local function file_size(path)
1063 return lfs.attributes(path, 'size')
1064 end
1065
1066 local function file_md5sum(path)
1067 local f = assert(io.open(path, 'rb'))
1068 local content = f:read('*a')
1069 f:close()
1070 return md5.sumhexa(content)
1071 end
1072
1073 local function file_status(path)
1074 return {
1075 mtime = file_mtime(path),
1076 size = file_size(path),
1077 md5sum = file_md5sum(path),
1078 }
1079 end
1080
1081 local function init_file_database(programs, fn, config)
1082 -- the template
1083 local fdb = {
1084 targets = {},
1085 aux_files = {},
1086 }
1087
1088 -- investigate current status
1089 for _, v in ipairs(config.sequence) do
1090 -- names
1091 local cur_target = programs[v].target
1092 local cur_aux = programs[v].aux_file
1093
1094 -- target
1095 if lfs.isfile(cur_target) and not fdb.targets[cur_target] then
1096 fdb.targets[cur_target] = file_status(cur_target)
1097 end
1098
1099 -- aux_file
1100 if cur_aux then -- `prog.aux_file` is optional
1101 if lfs.isfile(cur_aux) and not fdb.aux_files[cur_aux] then
1102 fdb.aux_files[cur_aux] = file_status(cur_aux)
1103 end
1104 end
1105 end
1106
1107 return fdb
1108 end
1109
1110 local function construct_cmd(prog)
1111 -- construct the option
1112 local cmd_opt = ''
1113
1114 if prog.opts then
1115 -- construct each option
1116 for _, opt in ipairs(prog.opts) do
1117 if #opt > 0 then
1118 cmd_opt = cmd_opt .. ' ' .. opt
1119 end
1120 end
1121 end
1122
1123 -- construct the argument
1124 local cmd_arg = ''
1125
1126 -- construct each argument
1127 for _, arg in ipairs(prog.args) do
1128 cmd_arg = cmd_arg .. ' "' .. arg .. '"'
1129 end
1130
1131 -- whole command
1132 return prog.command .. cmd_opt .. cmd_arg
1133 end
1134
1135 local function check_rerun(prog, fdb)
1136 llmk.util.dbg_print('run', 'Checking the neccessity of rerun')
1137
1138 local aux = prog.aux_file
1139 local old_aux_exist = false
1140 local old_status
1141
1142 -- if aux file does not exist, no chance of rerun
1143 if not aux then
1144 llmk.util.dbg_print('run', 'No auxiliary file specified')
1145 return false, fdb
1146 end
1147
1148 -- if aux file does not exist, no chance of rerun
1149 if not lfs.isfile(aux) then
1150 llmk.util.dbg_print('run', 'The auxiliary file "%s" does not exist', aux)
1151 return false, fdb
1152 end
1153
1154 -- copy old information and update fdb
1155 if fdb.aux_files[aux] then
1156 old_aux_exist = true
1157 old_status = table_copy(fdb.aux_files[aux])
1158 end
1159 local aux_status = file_status(aux)
1160 fdb.aux_files[aux] = aux_status
1161
1162 -- if aux file is not new, no rerun
1163 local new = aux_status.mtime >= start_time
1164 if not new and old_aux_exist then
1165 new = aux_status.mtime > old_status.mtime
1166 end
1167
1168 if not new then
1169 llmk.util.dbg_print('run', 'No rerun because the aux file is not new')
1170 return false, fdb
1171 end
1172
1173 -- if aux file is empty (or almost), no rerun
1174 if aux_status.size < prog.aux_empty_size then
1175 llmk.util.dbg_print('run', 'No rerun because the aux file is (almost) empty')
1176 return false, fdb
1177 end
1178
1179 -- if new aux is not different from older one, no rerun
1180 if old_aux_exist then
1181 if aux_status.md5sum == old_status.md5sum then
1182 llmk.util.dbg_print('run', 'No rerun because the aux file has not been changed')
1183 return false, fdb
1184 end
1185 end
1186
1187 -- ok, then try rerun
1188 llmk.util.dbg_print('run', 'Try to rerun!')
1189 return true, fdb
1190 end
1191
1192 local function silencer(cmd)
1193 local redirect_code
1194 if os.type == 'windows' then
1195 redirect_code = ' >NUL 2>&1'
1196 else
1197 redirect_code = ' >/dev/null 2>&1'
1198 end
1199 silencer = function(cmd) return cmd .. redirect_code end
1200 return silencer(cmd)
1201 end
1202
1203 local function run_program(name, prog, fn, fdb, postprocess)
1204 -- preparation for dry run
1205 local function concat_cond(tab)
1206 local res
1207 for i, v in ipairs(tab) do
1208 if i == 1 then
1209 res = v
1210 else
1211 res = res .. '; ' .. v
1212 end
1213 end
1214 return res
1215 end
1216 local cond = {}
1217
1218 if postprocess then
1219 cond[#cond + 1] = 'as postprocess'
1220 end
1221
1222 if prog.aux_file then
1223 cond[#cond + 1] = 'possibly with rerunning'
1224 end
1225
1226 -- does command specified?
1227 if #prog.command < 1 then
1228 llmk.util.err_print('warning',
1229 'The "command" key is not set for program "%s"; skipping', name)
1230 return false
1231 end
1232
1233 -- does target exist?
1234 if not llmk.core.dry_run and not lfs.isfile(prog.target) then
1235 llmk.util.dbg_print('run',
1236 'Skipping "%s" because target (%s) does not exist',
1237 prog.command, prog.target)
1238 return false
1239 end
1240
1241 -- is the target modified?
1242 if prog.generated_target then
1243 if llmk.core.dry_run then
1244 cond[#cond + 1] = string.format('if the target file "%s" has been generated',
1245 prog.target)
1246 elseif file_mtime(prog.target) < start_time then
1247 llmk.util.dbg_print('run',
1248 'Skipping "%s" because target (%s) is not updated',
1249 prog.command, prog.target)
1250 return false
1251 end
1252 else
1253 if llmk.core.dry_run then
1254 cond[#cond + 1] = string.format('if the target file "%s" exists', prog.target)
1255 end
1256 end
1257
1258 local cmd = construct_cmd(prog)
1259 if llmk.core.dry_run then
1260 print('Dry running: ' .. cmd)
1261 if #cond > 0 then
1262 llmk.util.err_print('info', '<-- ' .. concat_cond(cond))
1263 end
1264 return false
1265 else
1266 llmk.util.err_print('info', 'Running command: ' .. cmd)
1267 end
1268
1269 -- redirect stdout and stderr to NULL in silent mode
1270 if llmk.core.silent then
1271 cmd = silencer(cmd)
1272 end
1273
1274 -- call and check the status
1275 -- Note: os.execute() returns values 256 multiples of actual status
1276 -- except on Windows
1277 local cmd_status = llmk.util.get_status(os.execute(cmd))
1278 if cmd_status > 0 then
1279 llmk.util.err_print('error',
1280 'Fail running %s (exit code: %d)', cmd, cmd_status)
1281 os.exit(llmk.const.exit_failure)
1282 end
1283
1284 return true
1285 end
1286
1287 local function process_program(programs, name, fn, fdb, config, postprocess)
1288 local postprocess = postprocess or false
1289 local prog = programs[name]
1290 local should_rerun
1291
1292 -- execute the command
1293 local run = false
1294 local exe_count = 0
1295 while true do
1296 exe_count = exe_count + 1
1297 run = run_program(name, prog, fn, fdb, postprocess)
1298
1299 -- if the run is skipped, break immediately
1300 if not run then break end
1301
1302 -- if not neccesarry to rerun or reached to max_repeat, break the loop
1303 should_rerun, fdb = check_rerun(prog, fdb)
1304 if not ((exe_count < config.max_repeat) and should_rerun) then
1305 break
1306 end
1307 end
1308
1309 -- go to the postprocess process
1310 if prog.postprocess and (run or llmk.core.dry_run) then
1311 llmk.util.dbg_print('run', 'Going to postprocess "%s"', prog.postprocess)
1312 process_program(programs, prog.postprocess, fn, fdb, config, true)
1313 end
1314 end
1315
1316 function M.run_sequence(fn, config)
1317 llmk.util.err_print('info', 'Beginning a sequence for "%s"', fn)
1318
1319 -- setup the programs table
1320 local programs = setup_programs(fn, config)
1321 llmk.util.dbg_print('programs', 'Current programs table:')
1322 llmk.util.dbg_print_table('programs', programs)
1323
1324 -- create a file database
1325 local fdb = init_file_database(programs, fn, config)
1326 llmk.util.dbg_print('fdb', 'The initial file database is as follows:')
1327 llmk.util.dbg_print_table('fdb', fdb)
1328
1329 -- check if output directory exists
1330 if config.output_directory and not lfs.isdir(config.output_directory) then
1331 llmk.util.err_print('error', 'Output directory does not exist "%s"', config.output_directory)
1332 end
1333
1334 for _, name in ipairs(config.sequence) do
1335 llmk.util.dbg_print('run', 'Preparing for program "%s"', name)
1336 process_program(programs, name, fn, fdb, config)
1337 end
1338 end
1339
1340 llmk.runner = M
1341 end
1342
1343 do -- The "cleaner" submodule
1344 local M = {}
1345
1346 -- dependencies
1347 local lfs = require("lfs")
1348
1349 -- fn is filepath of target to remove.
1350 local function remove(fn)
1351 if llmk.core.dry_run then
1352 print(string.format('Dry running: removing file "%s"', fn))
1353 else
1354 local ok = os.remove(fn)
1355
1356 if ok ~= true then
1357 llmk.util.err_print('error', 'Failed to remove "%s"', fn)
1358 else
1359 llmk.util.err_print('info', 'Removed "%s"', fn)
1360 end
1361 end
1362 end
1363
1364 local function replace_spec_and_remove_files(fns, source, output_directory)
1365 for _, fn in ipairs(fns) do
1366 local replaced_fn = llmk.util.replace_specifiers(fn, source, source, output_directory)
1367 if lfs.isfile(replaced_fn) then
1368 remove(replaced_fn)
1369 end
1370 end
1371 end
1372
1373 -- the actual process for the --clean action
1374 function M.clean(fn, config)
1375 llmk.util.err_print('info', 'Begining cleaning for "%s"', fn)
1376 replace_spec_and_remove_files(config.clean_files, fn, config.output_directory)
1377 replace_spec_and_remove_files(config.extra_clean_files, fn, config.output_directory)
1378 end
1379
1380 -- the actual process for the --clobber action
1381 function M.clobber(fn, config)
1382 llmk.util.err_print('info', 'Begining clobbering for "%s"', fn)
1383 replace_spec_and_remove_files(config.clean_files, fn, config.output_directory)
1384 replace_spec_and_remove_files(config.extra_clean_files, fn, config.output_directory)
1385 replace_spec_and_remove_files(config.clobber_files, fn, config.output_directory)
1386 end
1387
1388 llmk.cleaner = M
1389 end
1390
1391 ----------------------------------------
1392
1393 do -- The "cli" submodule
1394 local M = {}
1395 local C = llmk.const
1396
1397 local help_text = [[
1398 Usage: llmk [OPTION]... [FILE]...
1399
1400 Options:
1401 -c, --clean Remove the temporary files such as aux and log files.
1402 -C, --clobber Remove all generated files including final PDFs.
1403 -d CAT, --debug=CAT Activate debug output restricted to CAT.
1404 -D, --debug Activate all debug output (equal to "--debug=all").
1405 -h, --help Print this help message.
1406 -n, --dry-run Show what would have been executed.
1407 -q, --quiet Suppress most messages.
1408 -s, --silent Silence messages from called programs.
1409 -v, --verbose Print additional information.
1410 -V, --version Print the version number.
1411
1412 Please report bugs to <https://github.com/wtsnjp/llmk/issues>.
1413 ]]
1414
1415 local version_text = [[
1416 %s %s
1417
1418 %s %s.
1419 License: The MIT License <https://opensource.org/licenses/mit-license>.
1420 This is free software: you are free to change and redistribute it.
1421 ]]
1422
1423 -- execution functions
1424 local function read_options()
1425 local curr_arg
1426 local action = false
1427
1428 -- modified Alternative Get Opt
1429 -- cf. http://lua-users.org/wiki/AlternativeGetOpt
1430 local function getopt(arg, options)
1431 local tmp
1432 local tab = {}
1433 local saved_arg = {table.unpack(arg)}
1434 for k, v in ipairs(saved_arg) do
1435 if string.sub(v, 1, 2) == '--' then
1436 table.remove(arg, 1)
1437 local x = string.find(v, '=', 1, true)
1438 if x then
1439 table.insert(tab, {string.sub(v, 3, x-1), string.sub(v, x+1)})
1440 else
1441 table.insert(tab, {string.sub(v, 3), true})
1442 end
1443 elseif string.sub(v, 1, 1) == '-' then
1444 table.remove(arg, 1)
1445 local y = 2
1446 local l = string.len(v)
1447 local jopt
1448 while (y <= l) do
1449 jopt = string.sub(v, y, y)
1450 if string.find(options, jopt, 1, true) then
1451 if y < l then
1452 tmp = string.sub(v, y+1)
1453 y = l
1454 else
1455 table.remove(arg, 1)
1456 tmp = saved_arg[k + 1]
1457 end
1458 if string.match(tmp, '^%-') then
1459 table.insert(tab, {jopt, false})
1460 else
1461 table.insert(tab, {jopt, tmp})
1462 end
1463 else
1464 table.insert(tab, {jopt, true})
1465 end
1466 y = y + 1
1467 end
1468 end
1469 end
1470 return tab
1471 end
1472
1473 local opts = getopt(arg, 'd')
1474 for _, tp in pairs(opts) do
1475 k, v = tp[1], tp[2]
1476 if #k == 1 then
1477 curr_arg = '-' .. k
1478 else
1479 curr_arg = '--' .. k
1480 end
1481
1482 -- action
1483 if (curr_arg == '-h') or (curr_arg == '--help') then
1484 return 'help' -- immediately show help
1485 elseif (curr_arg == '-V') or (curr_arg == '--version') then
1486 return 'version' -- immediately show version
1487 elseif (curr_arg == '-c') or (curr_arg == '--clean') then
1488 action = 'clean'
1489 elseif (curr_arg == '-C') or (curr_arg == '--clobber') then
1490 action = 'clobber'
1491 -- debug
1492 elseif (curr_arg == '-D') or
1493 (curr_arg == '--debug' and (v == 'all' or v == true)) then
1494 for c, _ in pairs(llmk.core.debug) do
1495 llmk.core.debug[c] = true
1496 end
1497 elseif (curr_arg == '-d') or (curr_arg == '--debug') then
1498 if llmk.core.debug[v] == nil then
1499 llmk.util.err_print('warning', 'unknown debug category: ' .. v)
1500 else
1501 llmk.core.debug[v] = true
1502 end
1503 -- verbosity
1504 elseif (curr_arg == '-q') or (curr_arg == '--quiet') then
1505 llmk.core.verbosity_level = 0
1506 elseif (curr_arg == '-v') or (curr_arg == '--verbose') then
1507 llmk.core.verbosity_level = 2
1508 elseif (curr_arg == '-s') or (curr_arg == '--silent') then
1509 llmk.core.silent = true
1510 -- dry run
1511 elseif (curr_arg == '-n') or (curr_arg == '--dry-run') then
1512 llmk.core.dry_run = true
1513 -- problem
1514 else
1515 llmk.util.err_print('error', 'unknown option: ' .. curr_arg)
1516 os.exit(C.exit_error)
1517 end
1518 end
1519
1520 return action
1521 end
1522
1523 local function check_filename(fn)
1524 if lfs.isfile(fn) then
1525 return fn -- ok
1526 end
1527
1528 local ext = fn:match('%.(.-)$')
1529 if ext ~= nil then
1530 return nil
1531 end
1532
1533 local new_fn = fn .. '.tex'
1534 if lfs.isfile(new_fn) then
1535 return new_fn
1536 else
1537 return nil
1538 end
1539 end
1540
1541 local function make(fns, func)
1542 local config
1543 if #fns > 0 then
1544 for _, fn in ipairs(fns) do
1545 local checked_fn = check_filename(fn)
1546 if checked_fn then
1547 config = llmk.config.fetch_from_latex_source(checked_fn)
1548 func(checked_fn, config)
1549 else
1550 llmk.util.err_print('error', 'Source file "%s" does not exist', fn)
1551 os.exit(C.exit_error)
1552 end
1553 end
1554 else
1555 config = llmk.config.fetch_from_llmk_toml()
1556
1557 local source = config.source
1558 if source ~= nil then
1559 for _, fn in ipairs(source) do
1560 local checked_fn = check_filename(fn)
1561 if checked_fn then
1562 func(checked_fn, config)
1563 else
1564 llmk.util.err_print('error', 'Source file "%s" does not exist', fn)
1565 os.exit(C.exit_error)
1566 end
1567 end
1568 else
1569 llmk.util.err_print('error', 'No source detected')
1570 os.exit(C.exit_error)
1571 end
1572 end
1573 end
1574
1575 local function do_action(action)
1576 if action == 'help' then
1577 io.stdout:write(help_text)
1578 elseif action == 'version' then
1579 io.stdout:write(version_text:format(
1580 C.prog_name, C.version, C.copyright, C.author))
1581 elseif action == 'clean' then
1582 make(arg, llmk.cleaner.clean)
1583 elseif action == 'clobber' then
1584 make(arg, llmk.cleaner.clobber)
1585 end
1586 end
1587
1588 function M.exec()
1589 local action = read_options()
1590
1591 if action then
1592 do_action(action)
1593 os.exit(C.exit_ok)
1594 end
1595
1596 make(arg, llmk.runner.run_sequence)
1597 os.exit(C.exit_ok)
1598 end
1599
1600 llmk.cli = M
1601 end
1602
1603 ----------------------------------------
1604
1605 assert(llmk.cli, 'Internal error: llmk is not installed properly')
1606 llmk.cli.exec()
1607
1608 -- EOF