2 -- luatexja/ltj-base.lua
5 local tostring = tostring
6 local node, table, tex, token = node, table, tex, token
8 local cat_lp = luatexbase.catcodetables['latex-package']
14 local public_name = 'luatexja'
15 local public_version = 'alpha'
16 ltjb.public_name = public_name
17 ltjb.public_version = public_version
20 -------------------- Fully-expandable error messaging
21 local _error_set_break, _error_set_message, _error_show
22 local generic_error, _generic_warn_info
23 local generic_warning, generic_warning_no_line
24 local generic_info, generic_info_no_line
25 local package_error, package_warning, package_warning_no_line
26 local package_info, package_info_no_line
27 local ltj_error, ltj_warning_no_line
30 --! LaTeX 形式のエラーメッセージ(\PackageError 等)を
38 local function message_cont(str, c)
39 return str:gsub(err_break, LF .. c)
41 local function into_lines(str)
42 return str:gsub(err_break, LF):explode(LF)
45 _error_set_break = function (str)
49 _error_set_message = function (msgcont, main, help)
50 err_main = message_cont(main, msgcont)
51 err_help = into_lines(help)
54 _error_show = function (escchar)
55 local escapechar = tex.escapechar
56 local newlinechar = tex.newlinechar
57 local errorcontextlines = tex.errorcontextlines
58 if not escchar then tex.escapechar = -1 end
60 tex.errorcontextlines = -1
61 tex.error(err_main, err_help)
62 tex.escapechar = escapechar
63 tex.newlinechar = newlinechar
64 tex.errorcontextlines = errorcontextlines
67 local message_a = "Type H <return> for immediate help"
69 generic_error = function (msgcont, main, ref, help)
70 local mainref = main..".\n\n"..ref.."\n"..message_a
71 _error_set_message(msgcont, mainref, help)
75 _generic_warn_info = function (msgcont, main, warn, line)
76 local mainc = message_cont(main, msgcont)
77 local br = warn and "\n" or ""
78 local out = warn and "term and log" or "log"
79 local on_line = line and (" on input line "..tex.inputlineno) or ""
80 local newlinechar = tex.newlinechar
82 texio.write_nl(out, br..main..on_line.."."..br)
83 tex.newlinechar = newlinechar
86 generic_warning = function (msgcont, main)
87 _generic_warn_info(msgcont, main, true, true)
89 generic_warning_no_line = function (msgcont, main)
90 _generic_warn_info(msgcont, main, true, false)
92 generic_info = function (msgcont, main)
93 _generic_warn_info(msgcont, main, false, true)
95 generic_info_no_line = function (msgcont, main)
96 _generic_warn_info(msgcont, main, false, false)
99 package_error = function (pkgname, main, help)
100 generic_error("("..pkgname.." ",
101 "Package "..pkgname.." Error: "..main,
102 "See the "..pkgname.." package documentation for explanation.",
105 package_warning = function (pkgname, main)
106 generic_warning("("..pkgname.." ",
107 "Package "..pkgname.." Warning: "..main)
109 package_warning_no_line = function (pkgname, main)
110 generic_warning_no_line("("..pkgname.." ",
111 "Package "..pkgname.." Warning: "..main)
113 package_info = function (pkgname, main)
114 generic_info("("..pkgname.." ",
115 "Package "..pkgname.." Info: "..main)
117 package_info_no_line = function (pkgname, main)
118 generic_info_no_line("("..pkgname.." ",
119 "Package "..pkgname.." Info: "..main)
122 ltj_error = function (main, help)
123 package_error(public_name, main, help)
125 ltj_warning_no_line = function (main)
126 package_warning_no_line(public_name, main, help)
130 -------------------- TeX stream I/O
131 --! ixbase.print() と同じ
132 --- Extension to tex.print(). Each argument string may contain
133 -- newline characters, in which case the string is output (to
134 -- TeX input stream) as multiple lines.
135 -- @param ... (string) string to output
136 local function mprint(...)
139 if type(arg[1]) == "number" then
140 table.insert(lines, arg[1])
143 for _, cnk in ipairs(arg) do
144 local ls = cnk:explode("\n")
145 if ls[#ls] == "" then
146 table.remove(ls, #ls)
148 for _, l in ipairs(ls) do
149 table.insert(lines, l)
152 return tex.print(unpack(lines))
156 -------------------- Handling of TeX values
159 local glue_spec_id = node.id("glue_spec")
161 local function copy_skip(s1, s2)
163 s1 = node.new(glue_spec_id)
165 s1.width = s2.width or 0
166 s1.stretch = s2.stretch or 0
167 s1.stretch_order = s2.stretch_order or 0
168 s1.shrink = s2.shrink or 0
169 s1.shrink_order = s2.shrink_order or 0
173 --! ixbase.to_dimen() と同じ
174 local function to_dimen(val)
177 elseif type(val) == "number" then
180 return tex.sp(tostring(val))
184 local function parse_dimen(val)
185 val = tostring(val):lower()
186 local r, fil = val:match("([-.%d]+)fi(l*)")
188 val, fil = r.."pt", fil:len() + 1
192 return tex.sp(val), fil
195 --! ixbase.to_skip() と同じ
196 local function to_skip(val)
197 if type(val) == "userdata" then
200 local res = node.new(glue_spec_id)
203 elseif type(val) == "number" then
205 elseif type(val) == "table" then
208 local t = tostring(val):lower():explode()
209 local w, p, m = t[1], t[3], t[5]
210 if t[2] == "minus" then
213 res.width = tex.sp(t[1])
215 res.stretch, res.stretch_order = parse_dimen(p)
218 res.shrink, res.shrink_order = parse_dimen(m)
224 local function dump_skip(s)
225 print(("%s+%s<%s>-%s<%s>"):format(
226 s.width or 0, s.stretch or 0, s.stretch_order or 0,
227 s.shrink or 0, s.shrink_order or 0))
230 ltjb.to_dimen = to_dimen
231 ltjb.dump_skip = dump_skip
232 ltjb.to_skip = to_skip
235 -------------------- Virtual table for LaTeX counters
236 -- not used in current LuaTeX-ja
238 --! ixbase.counter と同じ
240 local mt_counter = {}
241 setmetatable(counter, mt_counter)
243 function mt_counter.__index(tbl, key)
244 return tex.count['c@'..key]
246 function mt_counter.__newindex(tbl, key, val)
247 tex.count['c@'..key] = val
249 ltjb.counter = counter
251 --! ixbase.length は tex.skip と全く同じなので不要.
254 -------------------- Number handling in TeX source
257 local tok_escape = token.create("ltj@@q@escape")
258 local tok_num = token.create("ltj@@q@escapenum")
259 local c_id_assign_int = token.command_id("assign_int")
260 local c_id_char_given = token.command_id("char_given")
262 local function error_scan()
263 package_error("luatexja",
264 "Missing number of a permitted form, treated as zero",
265 "A number should have been here; I inserted '0'.")
268 local function get_expd_next()
269 local next = token.get_next()
270 while token.is_expandable(next) do
272 next = token.get_next()
277 local function grab_decimal(next, res)
278 table.insert(res, next)
280 next = get_expd_next()
281 if not (next[1] == 12 and 0x30 <= next[2] and next[2] <= 0x39) then
284 table.insert(res, next)
286 if next[1] == 10 then next = nil end
290 local function grab_hexa(next, res)
292 table.insert(res, next)
294 next = get_expd_next()
295 if not ((next[1] == 12 and (0x30 <= next[2] and next[2] <= 0x39)) or
296 ((next[1] == 12 or next[1] == 11) and
297 (0x41 <= next[2] and next[2] <= 0x46))) then
301 table.insert(res, next)
303 if next[1] == 10 then next = nil end
307 local function grab_octal(next, res)
309 table.insert(res, next)
311 next = get_expd_next()
312 if not (next[1] == 12 and (0x30 <= next[2] and next[2] <= 0x37)) then
316 table.insert(res, next)
318 if next[1] == 10 then next = nil end
322 local function grab_charnum(next, res)
323 table.insert(res, next)
324 next = token.get_next()
325 table.insert(res, next)
326 next = get_expd_next()
327 if next[1] == 10 then next = nil end
331 local function scan_with(delay, scanner)
332 local function proc()
334 if delay > 0 then delay = delay - 1 end
335 return token.get_next()
337 local cont, back = scanner()
339 ltb.remove_from_callback("token_filter", "ltj@grab@num")
344 ltb.add_to_callback("token_filter", proc, "ltj@grab@num", 1)
347 local function scan_brace()
348 scan_with(1, function()
349 local next = token.get_next()
351 return false, { tok_escape, next }
352 elseif next[1] == 10 then
353 return true, { next }
355 return false, { next }
360 local function scan_number()
361 scan_with(1, function()
362 local next = get_expd_next()
363 local res, ok = { tok_num }, false
365 if next[1] == 12 and (next[2] == 0x2B or next[2] == 0x2D) then
366 table.insert(res, next)
367 elseif next[1] ~= 10 then
370 next = get_expd_next()
372 if next[1] == 12 and 0x30 <= next[2] and next[2] <= 0x39 then
373 ok, next = grab_decimal(next, res)
374 elseif next[1] == 12 and next[2] == 0x22 then
375 ok, next = grab_hexa(next, res)
376 elseif next[1] == 12 and next[2] == 0x27 then
377 ok, next = grab_octal(next, res)
378 elseif next[1] == 12 and next[2] == 0x60 then
379 ok, next = grab_charnum(next, res)
380 elseif next[1] == c_id_assign_int or next[1] == c_id_char_given then
381 table.insert(res, next)
385 table.insert(res, tok_num)
390 if next then table.insert(res, next) end
395 ltjb.scan_brace = scan_brace
396 ltjb.scan_number = scan_number
399 -------------------- TeX register allocation
400 -- not used in current LuaTeX-ja
403 local cmod_base_count = token.create('ltj@@count@zero')[2]
404 local cmod_base_attr = token.create('ltj@@attr@zero')[2]
405 local cmod_base_dimen = token.create('ltj@@dimen@zero')[2]
406 local cmod_base_skip = token.create('ltj@@skip@zero')[2]
408 local function const_number(name)
409 if name:sub(1, 1) == '\\' then name = name:sub(2) end
410 return token.create(name)[2]
413 local function count_number(name)
414 if name:sub(1, 1) == '\\' then name = name:sub(2) end
415 return token.create(name)[2] - cmod_base_count
418 local function attribute_number(name)
419 if name:sub(1, 1) == '\\' then name = name:sub(2) end
420 return token.create(name)[2] - cmod_base_attr
423 local function dimen_number(name)
424 if name:sub(1, 1) == '\\' then name = name:sub(2) end
425 return token.create(name)[2] - cmod_base_dimen
428 local function skip_number(name)
429 if name:sub(1, 1) == '\\' then name = name:sub(2) end
430 return token.create(name)[2] - cmod_base_skip
433 ltjb.const_number = const_number
434 ltjb.count_number = count_number
435 ltjb.attribute_number = attribute_number
436 ltjb.dimen_number = dimen_number
437 ltjb.skip_number = skip_number
440 -------------------- getting next token
442 local function get_cs(s)
443 cstemp = token.csname_name(token.get_next())
444 tex.sprint(cat_lp,'\\' .. s)
448 -------------------- common error message
450 local function in_unicode(c, admit_math)
451 local low = admit_math and -1 or 0
452 if type(c)~='number' or c<low or c>0x10FFFF then
453 local s = 'A character number must be between ' .. tostring(low)
454 .. ' and 0x10ffff.\n'
455 .. (admit_math and "(-1 is used for denoting `math boundary')\n" or '')
456 .. 'So I changed this one to zero.'
457 package_error('luatexja',
458 'bad character code (' .. tostring(c) .. ')', s)
463 ltjb.in_unicode = in_unicode
466 -------------------- cache management
467 -- load_cache (filename, outdate)
468 -- * filename: without suffix '.lua'
469 -- * outdate(t): return true iff the cache is outdated
470 -- * return value: non-nil iff the cache is up-to-date
471 -- save_cache (filename, t): no return value
472 -- save_cache_luc (filename, t): no return value
473 -- save_cache always calls save_cache_luc.
474 -- But sometimes we want to create only the precompiled cache,
475 -- when its 'text' version is already present in LuaTeX-ja distribution.
477 require('lualibs-lpeg') -- string.split
478 require('lualibs-os') -- os.type
481 local kpse_var_value = kpse.var_value
482 local path, pathtmp = kpse_var_value("TEXMFVAR")
483 pathtmp = kpse_var_value("TEXMFSYSVAR")
484 if pathtmp then path = (path and path .. ';' or '') .. pathtmp end
485 pathtmp = kpse_var_value("TEXMFCACHE")
486 if pathtmp then path = (path and path .. ';' or '') .. pathtmp end
488 if os.type~='windows' then path = string.gsub(path, ':', ';') end
489 path = table.unique(string.split(path, ';'))
491 local cache_dir = '/luatexja'
492 local find_file = kpse.find_file
493 local join, isreadable = file.join, file.isreadable
494 local tofile, serialize = table.tofile, table.serialize
495 local luc_suffix = jit and '.lub' or '.luc'
497 -- determine save path
499 for _,v in pairs(path) do
500 local testpath = join(v, cache_dir)
501 if not lfs.isdir(testpath) then dir.mkdirs(testpath) end
502 if lfs.isdir(testpath) then savepath = testpath; break end
505 save_cache_luc = function (filename, t, serialized)
506 local fullpath = savepath .. '/' .. filename .. luc_suffix
507 local s = serialized or serialize(t, 'return', false)
510 local f = io.open(fullpath, 'wb')
512 f:write(string.dump(sa, true))
513 texio.write('(save cache: ' .. fullpath .. ')')
519 save_cache = function (filename, t)
520 local fullpath = savepath .. '/' .. filename .. '.lua'
521 local s = serialize(t, 'return', false)
523 local f = io.open(fullpath, 'w')
526 texio.write('(save cache: ' .. fullpath .. ')')
529 save_cache_luc(filename, t, s)
533 local function load_cache_a (filename, outdate)
535 for _,v in pairs(path) do
536 local fn = join(v, cache_dir, filename)
537 if isreadable(fn) then
538 texio.write('(load cache: ' .. fn .. ')')
539 result = loadfile(fn)
540 result = result and result(); break
543 if (not result) or outdate(result) then
550 load_cache = function (filename, outdate)
551 local r = load_cache_a(filename .. luc_suffix, outdate)
555 local r = load_cache_a(filename .. '.lua', outdate)
556 if r then save_cache_luc(filename, r) end -- update the precompiled cache
561 ltjb.load_cache = load_cache
562 ltjb.save_cache_luc = save_cache_luc
563 ltjb.save_cache = save_cache
568 local tex_set_attr, tex_get_attr = tex.setattribute, tex.getattribute
569 function ltjb.ensure_tex_attr(a, v)
570 if tex_get_attr(a)~=v then
577 ltjb._error_set_break = _error_set_break
578 ltjb._error_set_message = _error_set_message
579 ltjb._error_show = _error_show
580 ltjb._generic_warn_info = _generic_warn_info
582 ltjb.package_error = package_error
583 ltjb.package_warning = package_warning
584 ltjb.package_warning_no_line = package_warning_no_line
585 ltjb.package_info = package_info
586 ltjb.package_info_no_line = package_info_no_line
588 ltjb.generic_error = generic_error
589 ltjb.generic_warning = generic_warning
590 ltjb.generic_warning_no_line = generic_warning_no_line
591 ltjb.generic_info = generic_info
592 ltjb.generic_info_no_line = generic_info_no_line
594 ltjb.ltj_warning_no_line = ltj_warning_no_line
595 ltjb.ltj_error = ltj_error
597 -------------------- mock of debug logger
598 if not ltjb.out_debug then
599 local function no_op() end
600 ltjb.start_time_measure = no_op
601 ltjb.stop_time_measure = no_op
602 ltjb.out_debug = no_op
603 ltjb.package_debug = no_op
604 ltjb.debug_logger = function() return no_op end
605 ltjb.show_term = no_op
606 ltjb.show_log = no_op
609 -------------------- all done