OSDN Git Service

fix "Command `\colon' already defined" error when fontspec is loaded without no-math...
[luatex-ja/luatexja.git] / src / ltj-base.lua
1 --
2 -- luatexja/ltj-base.lua
3 --
4 local ltb = luatexbase
5 local tostring = tostring
6 local node, table, tex, token = node, table, tex, token
7
8 local cat_lp = luatexbase.catcodetables['latex-package']
9
10 -------------------- 
11 local ltjb = {}
12 luatexja.base = ltjb
13
14 local public_name = 'luatexja'
15 local public_version = 'alpha'
16 ltjb.public_name = public_name
17 ltjb.public_version = public_version
18
19
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
28
29 do
30 --! LaTeX 形式のエラーメッセージ(\PackageError 等)を
31 --! Lua 関数の呼び出しで行う.
32
33   local LF = "\n"
34   local err_break = ""
35   local err_main = ""
36   local err_help = ""
37
38   local function message_cont(str, c)
39     return str:gsub(err_break, LF .. c)
40   end
41   local function into_lines(str)
42     return str:gsub(err_break, LF):explode(LF)
43   end
44
45   _error_set_break = function (str)
46     err_break = str
47   end
48
49   _error_set_message = function (msgcont, main, help)
50     err_main = message_cont(main, msgcont)
51     err_help = into_lines(help)
52   end
53
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
59     tex.newlinechar = 10
60     tex.errorcontextlines = -1
61     tex.error(err_main, err_help)
62     tex.escapechar = escapechar
63     tex.newlinechar = newlinechar
64     tex.errorcontextlines = errorcontextlines
65   end
66
67   local message_a = "Type  H <return>  for immediate help"
68
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)
72     _error_show(true)
73   end
74
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
81     tex.newlinechar = -1
82     texio.write_nl(out, br..main..on_line.."."..br)
83     tex.newlinechar = newlinechar
84   end
85
86   generic_warning = function (msgcont, main)
87     _generic_warn_info(msgcont, main, true, true)
88   end
89   generic_warning_no_line = function (msgcont, main)
90     _generic_warn_info(msgcont, main, true, false)
91   end
92   generic_info = function (msgcont, main)
93     _generic_warn_info(msgcont, main, false, true)
94   end
95   generic_info_no_line = function (msgcont, main)
96     _generic_warn_info(msgcont, main, false, false)
97   end
98
99   package_error = function (pkgname, main, help)
100     generic_error("("..pkgname.."                ",
101       "Package "..pkgname.." Error: "..main,
102       "See the "..pkgname.." package documentation for explanation.",
103       help)
104   end
105   package_warning = function (pkgname, main)
106     generic_warning("("..pkgname.."                ",
107       "Package "..pkgname.." Warning: "..main)
108   end
109   package_warning_no_line = function (pkgname, main)
110     generic_warning_no_line("("..pkgname.."                ",
111       "Package "..pkgname.." Warning: "..main)
112   end
113   package_info = function (pkgname, main)
114     generic_info("("..pkgname.."             ",
115       "Package "..pkgname.." Info: "..main)
116   end
117   package_info_no_line = function (pkgname, main)
118     generic_info_no_line("("..pkgname.."             ",
119       "Package "..pkgname.." Info: "..main)
120   end
121
122   ltj_error = function (main, help)
123     package_error(public_name, main, help)
124   end
125   ltj_warning_no_line = function (main)
126     package_warning_no_line(public_name, main, help)
127   end
128
129 end
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(...)
137    local arg = {...}
138    local lines = {}
139    if type(arg[1]) == "number" then
140       table.insert(lines, arg[1])
141       table.remove(arg, 1)
142    end
143    for _, cnk in ipairs(arg) do
144       local ls = cnk:explode("\n")
145       if ls[#ls] == "" then
146          table.remove(ls, #ls)
147       end
148       for _, l in ipairs(ls) do
149          table.insert(lines, l)
150       end
151    end
152    return tex.print(unpack(lines))
153 end
154 ltjb.mprint = mprint
155
156 -------------------- Handling of TeX values
157 do
158
159   local glue_spec_id = node.id("glue_spec")
160
161   local function copy_skip(s1, s2)
162     if not s1 then
163       s1 = node.new(glue_spec_id)
164     end
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
170     return s1
171   end
172
173 --! ixbase.to_dimen() と同じ
174   local function to_dimen(val)
175     if val == nil then
176       return 0
177     elseif type(val) == "number" then
178       return val
179     else
180       return tex.sp(tostring(val))
181     end
182   end
183
184   local function parse_dimen(val)
185     val = tostring(val):lower()
186     local r, fil = val:match("([-.%d]+)fi(l*)")
187     if r then
188       val, fil = r.."pt", fil:len() + 1
189     else
190       fil = 0
191     end
192     return tex.sp(val), fil
193   end
194
195 --! ixbase.to_skip() と同じ
196   local function to_skip(val)
197     if type(val) == "userdata" then
198       return val
199     end
200     local res = node.new(glue_spec_id)
201     if val == nil then
202       res.width = 0
203     elseif type(val) == "number" then
204       res.width = val
205     elseif type(val) == "table" then
206       copy_skip(res, val)
207     else
208       local t = tostring(val):lower():explode()
209       local w, p, m = t[1], t[3], t[5]
210       if t[2] == "minus" then
211         p, m = nil, t[3]
212       end
213       res.width = tex.sp(t[1])
214       if p then
215         res.stretch, res.stretch_order = parse_dimen(p)
216       end
217       if m then
218         res.shrink, res.shrink_order = parse_dimen(m)
219       end
220     end
221     return res
222   end
223
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))
228   end
229
230   ltjb.to_dimen = to_dimen
231   ltjb.dump_skip = dump_skip
232   ltjb.to_skip = to_skip
233 end
234
235 -------------------- Virtual table for LaTeX counters
236 -- not used in current LuaTeX-ja
237 do
238 --! ixbase.counter と同じ
239   counter = {}
240   local mt_counter = {}
241   setmetatable(counter, mt_counter)
242
243   function mt_counter.__index(tbl, key)
244     return tex.count['c@'..key]
245   end
246   function mt_counter.__newindex(tbl, key, val)
247     tex.count['c@'..key] = val
248   end
249   ltjb.counter = counter
250
251 --! ixbase.length は tex.skip と全く同じなので不要.
252 end
253
254 -------------------- common error message
255 do
256    local function in_unicode(c, admit_math)
257       local low = admit_math and -1 or 0
258       if type(c)~='number' or c<low or c>0x10FFFF then
259          local s = 'A character number must be between ' .. tostring(low) 
260             .. ' and 0x10ffff.\n'
261             .. (admit_math and "(-1 is used for denoting `math boundary')\n" or '')
262             .. 'So I changed this one to zero.'
263          package_error('luatexja',
264                             'bad character code (' .. tostring(c) .. ')', s)
265          c=0
266       end
267       return c
268    end
269    ltjb.in_unicode = in_unicode
270 end
271
272 -------------------- cache management
273 -- load_cache (filename, outdate)
274 --   * filename: without suffix '.lua'
275 --   * outdate(t): return true iff the cache is outdated
276 --   * return value: non-nil iff the cache is up-to-date
277 -- save_cache (filename, t): no return value
278 -- save_cache_luc (filename, t): no return value
279 --   save_cache always calls save_cache_luc. 
280 --   But sometimes we want to create only the precompiled cache,
281 --   when its 'text' version is already present in LuaTeX-ja distribution.
282
283 require('lualibs-lpeg') -- string.split
284 require('lualibs-os')   -- os.type
285
286 do
287    local kpse_var_value = kpse.var_value
288    local path, pathtmp = kpse_var_value("TEXMFVAR")
289    pathtmp = kpse_var_value("TEXMFSYSVAR")
290    if pathtmp then path = (path and path .. ';' or '') .. pathtmp end
291    pathtmp = kpse_var_value("TEXMFCACHE")
292    if pathtmp then path = (path and path .. ';' or '') .. pathtmp end
293
294    if os.type~='windows' then path = string.gsub(path, ':', ';') end
295    path = table.unique(string.split(path, ';'))
296
297    local cache_dir = '/luatexja'
298    local find_file = kpse.find_file
299    local join, isreadable = file.join, file.isreadable
300    local tofile, serialize = table.tofile, table.serialize
301    local luc_suffix = jit and '.lub' or '.luc'
302
303    -- determine save path
304    local savepath = ''
305    for _,v in pairs(path) do
306       local testpath =  join(v, cache_dir)
307       if not lfs.isdir(testpath) then dir.mkdirs(testpath) end
308       if lfs.isdir(testpath) then savepath = testpath; break end
309    end
310
311    save_cache_luc = function (filename, t, serialized)
312       local fullpath = savepath .. '/' ..  filename .. luc_suffix
313       local s = serialized or serialize(t, 'return', false)
314       if s then
315          local sa = load(s)
316          local f = io.open(fullpath, 'wb')
317          if f and sa then 
318             f:write(string.dump(sa, true)) 
319             texio.write('(save cache: ' .. fullpath .. ')')
320          end
321          f:close()
322       end
323    end
324
325    save_cache = function (filename, t)
326       local fullpath = savepath .. '/' ..  filename .. '.lua'
327       local s = serialize(t, 'return', false)
328       if s then
329          local f = io.open(fullpath, 'w')
330          if f then 
331             f:write(s) 
332             texio.write('(save cache: ' .. fullpath .. ')')
333          end
334          f:close()
335          save_cache_luc(filename, t, s)
336       end
337    end
338
339    local function load_cache_a (filename, outdate)
340       local result
341       for _,v in pairs(path) do
342          local fn = join(v, cache_dir, filename)
343          if isreadable(fn) then 
344             texio.write('(load cache: ' .. fn .. ')')
345             result = loadfile(fn)
346             result = result and result(); break
347          end
348       end
349       if (not result) or outdate(result) then 
350          return nil 
351       else 
352          return result 
353       end
354    end
355    
356    load_cache = function (filename, outdate)
357       local r = load_cache_a(filename ..  luc_suffix, outdate)
358       if r then 
359          return r
360       else
361          local r = load_cache_a(filename .. '.lua', outdate)
362          if r then save_cache_luc(filename, r) end -- update the precompiled cache
363          return r
364       end
365    end
366
367    ltjb.load_cache = load_cache
368    ltjb.save_cache_luc = save_cache_luc
369    ltjb.save_cache = save_cache
370 end
371
372 ----
373 do
374    local tex_set_attr, tex_get_attr = tex.setattribute, tex.getattribute
375    function ltjb.ensure_tex_attr(a, v)
376       if tex_get_attr(a)~=v then
377          tex_set_attr(a, v)
378       end
379    end
380 end
381 ----
382
383 ltjb._error_set_break = _error_set_break
384 ltjb._error_set_message = _error_set_message
385 ltjb._error_show = _error_show
386 ltjb._generic_warn_info = _generic_warn_info
387
388 ltjb.package_error = package_error
389 ltjb.package_warning = package_warning
390 ltjb.package_warning_no_line = package_warning_no_line
391 ltjb.package_info = package_info
392 ltjb.package_info_no_line = package_info_no_line
393
394 ltjb.generic_error = generic_error
395 ltjb.generic_warning = generic_warning
396 ltjb.generic_warning_no_line = generic_warning_no_line
397 ltjb.generic_info = generic_info
398 ltjb.generic_info_no_line = generic_info_no_line
399
400 ltjb.ltj_warning_no_line = ltj_warning_no_line
401 ltjb.ltj_error = ltj_error
402
403 ---- deterministic version of luatexbase.add_to_callback
404 function ltjb.add_to_callback(name,fun,description,priority)
405     local priority= priority
406     if priority==nil then
407         priority=#luatexbase.callback_descriptions(name)+1
408     end
409     if(luatexbase.callbacktypes[name] == 3 and
410     priority == 1 and
411     #luatexbase.callback_descriptions(name)==1) then
412         luatexbase.module_warning("luatexbase",
413         "resetting exclusive callback: " .. name)
414         luatexbase.reset_callback(name)
415     end
416     local saved_callback={},ff,dd
417     for k,v in ipairs(luatexbase.callback_descriptions(name)) do
418         if k >= priority then
419             ff,dd= luatexbase.remove_from_callback(name, v)
420             saved_callback[#saved_callback+1]={ff,dd}
421         end
422     end
423     luatexbase.base_add_to_callback(name,fun,description)
424     for _,v in ipairs(saved_callback) do
425         luatexbase.base_add_to_callback(name,v[1],v[2])
426     end
427     return
428 end
429
430 -------------------- mock of debug logger
431 if not ltjb.out_debug then
432    local function no_op() end
433    ltjb.start_time_measure = no_op
434    ltjb.stop_time_measure = no_op
435    ltjb.out_debug = no_op
436    ltjb.package_debug = no_op
437    ltjb.debug_logger = function() return no_op end
438    ltjb.show_term = no_op
439    ltjb.show_log = no_op
440 end
441
442 -------------------- all done
443 -- EOF